source: trunk/gui/scripts/flowvisviewer.tcl @ 1463

Last change on this file since 1463 was 1463, checked in by gah, 12 years ago
File size: 89.2 KB
Line 
1
2# ----------------------------------------------------------------------
3#  COMPONENT: flowvisviewer - 3D flow rendering
4#
5#
6# This widget performs volume and flow rendering on 3D scalar/vector datasets.
7# It connects to the Flowvis server running on a rendering farm, transmits
8# data, and displays the results.
9#
10# ======================================================================
11#  AUTHOR:  Michael McLennan, Purdue University
12#  Copyright (c) 2004-2005  Purdue Research Foundation
13#
14# See the file "license.terms" for information on usage and redistribution of
15# this file, and for a DISCLAIMER OF ALL WARRANTIES.
16# ======================================================================
17package require Itk
18package require BLT
19package require Img
20
21option add *FlowvisViewer.width 5i widgetDefault
22option add *FlowvisViewer*cursor crosshair widgetDefault
23option add *FlowvisViewer.height 4i widgetDefault
24option add *FlowvisViewer.foreground black widgetDefault
25option add *FlowvisViewer.controlBackground gray widgetDefault
26option add *FlowvisViewer.controlDarkBackground #999999 widgetDefault
27option add *FlowvisViewer.plotBackground black widgetDefault
28option add *FlowvisViewer.plotForeground white widgetDefault
29option add *FlowvisViewer.plotOutline gray widgetDefault
30option add *FlowvisViewer.font \
31    -*-helvetica-medium-r-normal-*-12-* widgetDefault
32
33# must use this name -- plugs into Rappture::resources::load
34proc FlowvisViewer_init_resources {} {
35    Rappture::resources::register \
36        nanovis_server Rappture::FlowvisViewer::SetServerList
37}
38
39itcl::class Rappture::FlowvisViewer {
40    inherit Rappture::VisViewer
41
42    itk_option define -plotforeground plotForeground Foreground ""
43    itk_option define -plotbackground plotBackground Background ""
44    itk_option define -plotoutline plotOutline PlotOutline ""
45
46    constructor { hostlist args } {
47        Rappture::VisViewer::constructor $hostlist
48    } {
49        # defined below
50    }
51    destructor {
52        # defined below
53    }
54    public proc SetServerList { namelist } {
55        Rappture::VisViewer::SetServerList "nanovis" $namelist
56    }
57    public method add {dataobj {settings ""}}
58    public method camera {option args}
59    public method delete {args}
60    public method download {option args}
61    public method flow {option}
62    public method get {args}
63    public method isconnected {}
64    public method limits { tf }
65    public method overmarker { m x }
66    public method parameters {title args} {
67        # do nothing
68    }
69    public method rmdupmarker { m x }
70    public method scale {args}
71    public method updatetransferfuncs {}
72
73    protected method Connect {}
74    protected method CurrentVolumeIds {{what -all}}
75    protected method Disconnect {}
76    protected method DoResize {}
77    protected method ResizeLegend {}
78    protected method FixSettings {what {value ""}}
79    protected method Pan {option x y}
80    protected method Rebuild {}
81    protected method ReceiveData { args }
82    protected method ReceiveImage { args }
83    protected method ReceiveLegend { tf vmin vmax size }
84    protected method Rotate {option x y}
85    protected method SendCmd {string}
86    protected method SendDataObjs {}
87    protected method SendTransferFuncs {}
88    protected method Slice {option args}
89    protected method SlicerTip {axis}
90    protected method Zoom {option}
91
92    # soon to be removed.
93    protected method Flow {option args}
94    protected method Play {}
95    protected method Pause {}
96
97
98    # The following methods are only used by this class.
99
100    private method AddIsoMarker { x y }
101    private method BuildCameraTab {}
102    private method BuildCutplanesTab {}
103    private method BuildViewTab {}
104    private method BuildVolumeTab {}
105    private method ComputeTransferFunc { tf }
106    private method EventuallyResize { w h }
107    private method EventuallyResizeLegend { }
108    private method FlowCmd { dataobj comp nbytes extents }
109    private method GetMovie { widget width height }
110    private method NameTransferFunc { dataobj comp }
111    private method PanCamera {}
112    private method ParseLevelsOption { tf levels }
113    private method ParseMarkersOption { tf markers }
114    private method WaitIcon { option widget }
115
116    private method GetFlowInfo { widget }
117    private method particles { tag name }
118    private method box { tag name }
119    private method streams { tag name }
120
121    private variable _outbuf       ;# buffer for outgoing commands
122
123    private variable _dlist ""     ;# list of data objects
124    private variable _allDataObjs
125    private variable _obj2ovride   ;# maps dataobj => style override
126    private variable _obj2id       ;# maps dataobj-component to volume ID
127                                    # in the server
128    private variable _id2obj       ;# maps dataobj => volume ID in server
129    private variable _sendobjs ""  ;# list of data objs to send to server
130    private variable _recvObjs  ;# list of data objs to send to server
131    private variable _obj2style    ;# maps dataobj-component to transfunc
132    private variable _style2objs   ;# maps tf back to list of
133                                    # dataobj-components using the tf.
134    private variable _obj2flow;         # Maps dataobj-component to a flow.
135
136    private variable _click        ;# info used for rotate operations
137    private variable _limits       ;# autoscale min/max for all axes
138    private variable _view         ;# view params for 3D view
139    private variable _isomarkers    ;# array of isosurface level values 0..1
140    private common   _settings
141    private variable _activeTf ""  ;# The currently active transfer function.
142    private variable _first ""     ;# This is the topmost volume.
143    private variable _buffering 0
144    private variable _flow
145    # This
146    # indicates which isomarkers and transfer
147    # function to use when changing markers,
148    # opacity, or thickness.
149    common _downloadPopup          ;# download options from popup
150
151    private common _hardcopy
152    private variable _width 0
153    private variable _height 0
154    private variable _resizePending 0
155    private variable _resizeLegendPending 0
156}
157
158itk::usual FlowvisViewer {
159    keep -background -foreground -cursor -font
160    keep -plotbackground -plotforeground
161}
162
163# ----------------------------------------------------------------------
164# CONSTRUCTOR
165# ----------------------------------------------------------------------
166itcl::body Rappture::FlowvisViewer::constructor { hostlist args } {
167
168    # Draw legend event
169    $_dispatcher register !legend
170    $_dispatcher dispatch $this !legend "[itcl::code $this ResizeLegend]; list"
171
172    # Send dataobjs event
173    $_dispatcher register !send_dataobjs
174    $_dispatcher dispatch $this !send_dataobjs \
175        "[itcl::code $this SendDataObjs]; list"
176
177    # Send transferfunctions event
178    $_dispatcher register !send_transfunc
179    $_dispatcher dispatch $this !send_transfunc \
180        "[itcl::code $this SendTransferFuncs]; list"
181
182    # Rebuild event.
183    $_dispatcher register !rebuild
184    $_dispatcher dispatch $this !rebuild "[itcl::code $this Rebuild]; list"
185
186    # Resize event.
187    $_dispatcher register !resize
188    $_dispatcher dispatch $this !resize "[itcl::code $this DoResize]; list"
189
190    $_dispatcher register !play
191    $_dispatcher dispatch $this !play "[itcl::code $this flow next]; list"
192   
193    set _flow(state) 0
194
195    set _outbuf ""
196
197    array set _downloadPopup {
198        format draft
199    }
200    #
201    # Populate parser with commands handle incoming requests
202    #
203    $_parser alias image [itcl::code $this ReceiveImage]
204    $_parser alias legend [itcl::code $this ReceiveLegend]
205    $_parser alias data [itcl::code $this ReceiveData]
206
207    # Initialize the view to some default parameters.
208    array set _view {
209        theta   45
210        phi     45
211        psi     0
212        zoom    1.0
213        pan-x   0
214        pan-y   0
215    }
216    set _obj2id(count) 0
217    set _id2obj(count) 0
218    set _limits(vmin) 0.0
219    set _limits(vmax) 1.0
220
221    array set _settings [subst {
222        $this-loop              0
223        $this-pan-x             $_view(pan-x)
224        $this-pan-y             $_view(pan-y)
225        $this-phi               $_view(phi)
226        $this-play              0
227        $this-psi               $_view(psi)
228        $this-step              0
229        $this-speed             500
230        $this-duration          1:00
231        $this-theta             $_view(theta)
232        $this-volume            1
233        $this-xcutplane         0
234        $this-xcutposition      0
235        $this-ycutplane         0
236        $this-ycutposition      0
237        $this-zcutplane         0
238        $this-zcutposition      0
239        $this-zoom              $_view(zoom)
240    }]
241
242    set f [$itk_component(main) component controls]
243    itk_component add reset {
244        button $f.reset -borderwidth 1 -padx 1 -pady 1 \
245            -highlightthickness 0 \
246            -image [Rappture::icon reset-view] \
247            -command [itcl::code $this Zoom reset]
248    } {
249        usual
250        ignore -highlightthickness
251    }
252    pack $itk_component(reset) -side top -padx 2 -pady 2
253    Rappture::Tooltip::for $itk_component(reset) "Reset the view to the default zoom level"
254
255    itk_component add zoomin {
256        button $f.zin -borderwidth 1 -padx 1 -pady 1 \
257            -highlightthickness 0 \
258            -image [Rappture::icon zoom-in] \
259            -command [itcl::code $this Zoom in]
260    } {
261        usual
262        ignore -highlightthickness
263    }
264    pack $itk_component(zoomin) -side top -padx 2 -pady 2
265    Rappture::Tooltip::for $itk_component(zoomin) "Zoom in"
266
267    itk_component add zoomout {
268        button $f.zout -borderwidth 1 -padx 1 -pady 1 \
269            -highlightthickness 0 \
270            -image [Rappture::icon zoom-out] \
271            -command [itcl::code $this Zoom out]
272    } {
273        usual
274        ignore -highlightthickness
275    }
276    pack $itk_component(zoomout) -side top -padx 2 -pady 2
277    Rappture::Tooltip::for $itk_component(zoomout) "Zoom out"
278
279    itk_component add volume {
280        Rappture::PushButton $f.volume \
281            -onimage [Rappture::icon volume-on] \
282            -offimage [Rappture::icon volume-off] \
283            -command [itcl::code $this FixSettings volume] \
284            -variable [itcl::scope _settings($this-volume)]
285    }
286    $itk_component(volume) select
287    Rappture::Tooltip::for $itk_component(volume) \
288        "Toggle the volume cloud on/off"
289    pack $itk_component(volume) -padx 2 -pady 2
290
291    BuildViewTab
292    BuildVolumeTab
293    BuildCutplanesTab
294    BuildCameraTab
295
296
297    bind $itk_component(3dview) <Configure> \
298        [itcl::code $this EventuallyResize %w %h]
299
300    # Legend
301    set _image(legend) [image create photo]
302    itk_component add legend {
303        canvas $itk_component(plotarea).legend -height 50 -highlightthickness 0
304    } {
305        usual
306        ignore -highlightthickness
307        rename -background -plotbackground plotBackground Background
308    }
309    bind $itk_component(legend) <Configure> \
310        [itcl::code $this EventuallyResizeLegend]
311
312    # Hack around the Tk panewindow.  The problem is that the requested
313    # size of the 3d view isn't set until an image is retrieved from
314    # the server.  So the panewindow uses the tiny size.
315    set w 10000
316    pack forget $itk_component(3dview)
317    blt::table $itk_component(plotarea) \
318        0,0 $itk_component(3dview) -fill both -reqwidth $w \
319        1,0 $itk_component(legend) -fill x
320    blt::table configure $itk_component(plotarea) r1 -resize none   
321    # Create flow controls...
322
323    itk_component add flowcontrols {
324        frame $itk_interior.flowcontrols
325    } {
326        usual
327        rename -background -controlbackground controlBackground Background
328    }
329    pack forget $itk_component(main)
330    blt::table $itk_interior \
331        0,0 $itk_component(main) -fill both  \
332        1,0 $itk_component(flowcontrols) -fill x
333    blt::table configure $itk_interior r1 -resize none
334
335    # Rewind
336    itk_component add rewind {
337        button $itk_component(flowcontrols).reset \
338            -borderwidth 1 -padx 1 -pady 1 \
339            -image [Rappture::icon flow-rewind] \
340            -command [itcl::code $this flow reset]
341    } {
342        usual
343        ignore -borderwidth
344        rename -highlightbackground -controlbackground controlBackground \
345            Background
346    }
347    Rappture::Tooltip::for $itk_component(rewind) \
348        "Rewind flow"
349
350    # Stop
351    itk_component add stop {
352        button $itk_component(flowcontrols).stop \
353            -borderwidth 1 -padx 1 -pady 1 \
354            -image [Rappture::icon flow-stop] \
355            -command [itcl::code $this flow stop]
356    } {
357        usual
358        ignore -borderwidth
359        rename -highlightbackground -controlbackground controlBackground \
360            Background
361    }
362    Rappture::Tooltip::for $itk_component(stop) \
363        "Stop flow"
364
365    # Play
366    itk_component add play {
367        Rappture::PushButton $itk_component(flowcontrols).play \
368            -onimage [Rappture::icon flow-pause] \
369            -offimage [Rappture::icon flow-play] \
370            -variable [itcl::scope _settings($this-play)] \
371            -command [itcl::code $this flow toggle]
372    }
373    set fg [option get $itk_component(hull) font Font]
374    Rappture::Tooltip::for $itk_component(play) \
375        "Play/Pause flow"
376
377    # Loop
378    itk_component add loop {
379        Rappture::PushButton $itk_component(flowcontrols).loop \
380            -onimage [Rappture::icon flow-loop] \
381            -offimage [Rappture::icon flow-loop] \
382            -variable [itcl::scope _settings($this-loop)]
383    }
384    Rappture::Tooltip::for $itk_component(loop) \
385        "Play continuously"
386
387    # Frame
388    itk_component add frame {
389        ::scale $itk_component(flowcontrols).frame -from 1 -to 100 \
390            -showvalue 0 -orient horizontal -width 14 \
391            -state disabled \
392            -variable [itcl::scope _settings($this-currenttime)]  \
393            -highlightthickness 0
394    } {
395        usual
396        ignore -highlightthickness
397        rename -background -controlbackground controlBackground Background
398    }
399    $itk_component(frame) set 1
400
401    itk_component add dial {
402        Rappture::Radiodial $itk_component(flowcontrols).dial \
403            -length 10 -valuewidth 0 -valuepadding 0 -padding 6 \
404            -linecolor "" -activelinecolor "" \
405            -knobimage [Rappture::icon knob2] -knobposition center@middle
406    } {
407        usual
408        keep -dialprogresscolor
409        rename -background -controlbackground controlBackground Background
410    }
411    grid $itk_component(dial) -row 1 -column 1 -sticky ew
412    bind $itk_component(dial) <<Value>> [itcl::code $this _fixValue]
413
414    # Duration
415    itk_component add duration {
416        entry $itk_component(flowcontrols).duration \
417            -textvariable [itcl::scope _settings($this-duration)] \
418            -bg white -width 6
419    } {
420        usual
421        ignore -highlightthickness -background
422    }
423    bind $itk_component(duration) <Return> [itcl::code $this flow duration]
424
425    itk_component add durationlabel {
426        label $itk_component(flowcontrols).durationl \
427            -text "Duration:" -font $fg \
428            -highlightthickness 0
429    } {
430        usual
431        ignore -highlightthickness
432        rename -background -controlbackground controlBackground Background
433    }
434
435    itk_component add speedlabel {
436        label $itk_component(flowcontrols).speedl -text "Speed:" -font $fg \
437            -highlightthickness 0
438    } {
439        usual
440        ignore -highlightthickness
441        rename -background -controlbackground controlBackground Background
442    }
443
444    # Speed
445    itk_component add speed {
446        Rappture::Spinint $itk_component(flowcontrols).speed \
447            -min 1 -max 10 -width 2
448    } {
449        usual
450        ignore -highlightthickness
451        rename -background -controlbackground controlBackground Background
452    }
453    $itk_component(speed) value 1
454    bind $itk_component(speed) <<Value>> [itcl::code $this flow speed]
455
456
457    blt::table $itk_component(flowcontrols) \
458        0,0 $itk_component(rewind) -padx {3 0} \
459        0,1 $itk_component(stop) -padx {2 0} \
460        0,2 $itk_component(play) -padx {2 0} \
461        0,3 $itk_component(loop) -padx {2 0} \
462        0,4 $itk_component(dial) -fill x -padx {2 0 } \
463        0,5 $itk_component(speedlabel) -padx {2 0} \
464        0,6 $itk_component(speed) -padx {2 0} \
465        0,7 $itk_component(durationlabel) -padx {2 0} \
466        0,8 $itk_component(duration) -padx { 2 3}
467
468    blt::table configure $itk_component(flowcontrols) c* -resize none
469    blt::table configure $itk_component(flowcontrols) c4 -resize both
470    blt::table configure $itk_component(flowcontrols) r0 -pady 1
471    # Bindings for rotation via mouse
472    bind $itk_component(3dview) <ButtonPress-1> \
473        [itcl::code $this Rotate click %x %y]
474    bind $itk_component(3dview) <B1-Motion> \
475        [itcl::code $this Rotate drag %x %y]
476    bind $itk_component(3dview) <ButtonRelease-1> \
477        [itcl::code $this Rotate release %x %y]
478
479    bind $itk_component(3dview) <Configure> \
480        [itcl::code $this EventuallyResize %w %h]
481
482    # Bindings for panning via mouse
483    bind $itk_component(3dview) <ButtonPress-2> \
484        [itcl::code $this Pan click %x %y]
485    bind $itk_component(3dview) <B2-Motion> \
486        [itcl::code $this Pan drag %x %y]
487    bind $itk_component(3dview) <ButtonRelease-2> \
488        [itcl::code $this Pan release %x %y]
489
490    # Bindings for panning via keyboard
491    bind $itk_component(3dview) <KeyPress-Left> \
492        [itcl::code $this Pan set -10 0]
493    bind $itk_component(3dview) <KeyPress-Right> \
494        [itcl::code $this Pan set 10 0]
495    bind $itk_component(3dview) <KeyPress-Up> \
496        [itcl::code $this Pan set 0 -10]
497    bind $itk_component(3dview) <KeyPress-Down> \
498        [itcl::code $this Pan set 0 10]
499    bind $itk_component(3dview) <Shift-KeyPress-Left> \
500        [itcl::code $this Pan set -2 0]
501    bind $itk_component(3dview) <Shift-KeyPress-Right> \
502        [itcl::code $this Pan set 2 0]
503    bind $itk_component(3dview) <Shift-KeyPress-Up> \
504        [itcl::code $this Pan set 0 -2]
505    bind $itk_component(3dview) <Shift-KeyPress-Down> \
506        [itcl::code $this Pan set 0 2]
507
508    # Bindings for zoom via keyboard
509    bind $itk_component(3dview) <KeyPress-Prior> \
510        [itcl::code $this Zoom out]
511    bind $itk_component(3dview) <KeyPress-Next> \
512        [itcl::code $this Zoom in]
513
514    bind $itk_component(3dview) <Enter> "focus $itk_component(3dview)"
515
516    if {[string equal "x11" [tk windowingsystem]]} {
517        # Bindings for zoom via mouse
518        bind $itk_component(3dview) <4> [itcl::code $this Zoom out]
519        bind $itk_component(3dview) <5> [itcl::code $this Zoom in]
520    }
521
522    set _image(download) [image create photo]
523
524    eval itk_initialize $args
525
526    Connect
527}
528
529# ----------------------------------------------------------------------
530# DESTRUCTOR
531# ----------------------------------------------------------------------
532itcl::body Rappture::FlowvisViewer::destructor {} {
533    set _sendobjs ""  ;# stop any send in progress
534    $_dispatcher cancel !rebuild
535    $_dispatcher cancel !send_dataobjs
536    $_dispatcher cancel !send_transfunc
537    image delete $_image(plot)
538    image delete $_image(legend)
539    image delete $_image(download)
540    array unset _settings $this-*
541}
542
543# ----------------------------------------------------------------------
544# USAGE: add <dataobj> ?<settings>?
545#
546# Clients use this to add a data object to the plot.  The optional
547# <settings> are used to configure the plot.  Allowed settings are
548# -color, -brightness, -width, -linestyle, and -raise.
549# ----------------------------------------------------------------------
550itcl::body Rappture::FlowvisViewer::add {dataobj {settings ""}} {
551    array set params {
552        -color auto
553        -width 1
554        -linestyle solid
555        -brightness 0
556        -raise 0
557        -description ""
558        -param ""
559    }
560    foreach {opt val} $settings {
561        if {![info exists params($opt)]} {
562            error "bad setting \"$opt\": should be [join [lsort [array names params]] {, }]"
563        }
564        set params($opt) $val
565    }
566    if {$params(-color) == "auto" || $params(-color) == "autoreset"} {
567        # can't handle -autocolors yet
568        set params(-color) black
569    }
570    foreach comp [$dataobj components] {
571        set flowobj [$dataobj flowhints $comp]
572        if { $flowobj == "" } {
573            puts stderr "no flowhints $dataobj-$comp"
574            continue
575        }
576        set _obj2flow($dataobj-$comp) $flowobj
577    }
578    set pos [lsearch -exact $dataobj $_dlist]
579    if {$pos < 0} {
580        lappend _dlist $dataobj
581        set _allDataObjs($dataobj) 1
582        set _obj2ovride($dataobj-color) $params(-color)
583        set _obj2ovride($dataobj-width) $params(-width)
584        set _obj2ovride($dataobj-raise) $params(-raise)
585        $_dispatcher event -idle !rebuild
586    }
587}
588
589# ----------------------------------------------------------------------
590# USAGE: get ?-objects?
591# USAGE: get ?-image 3dview|legend?
592#
593# Clients use this to query the list of objects being plotted, in
594# order from bottom to top of this result.  The optional "-image"
595# flag can also request the internal images being shown.
596# ----------------------------------------------------------------------
597itcl::body Rappture::FlowvisViewer::get {args} {
598    if {[llength $args] == 0} {
599        set args "-objects"
600    }
601
602    set op [lindex $args 0]
603    switch -- $op {
604      -objects {
605        # put the dataobj list in order according to -raise options
606        set dlist $_dlist
607        foreach obj $dlist {
608            if {[info exists _obj2ovride($obj-raise)] && $_obj2ovride($obj-raise)} {
609                set i [lsearch -exact $dlist $obj]
610                if {$i >= 0} {
611                    set dlist [lreplace $dlist $i $i]
612                    lappend dlist $obj
613                }
614            }
615        }
616        return $dlist
617      }
618      -image {
619        if {[llength $args] != 2} {
620            error "wrong # args: should be \"get -image 3dview|legend\""
621        }
622        switch -- [lindex $args end] {
623            3dview {
624                return $_image(plot)
625            }
626            legend {
627                return $_image(legend)
628            }
629            default {
630                error "bad image name \"[lindex $args end]\": should be 3dview or legend"
631            }
632        }
633      }
634      default {
635        error "bad option \"$op\": should be -objects or -image"
636      }
637    }
638}
639
640# ----------------------------------------------------------------------
641# USAGE: delete ?<dataobj1> <dataobj2> ...?
642#
643#       Clients use this to delete a dataobj from the plot.  If no dataobjs
644#       are specified, then all dataobjs are deleted.  No data objects are
645#       deleted.  They are only removed from the display list.
646#
647# ----------------------------------------------------------------------
648itcl::body Rappture::FlowvisViewer::delete {args} {
649     flow stop
650    if {[llength $args] == 0} {
651        set args $_dlist
652    }
653
654    # Delete all specified dataobjs
655    set changed 0
656    foreach dataobj $args {
657        set pos [lsearch -exact $_dlist $dataobj]
658        if { $pos >= 0 } {
659            foreach comp [$dataobj components] {
660                if { [info exists obj2id($dataobj-$comp)] } {
661                    set ivol $_obj2id($dataobj-$comp)
662                    array unset _limits $ivol-*
663                }
664            }
665            set _dlist [lreplace $_dlist $pos $pos]
666            array unset _obj2ovride $dataobj-*
667            array unset _obj2flow $dataobj-*
668            array unset _obj2id $dataobj-*
669            array unset _obj2style $dataobj-*
670            set changed 1
671        }
672    }
673    # If anything changed, then rebuild the plot
674    if {$changed} {
675        # Repair the reverse lookup
676        foreach tf [array names _style2objs] {
677            set list {}
678            foreach {dataobj comp} $_style2objs($tf) break
679            if { [info exists _obj2id($dataobj-$comp)] } {
680                lappend list $dataobj $comp
681            }
682            if { $list == "" } {
683                array unset _style2objs $tf
684            } else {
685                set _style2objs($tf) $list
686            }
687        }
688        $_dispatcher event -idle !rebuild
689    }
690}
691
692# ----------------------------------------------------------------------
693# USAGE: scale ?<data1> <data2> ...?
694#
695# Sets the default limits for the overall plot according to the
696# limits of the data for all of the given <data> objects.  This
697# accounts for all objects--even those not showing on the screen.
698# Because of this, the limits are appropriate for all objects as
699# the user scans through data in the ResultSet viewer.
700# ----------------------------------------------------------------------
701itcl::body Rappture::FlowvisViewer::scale {args} {
702    foreach val {xmin xmax ymin ymax zmin zmax vmin vmax} {
703        set _limits($val) ""
704    }
705    foreach obj $args {
706        foreach axis {x y z v} {
707
708            foreach { min max } [$obj limits $axis] break
709
710            if {"" != $min && "" != $max} {
711                if {"" == $_limits(${axis}min)} {
712                    set _limits(${axis}min) $min
713                    set _limits(${axis}max) $max
714                } else {
715                    if {$min < $_limits(${axis}min)} {
716                        set _limits(${axis}min) $min
717                    }
718                    if {$max > $_limits(${axis}max)} {
719                        set _limits(${axis}max) $max
720                    }
721                }
722            }
723        }
724    }
725}
726
727# ----------------------------------------------------------------------
728# USAGE: download coming
729# USAGE: download controls <downloadCommand>
730# USAGE: download now
731#
732# Clients use this method to create a downloadable representation
733# of the plot.  Returns a list of the form {ext string}, where
734# "ext" is the file extension (indicating the type of data) and
735# "string" is the data itself.
736# ----------------------------------------------------------------------
737itcl::body Rappture::FlowvisViewer::download {option args} {
738    switch $option {
739        coming {
740            if {[catch {
741                blt::winop snap $itk_component(plotarea) $_image(download)
742            }]} {
743                $_image(download) configure -width 1 -height 1
744                $_image(download) put #000000
745            }
746        }
747        controls {
748            set popup .flowvisviewerdownload
749            if {![winfo exists .flowvisviewerdownload]} {
750                # if we haven't created the popup yet, do it now
751                Rappture::Balloon $popup \
752                    -title "[Rappture::filexfer::label downloadWord] as..."
753                set inner [$popup component inner]
754                label $inner.summary -text "" -anchor w
755                pack $inner.summary -side top
756                set img $_image(plot)
757                set res "[image width $img]x[image height $img]"
758                radiobutton $inner.draft -text "Image (draft $res)" \
759                    -variable Rappture::MolvisViewer::_downloadPopup(format) \
760                    -value draft
761                pack $inner.draft -anchor w
762
763                set res "640x480"
764                radiobutton $inner.medium -text "Movie (standard $res)" \
765                    -variable Rappture::MolvisViewer::_downloadPopup(format) \
766                    -value $res
767                pack $inner.medium -anchor w
768
769                set res "1024x768"
770                radiobutton $inner.high -text "Movie (high quality $res)" \
771                    -variable Rappture::MolvisViewer::_downloadPopup(format) \
772                    -value $res
773                pack $inner.high -anchor w
774                button $inner.go -text [Rappture::filexfer::label download] \
775                    -command [lindex $args 0]
776                pack $inner.go -pady 4
777                $inner.draft select
778            } else {
779                set inner [$popup component inner]
780            }
781            set num [llength [get]]
782            set num [expr {($num == 1) ? "1 result" : "$num results"}]
783            $inner.summary configure -text "[Rappture::filexfer::label downloadWord] $num in the following format:"
784            update idletasks ;# fix initial sizes
785            return $popup
786        }
787        now {
788            set popup .molvisviewerdownload
789            if {[winfo exists .molvisviewerdownload]} {
790                $popup deactivate
791            }
792            switch -- $_downloadPopup(format) {
793                draft {
794                    # Get the image data (as base64) and decode it back to
795                    # binary.  This is better than writing to temporary
796                    # files.  When we switch to the BLT picture image it
797                    # won't be necessary to decode the image data.
798                    set bytes [$_image(plot) data -format "jpeg -quality 100"]
799                    set data [Rappture::encoding::decode -as b64 $data]
800                    return [list .jpg $data]
801                }
802                "640x480" {
803                    return [$this GetMovie [lindex $args 0] 640 480]
804                }
805                "1024x768" {
806                    return [$this GetMovie [lindex $args 0] 1024 768]
807                }
808            }
809        }
810        default {
811            error "bad option \"$option\": should be coming, controls, now"
812        }
813    }
814}
815
816# ----------------------------------------------------------------------
817# USAGE: Connect ?<host:port>,<host:port>...?
818#
819# Clients use this method to establish a connection to a new
820# server, or to reestablish a connection to the previous server.
821# Any existing connection is automatically closed.
822# ----------------------------------------------------------------------
823itcl::body Rappture::FlowvisViewer::Connect {} {
824    set _hosts [GetServerList "nanovis"]
825    if { "" == $_hosts } {
826        return 0
827    }
828    set result [VisViewer::Connect $_hosts]
829    if { $result } {
830        set w [winfo width $itk_component(3dview)]
831        set h [winfo height $itk_component(3dview)]
832        EventuallyResize $w $h
833    }
834    return $result
835}
836
837#
838# isconnected --
839#
840#       Indicates if we are currently connected to the visualization server.
841#
842itcl::body Rappture::FlowvisViewer::isconnected {} {
843    return [VisViewer::IsConnected]
844}
845
846#
847# Disconnect --
848#
849#       Clients use this method to disconnect from the current rendering
850#       server.
851#
852itcl::body Rappture::FlowvisViewer::Disconnect {} {
853    VisViewer::Disconnect
854
855    # disconnected -- no more data sitting on server
856    set _outbuf ""
857    catch {unset _obj2id}
858    array unset _id2obj
859    set _obj2id(count) 0
860    set _id2obj(count) 0
861    set _sendobjs ""
862}
863
864#
865# SendCmd
866#
867#       Send commands off to the rendering server.  If we're currently
868#       sending data objects to the server, buffer the commands to be
869#       sent later.
870#
871itcl::body Rappture::FlowvisViewer::SendCmd { string } {
872    if { $_buffering } {
873        append _outbuf $string "\n"
874    } else {
875        foreach line [split $string \n] {
876            SendEcho >>line $line
877        }
878        SendBytes "$string\n"
879    }
880}
881
882# ----------------------------------------------------------------------
883# USAGE: SendDataObjs
884#
885# Used internally to send a series of volume objects off to the
886# server.  Sends each object, a little at a time, with updates in
887# between so the interface doesn't lock up.
888# ----------------------------------------------------------------------
889itcl::body Rappture::FlowvisViewer::SendDataObjs {} {
890    puts stderr "in SendDataObjs"
891
892    blt::busy hold $itk_component(hull); update idletasks
893    foreach dataobj $_sendobjs {
894        foreach comp [$dataobj components] {
895            # Send the data as one huge base64-encoded mess -- yuck!
896            set data [$dataobj blob $comp]
897            set nbytes [string length $data]
898            set extents [$dataobj extents $comp]
899            # I have a field. Is a vector field or a volume field?
900            if { $extents == 1 } {
901                set cmd "volume data follows $nbytes $dataobj-$comp\n"
902            } else {
903                set cmd [FlowCmd $dataobj $comp $nbytes $extents]
904                if { $cmd == "" } {
905                    puts stderr "no command"
906                    continue
907                }
908            }
909            if { ![SendBytes $cmd] } {
910                    puts stderr "can't send"
911                return
912            }
913            if { ![SendBytes $data] } {
914                    puts stderr "can't send"
915                return
916            }
917            set ivol $_obj2id(count)
918            incr _obj2id(count)
919
920            NameTransferFunc $dataobj $comp
921            set _recvObjs($dataobj-$comp) 1
922        }
923    }
924    set _sendobjs ""
925    blt::busy release $itk_component(hull)
926
927    # Turn on buffering of commands to the server.  We don't want to
928    # be preempted by a server disconnect/reconnect (which automatically
929    # generates a new call to Rebuild).   
930    set _buffering 1
931
932    # activate the proper volume
933    set _first [lindex [get] 0]
934    if { "" != $_first } {
935        set axis [$_first hints updir]
936        if {"" != $axis} {
937            SendCmd "up $axis"
938        }
939
940        if 0 {
941        set location [$_first hints camera]
942        if { $location != "" } {
943            array set _view $location
944        }
945        set _settings($this-theta) $_view(theta)
946        set _settings($this-phi)   $_view(phi)
947        set _settings($this-psi)   $_view(psi)
948        set _settings($this-pan-x) $_view(pan-x)
949        set _settings($this-pan-y) $_view(pan-y)
950        set _settings($this-zoom)  $_view(zoom)
951        set xyz [Euler2XYZ $_view(theta) $_view(phi) $_view(psi)]
952        SendCmd "camera angle $xyz"
953        PanCamera
954        SendCmd "camera zoom $_view(zoom)"
955        }
956        # The active transfer function is by default the first component of
957        # the first data object.  This assumes that the data is always
958        # successfully transferred.
959        set comp [lindex [$_first components] 0]
960        set _activeTf [lindex $_obj2style($_first-$comp) 0]
961    }
962
963    if 0 {
964    SendCmd "volume state 0"
965    set vols {}
966    foreach key [array names _obj2id $_first-*] {
967        lappend vols $_obj2id($key)
968    }
969    if { $vols != ""  && $_settings($this-volume) } {
970        SendCmd "volume state 1 $vols"
971    }
972    # sync the state of slicers
973    set vols [CurrentVolumeIds -cutplanes]
974    foreach axis {x y z} {
975        SendCmd "cutplane state $_settings($this-${axis}cutplane) $axis $vols"
976        set pos [expr {0.01*$_settings($this-${axis}cutposition)}]
977        SendCmd "cutplane position $pos $axis $vols"
978    }
979
980    # Add this when we fix grid for volumes
981    SendCmd "volume axis label x \"\""
982    SendCmd "volume axis label y \"\""
983    SendCmd "volume axis label z \"\""
984    SendCmd "grid axisname x X eV"
985    SendCmd "grid axisname y Y eV"
986    SendCmd "grid axisname z Z eV"
987    }
988
989    # Actually write the commands to the server socket.  If it fails, we don't
990    # care.  We're finished here.
991    SendBytes $_outbuf;                 
992    set _buffering 0;                   # Turn off buffering.
993    set _outbuf "";                     # Clear the buffer.             
994}
995
996# ----------------------------------------------------------------------
997# USAGE: SendTransferFuncs
998# ----------------------------------------------------------------------
999itcl::body Rappture::FlowvisViewer::SendTransferFuncs {} {
1000    if { $_activeTf == "" } {
1001        puts stderr "no active tf"
1002        return
1003    }
1004    set tf $_activeTf
1005    if { $_first == "" } {
1006        puts stderr "no first"
1007        return
1008    }
1009
1010    # Insure that the global opacity and thickness settings (in the slider
1011    # settings widgets) are used for the active transfer-function.  Update the
1012    # values in the _settings varible.
1013    set value $_settings($this-opacity)
1014    set opacity [expr { double($value) * 0.01 }]
1015    set _settings($this-$tf-opacity) $opacity
1016    set value $_settings($this-thickness)
1017    # Scale values between 0.00001 and 0.01000
1018    set thickness [expr {double($value) * 0.0001}]
1019    set _settings($this-$tf-thickness) $thickness
1020
1021    foreach key [array names _obj2style $_first-*] {
1022        if { [info exists _obj2style($key)] } {
1023            foreach tf $_obj2style($key) {
1024                ComputeTransferFunc $tf
1025            }
1026        }
1027    }
1028    ResizeLegend
1029}
1030
1031# ----------------------------------------------------------------------
1032# USAGE: ReceiveImage -bytes $size -type $type -token $token
1033#
1034# Invoked automatically whenever the "image" command comes in from
1035# the rendering server.  Indicates that binary image data with the
1036# specified <size> will follow.
1037# ----------------------------------------------------------------------
1038itcl::body Rappture::FlowvisViewer::ReceiveImage { args } {
1039    array set info {
1040        -token "???"
1041        -bytes 0
1042        -type image
1043    }
1044    array set info $args
1045    set bytes [ReceiveBytes $info(-bytes)]
1046    ReceiveEcho <<line "<read $info(-bytes) bytes"
1047    if { $info(-type) == "image" } {
1048        $_image(plot) configure -data $bytes
1049    } elseif { $info(type) == "print" } {
1050        set tag $this-print-$info(-token)
1051        set _hardcopy($tag) $bytes
1052    } elseif { $info(type) == "movie" } {
1053        set tag $this-movie-$info(-token)
1054        set _hardcopy($tag) $bytes
1055    }
1056}
1057
1058#
1059# ReceiveLegend --
1060#
1061#       The procedure is the response from the render server to each "legend"
1062#       command.  The server sends back a "legend" command invoked our
1063#       the slave interpreter.  The purpose is to collect data of the image
1064#       representing the legend in the canvas.  In addition, the isomarkers
1065#       of the active transfer function are displayed.
1066#
1067#       I don't know is this is the right place to display the isomarkers.
1068#       I don't know all the different paths used to draw the plot. There's
1069#       "Rebuild", "add", etc.
1070#
1071itcl::body Rappture::FlowvisViewer::ReceiveLegend { tf vmin vmax size } {
1072    if { ![isconnected] } {
1073        return
1074    }
1075    set bytes [ReceiveBytes $size]
1076    $_image(legend) configure -data $bytes
1077    ReceiveEcho <<line "<read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
1078
1079    set c $itk_component(legend)
1080    set w [winfo width $c]
1081    set h [winfo height $c]
1082    #foreach { dataobj comp } $_id2obj($ivol) break
1083    set lx 10
1084    set ly [expr {$h - 1}]
1085    if {"" == [$c find withtag transfunc]} {
1086        $c create image 10 10 -anchor nw \
1087            -image $_image(legend) -tags transfunc
1088        $c create text $lx $ly -anchor sw \
1089            -fill $itk_option(-plotforeground) -tags "limits vmin"
1090        $c create text [expr {$w-$lx}] $ly -anchor se \
1091            -fill $itk_option(-plotforeground) -tags "limits vmax"
1092        $c lower transfunc
1093        $c bind transfunc <ButtonRelease-1> \
1094            [itcl::code $this AddIsoMarker %x %y]
1095    }
1096    # Display the markers used by the active transfer function.
1097    #set tf $_activeTf
1098
1099    array set limits [limits $tf]
1100    $c itemconfigure vmin -text [format %.2g $limits(min)]
1101    $c coords vmin $lx $ly
1102
1103    $c itemconfigure vmax -text [format %.2g $limits(max)]
1104    $c coords vmax [expr {$w-$lx}] $ly
1105
1106    if { [info exists _isomarkers($tf)] } {
1107        foreach m $_isomarkers($tf) {
1108            $m visible yes
1109        }
1110    }
1111}
1112
1113#
1114# ReceiveData --
1115#
1116#       The procedure is the response from the render server to each "data
1117#       follows" command.  The server sends back a "data" command invoked our
1118#       the slave interpreter.  The purpose is to collect the min/max of the
1119#       volume sent to the render server.  Since the client (flowvisviewer)
1120#       doesn't parse 3D data formats, we rely on the server (flowvis) to
1121#       tell us what the limits are.  Once we've received the limits to all
1122#       the data we've sent (tracked by _recvObjs) we can then determine
1123#       what the transfer functions are for these # volumes.
1124#
1125#       Note: There is a considerable tradeoff in having the server report
1126#             back what the data limits are.  It means that much of the code
1127#             having to do with transfer-functions has to wait for the data
1128#             to come back, since the isomarkers are calculated based upon
1129#             the data limits.  The client code is much messier because of
1130#             this.  The alternative is to parse any of the 3D formats on the
1131#             client side.
1132#
1133itcl::body Rappture::FlowvisViewer::ReceiveData { args } {
1134    if { ![isconnected] } {
1135        return
1136    }
1137    # Arguments from server are name value pairs. Stuff them in an array.
1138    array set info $args
1139
1140    set ivol $info(id);         # Id of volume created by server.
1141    set tag $info(tag)
1142    set parts [split $tag -]
1143
1144    #
1145    # Volumes don't exist until we're told about them.
1146    #
1147    set _id2obj($ivol) $parts
1148    set dataobj [lindex $parts 0]
1149    set _obj2id($tag) $ivol
1150    # It's a lie. There's no volume yet.
1151    if { $_settings($this-volume) && $dataobj == $_first } {
1152        SendCmd "volume state 1"
1153    }
1154    set _limits($ivol-min) $info(min);  # Minimum value of the volume.
1155    set _limits($ivol-max) $info(max);  # Maximum value of the volume.
1156    set _limits(vmin)      $info(vmin); # Overall minimum value.
1157    set _limits(vmax)      $info(vmax); # Overall maximum value.
1158
1159    unset _recvObjs($tag)
1160    if { [array size _recvObjs] == 0 } {
1161        updatetransferfuncs
1162    }
1163}
1164
1165#
1166# Rebuild --
1167#
1168# Called automatically whenever something changes that affects the data
1169# in the widget.  Clears any existing data and rebuilds the widget to
1170# display new data. 
1171#
1172itcl::body Rappture::FlowvisViewer::Rebuild {} {
1173    #puts stderr "in Rebuild"
1174    # Hide all the isomarkers. Can't remove them. Have to remember the
1175    # settings since the user may have created/deleted/moved markers.
1176
1177    foreach tf [array names _isomarkers] {
1178        foreach m $_isomarkers($tf) {
1179            $m visible no
1180        }
1181    }
1182
1183    # in the midst of sending data? then bail out
1184    if {[llength $_sendobjs] > 0} {
1185        $_dispatcher event -idle !rebuild
1186        return
1187    }
1188
1189    # Turn on buffering of commands to the server.  We don't want to
1190    # be preempted by a server disconnect/reconnect (which automatically
1191    # generates a new call to Rebuild).   
1192    set _buffering 1
1193
1194    set w [winfo width $itk_component(3dview)]
1195    set h [winfo height $itk_component(3dview)]
1196    EventuallyResize $w $h
1197
1198    # Find any new data that needs to be sent to the server.  Queue this up on
1199    # the _sendobjs list, and send it out a little at a time.  Do this first,
1200    # before we rebuild the rest.
1201    foreach dataobj [get] {
1202        set comp [lindex [$dataobj components] 0]
1203        if {![info exists _obj2id($dataobj-$comp)]} {
1204            if { [lsearch -exact $_sendobjs $dataobj] < 0 } {
1205                lappend _sendobjs $dataobj
1206            }
1207        }
1208    }
1209
1210    #
1211    # Reset the camera and other view parameters
1212    #
1213    FixSettings light
1214    FixSettings transp
1215    FixSettings isosurface
1216    FixSettings grid
1217    FixSettings axes
1218    FixSettings outline
1219    # nothing to send -- activate the proper ivol
1220    set _first [lindex [get] 0]
1221    if {"" != $_first} {
1222        set axis [$_first hints updir]
1223        if {"" != $axis} {
1224            SendCmd "up $axis"
1225        }
1226        set location [$_first hints camera]
1227        if { $location != "" } {
1228            array set _view $location
1229        }
1230    }
1231    set _settings($this-theta) $_view(theta)
1232    set _settings($this-phi)   $_view(phi)
1233    set _settings($this-psi)   $_view(psi)
1234    set _settings($this-pan-x) $_view(pan-x)
1235    set _settings($this-pan-y) $_view(pan-y)
1236    set _settings($this-zoom)  $_view(zoom)
1237
1238    set xyz [Euler2XYZ $_view(theta) $_view(phi) $_view(psi)]
1239    SendCmd "camera angle $xyz"
1240    PanCamera
1241    SendCmd "camera zoom $_view(zoom)"
1242
1243    if {[llength $_sendobjs] > 0} {
1244        # send off new data objects
1245        $_dispatcher event -idle !send_dataobjs
1246        puts stderr "more sendobjs "
1247        return
1248    }
1249
1250    # nothing to send -- activate the proper ivol
1251    set _first [lindex [get] 0]
1252    if {"" != $_first} {
1253        set axis [$_first hints updir]
1254        if {"" != $axis} {
1255            SendCmd "up $axis"
1256        }
1257        set location [$_first hints camera]
1258        if { $location != "" } {
1259            array set _view $location
1260        }
1261        if { 0 && $_settings($this-volume) }  {
1262            SendCmd "volume state 0"
1263            foreach key [array names _obj2id $_first-*] {
1264                lappend vols $_obj2id($key)
1265            }
1266            SendCmd "volume state 1 $vols"
1267        }
1268        #
1269        # The _obj2id and _id2style arrays may or may not have the right
1270        # information.  It's possible for the server to know about volumes
1271        # that the client has assumed it's deleted.  We could add checks.
1272        # But this problem needs to be fixed not bandaided.
1273        set comp [lindex [$_first components] 0]
1274        set ivol $_obj2id($_first-$comp)
1275
1276    }
1277    foreach dataobj [get] {
1278        foreach comp [$_first components] {
1279            NameTransferFunc $dataobj $comp
1280        }
1281    }
1282
1283    # sync the state of slicers
1284    set vols [CurrentVolumeIds -cutplanes]
1285    foreach axis {x y z} {
1286        SendCmd "cutplane state $_settings($this-${axis}cutplane) $axis $vols"
1287        set pos [expr {0.01*$_settings($this-${axis}cutposition)}]
1288        SendCmd "cutplane position $pos $axis $vols"
1289    }
1290    SendCmd "volume data state $_settings($this-volume)"
1291    $_dispatcher event -idle !legend
1292
1293    # Actually write the commands to the server socket.  If it fails, we don't
1294    # care.  We're finished here.
1295    SendBytes $_outbuf;                 
1296    set _buffering 0;                   # Turn off buffering.
1297    set _outbuf "";                     # Clear the buffer.             
1298    #puts stderr "exit Rebuild"
1299}
1300
1301# ----------------------------------------------------------------------
1302# USAGE: CurrentVolumeIds ?-cutplanes?
1303#
1304# Returns a list of volume server IDs for the current volume being
1305# displayed.  This is normally a single ID, but it might be a list
1306# of IDs if the current data object has multiple components.
1307# ----------------------------------------------------------------------
1308itcl::body Rappture::FlowvisViewer::CurrentVolumeIds {{what -all}} {
1309    set rlist ""
1310    if { $_first == "" } {
1311        return
1312    }
1313    foreach key [array names _obj2id *-*] {
1314        if {[string match $_first-* $key]} {
1315            array set style {
1316                -cutplanes 1
1317            }
1318            foreach {dataobj comp} [split $key -] break
1319            array set style [lindex [$dataobj components -style $comp] 0]
1320
1321            if {$what != "-cutplanes" || $style(-cutplanes)} {
1322                lappend rlist $_obj2id($key)
1323            }
1324        }
1325    }
1326    return $rlist
1327}
1328
1329# ----------------------------------------------------------------------
1330# USAGE: Zoom in
1331# USAGE: Zoom out
1332# USAGE: Zoom reset
1333#
1334# Called automatically when the user clicks on one of the zoom
1335# controls for this widget.  Changes the zoom for the current view.
1336# ----------------------------------------------------------------------
1337itcl::body Rappture::FlowvisViewer::Zoom {option} {
1338    switch -- $option {
1339        "in" {
1340            set _view(zoom) [expr {$_view(zoom)*1.25}]
1341            set _settings($this-zoom) $_view(zoom)
1342        }
1343        "out" {
1344            set _view(zoom) [expr {$_view(zoom)*0.8}]
1345            set _settings($this-zoom) $_view(zoom)
1346        }
1347        "reset" {
1348            array set _view {
1349                theta   45
1350                phi     45
1351                psi     0
1352                zoom    1.0
1353                pan-x   0
1354                pan-y   0
1355            }
1356            if { $_first != "" } {
1357                set location [$_first hints camera]
1358                if { $location != "" } {
1359                    array set _view $location
1360                }
1361            }
1362            set xyz [Euler2XYZ $_view(theta) $_view(phi) $_view(psi)]
1363            SendCmd "camera angle $xyz"
1364            PanCamera
1365            set _settings($this-theta) $_view(theta)
1366            set _settings($this-phi)   $_view(phi)
1367            set _settings($this-psi)   $_view(psi)
1368            set _settings($this-pan-x) $_view(pan-x)
1369            set _settings($this-pan-y) $_view(pan-y)
1370            set _settings($this-zoom)  $_view(zoom)
1371        }
1372    }
1373    SendCmd "camera zoom $_view(zoom)"
1374}
1375
1376itcl::body Rappture::FlowvisViewer::PanCamera {} {
1377    #set x [expr ($_view(pan-x)) / $_limits(xrange)]
1378    #set y [expr ($_view(pan-y)) / $_limits(yrange)]
1379    set x $_view(pan-x)
1380    set y $_view(pan-y)
1381    SendCmd "camera pan $x $y"
1382}
1383
1384# ----------------------------------------------------------------------
1385# USAGE: Rotate click <x> <y>
1386# USAGE: Rotate drag <x> <y>
1387# USAGE: Rotate release <x> <y>
1388#
1389# Called automatically when the user clicks/drags/releases in the
1390# plot area.  Moves the plot according to the user's actions.
1391# ----------------------------------------------------------------------
1392itcl::body Rappture::FlowvisViewer::Rotate {option x y} {
1393    switch -- $option {
1394        click {
1395            $itk_component(3dview) configure -cursor fleur
1396            set _click(x) $x
1397            set _click(y) $y
1398            set _click(theta) $_view(theta)
1399            set _click(phi) $_view(phi)
1400        }
1401        drag {
1402            if {[array size _click] == 0} {
1403                Rotate click $x $y
1404            } else {
1405                set w [winfo width $itk_component(3dview)]
1406                set h [winfo height $itk_component(3dview)]
1407                if {$w <= 0 || $h <= 0} {
1408                    return
1409                }
1410
1411                if {[catch {
1412                    # this fails sometimes for no apparent reason
1413                    set dx [expr {double($x-$_click(x))/$w}]
1414                    set dy [expr {double($y-$_click(y))/$h}]
1415                }]} {
1416                    return
1417                }
1418
1419                #
1420                # Rotate the camera in 3D
1421                #
1422                if {$_view(psi) > 90 || $_view(psi) < -90} {
1423                    # when psi is flipped around, theta moves backwards
1424                    set dy [expr {-$dy}]
1425                }
1426                set theta [expr {$_view(theta) - $dy*180}]
1427                while {$theta < 0} { set theta [expr {$theta+180}] }
1428                while {$theta > 180} { set theta [expr {$theta-180}] }
1429
1430                if {abs($theta) >= 30 && abs($theta) <= 160} {
1431                    set phi [expr {$_view(phi) - $dx*360}]
1432                    while {$phi < 0} { set phi [expr {$phi+360}] }
1433                    while {$phi > 360} { set phi [expr {$phi-360}] }
1434                    set psi $_view(psi)
1435                } else {
1436                    set phi $_view(phi)
1437                    set psi [expr {$_view(psi) - $dx*360}]
1438                    while {$psi < -180} { set psi [expr {$psi+360}] }
1439                    while {$psi > 180} { set psi [expr {$psi-360}] }
1440                }
1441
1442                set _view(theta)        $theta
1443                set _view(phi)          $phi
1444                set _view(psi)          $psi
1445                set xyz [Euler2XYZ $theta $phi $psi]
1446                set _settings($this-theta) $_view(theta)
1447                set _settings($this-phi)   $_view(phi)
1448                set _settings($this-psi)   $_view(psi)
1449                SendCmd "camera angle $xyz"
1450                set _click(x) $x
1451                set _click(y) $y
1452            }
1453        }
1454        release {
1455            Rotate drag $x $y
1456            $itk_component(3dview) configure -cursor ""
1457            catch {unset _click}
1458        }
1459        default {
1460            error "bad option \"$option\": should be click, drag, release"
1461        }
1462    }
1463}
1464
1465# ----------------------------------------------------------------------
1466# USAGE: $this Pan click x y
1467#        $this Pan drag x y
1468#        $this Pan release x y
1469#
1470# Called automatically when the user clicks on one of the zoom
1471# controls for this widget.  Changes the zoom for the current view.
1472# ----------------------------------------------------------------------
1473itcl::body Rappture::FlowvisViewer::Pan {option x y} {
1474    # Experimental stuff
1475    set w [winfo width $itk_component(3dview)]
1476    set h [winfo height $itk_component(3dview)]
1477    if { $option == "set" } {
1478        set x [expr $x / double($w)]
1479        set y [expr $y / double($h)]
1480        set _view(pan-x) [expr $_view(pan-x) + $x]
1481        set _view(pan-y) [expr $_view(pan-y) + $y]
1482        PanCamera
1483        set _settings($this-pan-x) $_view(pan-x)
1484        set _settings($this-pan-y) $_view(pan-y)
1485        return
1486    }
1487    if { $option == "click" } {
1488        set _click(x) $x
1489        set _click(y) $y
1490        $itk_component(3dview) configure -cursor hand1
1491    }
1492    if { $option == "drag" || $option == "release" } {
1493        set dx [expr ($_click(x) - $x)/double($w)]
1494        set dy [expr ($_click(y) - $y)/double($h)]
1495        set _click(x) $x
1496        set _click(y) $y
1497        set _view(pan-x) [expr $_view(pan-x) - $dx]
1498        set _view(pan-y) [expr $_view(pan-y) - $dy]
1499        PanCamera
1500        set _settings($this-pan-x) $_view(pan-x)
1501        set _settings($this-pan-y) $_view(pan-y)
1502    }
1503    if { $option == "release" } {
1504        $itk_component(3dview) configure -cursor ""
1505    }
1506}
1507
1508
1509# ----------------------------------------------------------------------
1510# USAGE: Flow movie record|stop|play ?on|off|toggle?
1511#
1512# Called when the user clicks on the record, stop or play buttons
1513# for flow visualization.
1514# ----------------------------------------------------------------------
1515itcl::body Rappture::FlowvisViewer::Flow {option args} {
1516    switch -- $option {
1517        movie {
1518            if {[llength $args] < 1 || [llength $args] > 2} {
1519                error "wrong # args: should be \"Flow movie record|stop|play ?on|off|toggle?\""
1520            }
1521            set action [lindex $args 0]
1522            set op [lindex $args 1]
1523            if {$op == ""} { set op "on" }
1524
1525            set current [State $action]
1526            if {$op == "toggle"} {
1527                if {$current == "on"} {
1528                    set op "off"
1529                } else {
1530                    set op "on"
1531                }
1532            }
1533            set cmds ""
1534            switch -- $action {
1535                record {
1536                    if { [$itk_component(rewind) cget -relief] != "sunken" } {
1537                        $itk_component(rewind) configure -relief sunken
1538                        $itk_component(stop) configure -relief raised
1539                        $itk_component(play) configure -relief raised
1540                        set inner $itk_component(settingsFrame)
1541                        set frames [$inner.framecnt value]
1542                        set _settings(nsteps) $frames
1543                        set cmds "flow capture $frames"
1544                        SendCmd $cmds
1545                    }
1546                }
1547                stop {
1548                    if { [$itk_component(stop) cget -relief] != "sunken" } {
1549                        $itk_component(rewind) configure -relief raised
1550                        $itk_component(stop) configure -relief sunken
1551                        $itk_component(play) configure -relief raised
1552                        _pause
1553                        set cmds "flow reset"
1554                        SendCmd $cmds
1555                    }
1556                }
1557                play {
1558                    if { [$itk_component(play) cget -relief] != "sunken" } {
1559                        $itk_component(rewind) configure -relief raised
1560                        $itk_component(stop) configure -relief raised
1561                        $itk_component(play) configure \
1562                            -image [Rappture::icon flow-pause] \
1563                            -relief sunken
1564                        bind $itk_component(play) <ButtonPress> \
1565                            [itcl::code $this _pause]
1566                        flow next
1567                    }
1568                }
1569                default {
1570                    error "bad option \"$option\": should be one of record|stop|play"
1571                }
1572
1573            }
1574        }
1575        default {
1576            error "bad option \"$option\": should be movie"
1577        }
1578    }
1579}
1580
1581# ----------------------------------------------------------------------
1582# USAGE: Play
1583#
1584# ----------------------------------------------------------------------
1585itcl::body Rappture::FlowvisViewer::Play {} {
1586    SendCmd "flow next"
1587    set delay [expr {int(ceil(pow($_settings(speed)/10.0+2,2.0)*15))}]
1588    $_dispatcher event -after $delay !play
1589}
1590
1591# ----------------------------------------------------------------------
1592# USAGE: Pause
1593#
1594# Invoked when the user hits the "pause" button to stop playing the
1595# current sequence of frames as a movie.
1596# ----------------------------------------------------------------------
1597itcl::body Rappture::FlowvisViewer::Pause {} {
1598    $_dispatcher cancel !play
1599
1600    # Toggle the button to "play" mode
1601    $itk_component(play) configure \
1602        -image [Rappture::icon flow-start] \
1603        -relief raised
1604    bind $itk_component(play) <ButtonPress> \
1605        [itcl::code $this Flow movie play toggle]
1606}
1607
1608# ----------------------------------------------------------------------
1609# USAGE: FixSettings <what> ?<value>?
1610#
1611# Used internally to update rendering settings whenever parameters
1612# change in the popup settings panel.  Sends the new settings off
1613# to the back end.
1614# ----------------------------------------------------------------------
1615itcl::body Rappture::FlowvisViewer::FixSettings {what {value ""}} {
1616    switch -- $what {
1617        light {
1618            if {[isconnected]} {
1619                set val $_settings($this-light)
1620                set sval [expr {0.1*$val}]
1621                SendCmd "volume shading diffuse $sval"
1622                set sval [expr {sqrt($val+1.0)}]
1623                SendCmd "volume shading specular $sval"
1624            }
1625        }
1626        transp {
1627            if {[isconnected]} {
1628                set val $_settings($this-transp)
1629                set sval [expr {0.2*$val+1}]
1630                SendCmd "volume shading opacity $sval"
1631            }
1632        }
1633        opacity {
1634            if {[isconnected] && $_activeTf != "" } {
1635                set val $_settings($this-opacity)
1636                set sval [expr { 0.01 * double($val) }]
1637                set tf $_activeTf
1638                set _settings($this-$tf-opacity) $sval
1639                updatetransferfuncs
1640            }
1641        }
1642
1643        thickness {
1644            if {[isconnected] && $_activeTf != "" } {
1645                set val $_settings($this-thickness)
1646                # Scale values between 0.00001 and 0.01000
1647                set sval [expr {0.0001*double($val)}]
1648                set tf $_activeTf
1649                set _settings($this-$tf-thickness) $sval
1650                updatetransferfuncs
1651            }
1652        }
1653        "outline" {
1654            if {[isconnected]} {
1655                SendCmd "volume outline state $_settings($this-outline)"
1656            }
1657        }
1658        "isosurface" {
1659            if {[isconnected]} {
1660                SendCmd "volume shading isosurface $_settings($this-isosurface)"
1661            }
1662        }
1663        "grid" {
1664            if { [isconnected] } {
1665                SendCmd "grid visible $_settings($this-grid)"
1666            }
1667        }
1668        "axes" {
1669            if { [isconnected] } {
1670                SendCmd "axis visible $_settings($this-axes)"
1671            }
1672        }
1673        "legend" {
1674            if { $_settings($this-legend) } {
1675                blt::table $itk_component(plotarea) \
1676                    0,0 $itk_component(3dview) -fill both \
1677                    1,0 $itk_component(legend) -fill x
1678                blt::table configure $itk_component(plotarea) r1 -resize none
1679            } else {
1680                blt::table forget $itk_component(legend)
1681            }
1682        }
1683        "volume" {
1684            if { [isconnected] } {
1685                set vols [CurrentVolumeIds -cutplanes]
1686                SendCmd "volume data state $_settings($this-volume) $vols"
1687            }
1688        }
1689        "xcutplane" - "ycutplane" - "zcutplane" {
1690            set axis [string range $what 0 0]
1691            set bool $_settings($this-$what)
1692            if { [isconnected] } {
1693                set vols [CurrentVolumeIds -cutplanes]
1694                SendCmd "cutplane state $bool $axis $vols"
1695            }
1696            if { $bool } {
1697                $itk_component(${axis}CutScale) configure -state normal \
1698                    -troughcolor white
1699            } else {
1700                $itk_component(${axis}CutScale) configure -state disabled \
1701                    -troughcolor grey82
1702            }
1703        }
1704        default {
1705            error "don't know how to fix $what"
1706        }
1707    }
1708}
1709
1710# ----------------------------------------------------------------------
1711# USAGE: ResizeLegend
1712#
1713# Used internally to update the legend area whenever it changes size
1714# or when the field changes.  Asks the server to send a new legend
1715# for the current field.
1716# ----------------------------------------------------------------------
1717itcl::body Rappture::FlowvisViewer::ResizeLegend {} {
1718    set _resizeLegendPending 0
1719    set lineht [font metrics $itk_option(-font) -linespace]
1720    set w [expr {$_width-20}]
1721    set h [expr {[winfo height $itk_component(legend)]-20-$lineht}]
1722    if {$w > 0 && $h > 0 && "" != $_activeTf} {
1723        SendCmd "legend $_activeTf $w $h"
1724    } else {
1725    # Can't do this as this will remove the items associated with the
1726    # isomarkers.
1727
1728    #$itk_component(legend) delete all
1729    }
1730}
1731
1732#
1733# NameTransferFunc --
1734#
1735#       Creates a transfer function name based on the <style> settings in the
1736#       library run.xml file. This placeholder will be used later to create
1737#       and send the actual transfer function once the data info has been sent
1738#       to us by the render server. [We won't know the volume limits until the
1739#       server parses the 3D data and sends back the limits via ReceiveData.]
1740#
1741#       FIXME: The current way we generate transfer-function names completely
1742#              ignores the -markers option.  The problem is that we are forced
1743#              to compute the name from an increasing complex set of values:
1744#              color, levels, marker, opacity.  I think we're stuck doing it
1745#              now.
1746#
1747itcl::body Rappture::FlowvisViewer::NameTransferFunc { dataobj comp } {
1748    array set style {
1749        -color rainbow
1750        -levels 6
1751        -opacity 1.0
1752    }
1753    array set style [lindex [$dataobj components -style $comp] 0]
1754    set tf "$style(-color):$style(-levels):$style(-opacity)"
1755    lappend _obj2style($dataobj-$comp) $tf
1756    lappend _style2objs($tf) $dataobj $comp
1757    return $tf
1758}
1759
1760#
1761# ComputeTransferFunc --
1762#
1763#   Computes and sends the transfer function to the render server.  It's
1764#   assumed that the volume data limits are known and that the global
1765#   transfer-functions slider values have be setup.  Both parts are
1766#   needed to compute the relative value (location) of the marker, and
1767#   the alpha map of the transfer function.
1768#
1769itcl::body Rappture::FlowvisViewer::ComputeTransferFunc { tf } {
1770    array set style {
1771        -color rainbow
1772        -levels 6
1773        -opacity 1.0
1774    }
1775    set dataobj ""; set comp ""
1776    foreach {dataobj comp} $_style2objs($tf) break
1777    if { $dataobj == "" } {
1778        return 0
1779    }
1780    array set style [lindex [$dataobj components -style $comp] 0]
1781
1782
1783    # We have to parse the style attributes for a volume using this
1784    # transfer-function *once*.  This sets up the initial isomarkers for the
1785    # transfer function.  The user may add/delete markers, so we have to
1786    # maintain a list of markers for each transfer-function.  We use the one
1787    # of the volumes (the first in the list) using the transfer-function as a
1788    # reference.
1789    #
1790    # FIXME: The current way we generate transfer-function names completely
1791    #        ignores the -markers option.  The problem is that we are forced
1792    #        to compute the name from an increasing complex set of values:
1793    #        color, levels, marker, opacity.  I think the cow's out of the
1794    #        barn on this one.
1795
1796    if { ![info exists _isomarkers($tf)] } {
1797        # Have to defer creation of isomarkers until we have data limits
1798        if { [info exists style(-markers)] } {
1799            ParseMarkersOption $tf $style(-markers)
1800        } else {
1801            ParseLevelsOption $tf $style(-levels)
1802        }
1803    }
1804    if {$style(-color) == "rainbow"} {
1805        set style(-color) "white:yellow:green:cyan:blue:magenta"
1806    }
1807    set clist [split $style(-color) :]
1808    set cmap "0.0 [Color2RGB white] "
1809    for {set i 0} {$i < [llength $clist]} {incr i} {
1810        set x [expr {double($i+1)/([llength $clist]+1)}]
1811        set color [lindex $clist $i]
1812        append cmap "$x [Color2RGB $color] "
1813    }
1814    append cmap "1.0 [Color2RGB $color]"
1815
1816    set tag $this-$tf
1817    if { ![info exists _settings($tag-opacity)] } {
1818        set _settings($tag-opacity) $style(-opacity)
1819    }
1820    set max $_settings($tag-opacity)
1821
1822    set isovalues {}
1823    foreach m $_isomarkers($tf) {
1824        lappend isovalues [$m relval]
1825    }
1826    # Sort the isovalues
1827    set isovalues [lsort -real $isovalues]
1828
1829    if { ![info exists _settings($tag-thickness)]} {
1830        set _settings($tag-thickness) 0.05
1831    }
1832    set delta $_settings($tag-thickness)
1833
1834    set first [lindex $isovalues 0]
1835    set last [lindex $isovalues end]
1836    set wmap ""
1837    if { $first == "" || $first != 0.0 } {
1838        lappend wmap 0.0 0.0
1839    }
1840    foreach x $isovalues {
1841        set x1 [expr {$x-$delta-0.00001}]
1842        set x2 [expr {$x-$delta}]
1843        set x3 [expr {$x+$delta}]
1844        set x4 [expr {$x+$delta+0.00001}]
1845        if { $x1 < 0.0 } {
1846            set x1 0.0
1847        } elseif { $x1 > 1.0 } {
1848            set x1 1.0
1849        }
1850        if { $x2 < 0.0 } {
1851            set x2 0.0
1852        } elseif { $x2 > 1.0 } {
1853            set x2 1.0
1854        }
1855        if { $x3 < 0.0 } {
1856            set x3 0.0
1857        } elseif { $x3 > 1.0 } {
1858            set x3 1.0
1859        }
1860        if { $x4 < 0.0 } {
1861            set x4 0.0
1862        } elseif { $x4 > 1.0 } {
1863            set x4 1.0
1864        }
1865        # add spikes in the middle
1866        lappend wmap $x1 0.0
1867        lappend wmap $x2 $max
1868        lappend wmap $x3 $max
1869        lappend wmap $x4 0.0
1870    }
1871    if { $last == "" || $last != 1.0 } {
1872        lappend wmap 1.0 0.0
1873    }
1874    SendBytes "transfunc define $tf { $cmap } { $wmap }\n"
1875    return [SendBytes "$dataobj-$comp configure -transferfunction $tf\n"]
1876}
1877
1878# ----------------------------------------------------------------------
1879# CONFIGURATION OPTION: -plotbackground
1880# ----------------------------------------------------------------------
1881itcl::configbody Rappture::FlowvisViewer::plotbackground {
1882    if { [isconnected] } {
1883        foreach {r g b} [Color2RGB $itk_option(-plotbackground)] break
1884        #fix this!
1885        #SendCmd "color background $r $g $b"
1886    }
1887}
1888
1889# ----------------------------------------------------------------------
1890# CONFIGURATION OPTION: -plotforeground
1891# ----------------------------------------------------------------------
1892itcl::configbody Rappture::FlowvisViewer::plotforeground {
1893    if { [isconnected] } {
1894        foreach {r g b} [Color2RGB $itk_option(-plotforeground)] break
1895        #fix this!
1896        #SendCmd "color background $r $g $b"
1897    }
1898}
1899
1900# ----------------------------------------------------------------------
1901# CONFIGURATION OPTION: -plotoutline
1902# ----------------------------------------------------------------------
1903itcl::configbody Rappture::FlowvisViewer::plotoutline {
1904    # Must check if we are connected because this routine is called from the
1905    # class body when the -plotoutline itk_option is defined.  At that point
1906    # the FlowvisViewer class constructor hasn't been called, so we can't
1907    # start sending commands to visualization server.
1908    if { [isconnected] } {
1909        if {"" == $itk_option(-plotoutline)} {
1910            SendCmd "volume outline state off"
1911        } else {
1912            SendCmd "volume outline state on"
1913            SendCmd "volume outline color [Color2RGB $itk_option(-plotoutline)]"
1914        }
1915    }
1916}
1917
1918#
1919# The -levels option takes a single value that represents the number
1920# of evenly distributed markers based on the current data range. Each
1921# marker is a relative value from 0.0 to 1.0.
1922#
1923itcl::body Rappture::FlowvisViewer::ParseLevelsOption { tf levels } {
1924    set c $itk_component(legend)
1925    regsub -all "," $levels " " levels
1926    if {[string is int $levels]} {
1927        for {set i 1} { $i <= $levels } {incr i} {
1928            set x [expr {double($i)/($levels+1)}]
1929            set m [Rappture::IsoMarker \#auto $c $this $tf]
1930            $m relval $x
1931            lappend _isomarkers($tf) $m
1932        }
1933    } else {
1934        foreach x $levels {
1935            set m [Rappture::IsoMarker \#auto $c $this $tf]
1936            $m relval $x
1937            lappend _isomarkers($tf) $m
1938        }
1939    }
1940}
1941
1942#
1943# The -markers option takes a list of zero or more values (the values
1944# may be separated either by spaces or commas) that have the following
1945# format:
1946#
1947#   N%  Percent of current total data range.  Converted to
1948#       to a relative value between 0.0 and 1.0.
1949#   N   Absolute value of marker.  If the marker is outside of
1950#       the current range, it will be displayed on the outer
1951#       edge of the legends, but it range it represents will
1952#       not be seen.
1953#
1954itcl::body Rappture::FlowvisViewer::ParseMarkersOption { tf markers } {
1955    set c $itk_component(legend)
1956    regsub -all "," $markers " " markers
1957    foreach marker $markers {
1958        set n [scan $marker "%g%s" value suffix]
1959        if { $n == 2 && $suffix == "%" } {
1960            # ${n}% : Set relative value.
1961            set value [expr {$value * 0.01}]
1962            set m [Rappture::IsoMarker \#auto $c $this $tf]
1963            $m relval $value
1964            lappend _isomarkers($tf) $m
1965        } else {
1966            # ${n} : Set absolute value.
1967            set m [Rappture::IsoMarker \#auto $c $this $tf]
1968            $m absval $value
1969            lappend _isomarkers($tf) $m
1970        }
1971    }
1972}
1973
1974# ----------------------------------------------------------------------
1975# USAGE: UndateTransferFuncs
1976# ----------------------------------------------------------------------
1977itcl::body Rappture::FlowvisViewer::updatetransferfuncs {} {
1978    $_dispatcher event -idle !send_transfunc
1979}
1980
1981itcl::body Rappture::FlowvisViewer::AddIsoMarker { x y } {
1982    if { $_activeTf == "" } {
1983        error "active transfer function isn't set"
1984    }
1985    set tf $_activeTf
1986    set c $itk_component(legend)
1987    set m [Rappture::IsoMarker \#auto $c $this $tf]
1988    set w [winfo width $c]
1989    $m relval [expr {double($x-10)/($w-20)}]
1990    lappend _isomarkers($tf) $m
1991    updatetransferfuncs
1992    return 1
1993}
1994
1995itcl::body Rappture::FlowvisViewer::rmdupmarker { marker x } {
1996    set tf [$marker transferfunc]
1997    set bool 0
1998    if { [info exists _isomarkers($tf)] } {
1999        set list {}
2000        set marker [namespace tail $marker]
2001        foreach m $_isomarkers($tf) {
2002            set sx [$m screenpos]
2003            if { $m != $marker } {
2004                if { $x >= ($sx-3) && $x <= ($sx+3) } {
2005                    $marker relval [$m relval]
2006                    itcl::delete object $m
2007                    bell
2008                    set bool 1
2009                    continue
2010                }
2011            }
2012            lappend list $m
2013        }
2014        set _isomarkers($tf) $list
2015        updatetransferfuncs
2016    }
2017    return $bool
2018}
2019
2020itcl::body Rappture::FlowvisViewer::overmarker { marker x } {
2021    set tf [$marker transferfunc]
2022    if { [info exists _isomarkers($tf)] } {
2023        set marker [namespace tail $marker]
2024        foreach m $_isomarkers($tf) {
2025            set sx [$m screenpos]
2026            if { $m != $marker } {
2027                set bool [expr { $x >= ($sx-3) && $x <= ($sx+3) }]
2028                $m activate $bool
2029            }
2030        }
2031    }
2032    return ""
2033}
2034
2035itcl::body Rappture::FlowvisViewer::limits { tf } {
2036    set _limits(min) 0.0
2037    set _limits(max) 1.0
2038    if { ![info exists _style2objs($tf)] } {
2039        return [array get _limits]
2040    }
2041    set min ""; set max ""
2042    foreach {dataobj comp} $_style2objs($tf) {
2043        if { ![info exists _obj2id($dataobj-$comp)] } {
2044            continue
2045        }
2046        set ivol $_obj2id($dataobj-$comp)
2047        if { ![info exists _limits($ivol-min)] } {
2048            continue
2049        }
2050        if { $min == "" || $min > $_limits($ivol-min) } {
2051            set min $_limits($ivol-min)
2052        }
2053        if { $max == "" || $max < $_limits($ivol-max) } {
2054            set max $_limits($ivol-max)
2055        }
2056    }
2057    if { $min != "" } {
2058        set _limits(min) $min
2059    }
2060    if { $max != "" } {
2061        set _limits(max) $max
2062    }
2063    return [array get _limits]
2064}
2065
2066
2067
2068itcl::body Rappture::FlowvisViewer::BuildViewTab {} {
2069    foreach { key value } {
2070        grid            0
2071        axes            0
2072        outline         1
2073        volume          1
2074        legend          1
2075        particles       1
2076        lic             1
2077    } {
2078        set _settings($this-$key) $value
2079    }
2080
2081    set fg [option get $itk_component(hull) font Font]
2082    #set bfg [option get $itk_component(hull) boldFont Font]
2083
2084    set inner [$itk_component(main) insert end \
2085        -title "View Settings" \
2086        -icon [Rappture::icon wrench]]
2087    $inner configure -borderwidth 4
2088
2089    set ::Rappture::FlowvisViewer::_settings($this-isosurface) 0
2090    checkbutton $inner.isosurface \
2091        -text "Isosurface shading" \
2092        -variable [itcl::scope _settings($this-isosurface)] \
2093        -command [itcl::code $this FixSettings isosurface] \
2094        -font "Arial 9"
2095
2096    checkbutton $inner.axes \
2097        -text "Axes" \
2098        -variable [itcl::scope _settings($this-axes)] \
2099        -command [itcl::code $this FixSettings axes] \
2100        -font "Arial 9"
2101
2102    checkbutton $inner.grid \
2103        -text "Grid" \
2104        -variable [itcl::scope _settings($this-grid)] \
2105        -command [itcl::code $this FixSettings grid] \
2106        -font "Arial 9"
2107
2108    checkbutton $inner.outline \
2109        -text "Outline" \
2110        -variable [itcl::scope _settings($this-outline)] \
2111        -command [itcl::code $this FixSettings outline] \
2112        -font "Arial 9"
2113
2114    checkbutton $inner.legend \
2115        -text "Legend" \
2116        -variable [itcl::scope _settings($this-legend)] \
2117        -command [itcl::code $this FixSettings legend] \
2118        -font "Arial 9"
2119
2120    checkbutton $inner.volume \
2121        -text "Volume" \
2122        -variable [itcl::scope _settings($this-volume)] \
2123        -command [itcl::code $this FixSettings volume] \
2124        -font "Arial 9"
2125
2126    checkbutton $inner.particles \
2127        -text "Particles" \
2128        -variable [itcl::scope _settings($this-particles)] \
2129        -command [itcl::code $this FixSettings particles] \
2130        -font "Arial 9"
2131
2132    checkbutton $inner.lic \
2133        -text "Lic" \
2134        -variable [itcl::scope _settings($this-lic)] \
2135        -command [itcl::code $this FixSettings lic] \
2136        -font "Arial 9"
2137
2138    frame $inner.frame
2139
2140    blt::table $inner \
2141        0,0 $inner.axes  -columnspan 2 -anchor w \
2142        1,0 $inner.grid  -columnspan 2 -anchor w \
2143        2,0 $inner.outline  -columnspan 2 -anchor w \
2144        3,0 $inner.volume  -columnspan 2 -anchor w \
2145        4,0 $inner.legend  -columnspan 2 -anchor w
2146
2147    bind $inner <Map> [itcl::code $this GetFlowInfo $inner]
2148
2149    blt::table configure $inner r* -resize none
2150    blt::table configure $inner r5 -resize expand
2151}
2152
2153itcl::body Rappture::FlowvisViewer::BuildVolumeTab {} {
2154    foreach { key value } {
2155        light           40
2156        transp          50
2157        opacity         100
2158        thickness       350
2159    } {
2160        set _settings($this-$key) $value
2161    }
2162
2163    set inner [$itk_component(main) insert end \
2164        -title "Volume Settings" \
2165        -icon [Rappture::icon volume-on]]
2166    $inner configure -borderwidth 4
2167
2168    set fg [option get $itk_component(hull) font Font]
2169    #set bfg [option get $itk_component(hull) boldFont Font]
2170
2171    label $inner.dim -text "Dim" -font $fg
2172    ::scale $inner.light -from 0 -to 100 -orient horizontal \
2173        -variable [itcl::scope _settings($this-light)] \
2174        -width 10 \
2175        -showvalue off -command [itcl::code $this FixSettings light]
2176    label $inner.bright -text "Bright" -font $fg
2177
2178    label $inner.fog -text "Fog" -font $fg
2179    ::scale $inner.transp -from 0 -to 100 -orient horizontal \
2180        -variable [itcl::scope _settings($this-transp)] \
2181        -width 10 \
2182        -showvalue off -command [itcl::code $this FixSettings transp]
2183    label $inner.plastic -text "Plastic" -font $fg
2184
2185    label $inner.clear -text "Clear" -font $fg
2186    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
2187        -variable [itcl::scope _settings($this-opacity)] \
2188        -width 10 \
2189        -showvalue off -command [itcl::code $this FixSettings opacity]
2190    label $inner.opaque -text "Opaque" -font $fg
2191
2192    label $inner.thin -text "Thin" -font $fg
2193    ::scale $inner.thickness -from 0 -to 1000 -orient horizontal \
2194        -variable [itcl::scope _settings($this-thickness)] \
2195        -width 10 \
2196        -showvalue off -command [itcl::code $this FixSettings thickness]
2197    label $inner.thick -text "Thick" -font $fg
2198
2199    blt::table $inner \
2200        0,0 $inner.dim  -anchor e -pady 2 \
2201        0,1 $inner.light -columnspan 2 -pady 2 \
2202        0,3 $inner.bright -anchor w -pady 2 \
2203        1,0 $inner.fog -anchor e -pady 2 \
2204        1,1 $inner.transp -columnspan 2 -pady 2 \
2205        1,3 $inner.plastic -anchor w -pady 2 \
2206        2,0 $inner.clear -anchor e -pady 2 \
2207        2,1 $inner.opacity -columnspan 2 -pady 2 \
2208        2,3 $inner.opaque -anchor w -pady 2 \
2209        3,0 $inner.thin -anchor e -pady 2 \
2210        3,1 $inner.thickness -columnspan 2 -pady 2 \
2211        3,3 $inner.thick -anchor w -pady 2
2212
2213    blt::table configure $inner c0 c1 c3 r* -resize none
2214    blt::table configure $inner r6 -resize expand
2215}
2216
2217itcl::body Rappture::FlowvisViewer::BuildCutplanesTab {} {
2218    set inner [$itk_component(main) insert end \
2219        -title "Cutplane Settings" \
2220        -icon [Rappture::icon cutbutton]]
2221    $inner configure -borderwidth 4
2222
2223    # X-value slicer...
2224    itk_component add xCutButton {
2225        Rappture::PushButton $inner.xbutton \
2226            -onimage [Rappture::icon x-cutplane-on] \
2227            -offimage [Rappture::icon x-cutplane-off] \
2228            -command [itcl::code $this FixSettings xcutplane] \
2229            -variable [itcl::scope _settings($this-xcutplane)]
2230    }
2231    Rappture::Tooltip::for $itk_component(xCutButton) \
2232        "Toggle the X cut plane on/off"
2233
2234    itk_component add xCutScale {
2235        ::scale $inner.xval -from 100 -to 0 \
2236            -width 10 -orient vertical -showvalue off \
2237            -borderwidth 1 -highlightthickness 0 \
2238            -command [itcl::code $this Slice move x] \
2239            -variable [itcl::scope _settings($this-xcutposition)]
2240    } {
2241        usual
2242        ignore -borderwidth -highlightthickness
2243    }
2244    # Set the default cutplane value before disabling the scale.
2245    $itk_component(xCutScale) set 50
2246    $itk_component(xCutScale) configure -state disabled
2247    Rappture::Tooltip::for $itk_component(xCutScale) \
2248        "@[itcl::code $this SlicerTip x]"
2249
2250    # Y-value slicer...
2251    itk_component add yCutButton {
2252        Rappture::PushButton $inner.ybutton \
2253            -onimage [Rappture::icon y-cutplane-on] \
2254            -offimage [Rappture::icon y-cutplane-off] \
2255            -command [itcl::code $this FixSettings ycutplane] \
2256            -variable [itcl::scope _settings($this-ycutplane)]
2257    }
2258    Rappture::Tooltip::for $itk_component(yCutButton) \
2259        "Toggle the Y cut plane on/off"
2260
2261    itk_component add yCutScale {
2262        ::scale $inner.yval -from 100 -to 0 \
2263            -width 10 -orient vertical -showvalue off \
2264            -borderwidth 1 -highlightthickness 0 \
2265            -command [itcl::code $this Slice move y] \
2266            -variable [itcl::scope _settings($this-ycutposition)]
2267    } {
2268        usual
2269        ignore -borderwidth -highlightthickness
2270    }
2271    Rappture::Tooltip::for $itk_component(yCutScale) \
2272        "@[itcl::code $this SlicerTip y]"
2273    # Set the default cutplane value before disabling the scale.
2274    $itk_component(yCutScale) set 50
2275    $itk_component(yCutScale) configure -state disabled
2276
2277    # Z-value slicer...
2278    itk_component add zCutButton {
2279        Rappture::PushButton $inner.zbutton \
2280            -onimage [Rappture::icon z-cutplane-on] \
2281            -offimage [Rappture::icon z-cutplane-off] \
2282            -command [itcl::code $this FixSettings zcutplane] \
2283            -variable [itcl::scope _settings($this-zcutplane)]
2284    }
2285    Rappture::Tooltip::for $itk_component(zCutButton) \
2286        "Toggle the Z cut plane on/off"
2287
2288    itk_component add zCutScale {
2289        ::scale $inner.zval -from 100 -to 0 \
2290            -width 10 -orient vertical -showvalue off \
2291            -borderwidth 1 -highlightthickness 0 \
2292            -command [itcl::code $this Slice move z] \
2293            -variable [itcl::scope _settings($this-zcutposition)]
2294    } {
2295        usual
2296        ignore -borderwidth -highlightthickness
2297    }
2298    $itk_component(zCutScale) set 50
2299    $itk_component(zCutScale) configure -state disabled
2300    #$itk_component(zCutScale) configure -state disabled
2301    Rappture::Tooltip::for $itk_component(zCutScale) \
2302        "@[itcl::code $this SlicerTip z]"
2303
2304    blt::table $inner \
2305        1,1 $itk_component(xCutButton) \
2306        1,2 $itk_component(yCutButton) \
2307        1,3 $itk_component(zCutButton) \
2308        0,1 $itk_component(xCutScale) \
2309        0,2 $itk_component(yCutScale) \
2310        0,3 $itk_component(zCutScale) \
2311
2312    blt::table configure $inner r0 r1 c* -resize none
2313    blt::table configure $inner r2 c4 -resize expand
2314    blt::table configure $inner c0 -width 2
2315    blt::table configure $inner c1 c2 c3 -padx 2
2316}
2317
2318itcl::body Rappture::FlowvisViewer::BuildCameraTab {} {
2319    set inner [$itk_component(main) insert end \
2320        -title "Camera Settings" \
2321        -icon [Rappture::icon camera]]
2322    $inner configure -borderwidth 4
2323
2324    set labels { phi theta psi pan-x pan-y zoom }
2325    set row 0
2326    foreach tag $labels {
2327        label $inner.${tag}label -text $tag -font "Arial 9"
2328        entry $inner.${tag} -font "Arial 9"  -bg white \
2329            -textvariable [itcl::scope _settings($this-$tag)]
2330        bind $inner.${tag} <KeyPress-Return> \
2331            [itcl::code $this camera set ${tag}]
2332        blt::table $inner \
2333            $row,0 $inner.${tag}label -anchor e -pady 2 \
2334            $row,1 $inner.${tag} -anchor w -pady 2
2335        blt::table configure $inner r$row -resize none
2336        incr row
2337    }
2338    blt::table configure $inner c0 c1 -resize none
2339    blt::table configure $inner c2 -resize expand
2340    blt::table configure $inner r$row -resize expand
2341}
2342
2343itcl::body Rappture::FlowvisViewer::GetFlowInfo { w } {
2344    set flowobj ""
2345    foreach key [array names _obj2flow] {
2346        set flowobj $_obj2flow($key)
2347        break
2348    }
2349    if { $flowobj == "" } {
2350        return
2351    }
2352    if { [winfo exists $w.frame] } {
2353        destroy $w.frame
2354    }
2355    set inner [frame $w.frame]
2356    blt::table $w \
2357        5,0 $inner -fill both -columnspan 2 -anchor nw
2358    array set hints [$flowobj hints]
2359    checkbutton $inner.showstreams -text "Streams Plane" \
2360        -variable [itcl::scope _settings($this-streams)] \
2361        -command  [itcl::code $this streams $key $hints(name)]  \
2362        -font "Arial 9"
2363    Rappture::Tooltip::for $inner.showstreams $hints(description)
2364    label $inner.particles -text "Particles"    -font "Arial 9 bold"
2365    label $inner.boxes -text "Boxes"    -font "Arial 9 bold"
2366
2367    blt::table $inner \
2368        1,0 $inner.showstreams  -anchor w
2369    blt::table configure $inner c0 -resize none
2370    blt::table configure $inner c1 -resize expand
2371
2372    set row 2
2373    set particles [$flowobj particles]
2374    if { [llength $particles] > 0 } {
2375        blt::table $inner $row,0 $inner.particles  -anchor w
2376        incr row
2377    }
2378    foreach part $particles {
2379        array unset info
2380        array set info $part
2381        set name $info(name)
2382        if { ![info exists _settings($this-particles-$name)] } {
2383            set _settings($this-particles-$name) $info(hide)
2384        }
2385        checkbutton $inner.part$row -text $info(label) \
2386            -variable [itcl::scope _settings($this-particles-$name)] \
2387            -onvalue 0 -offvalue 1 \
2388            -command [itcl::code $this particles $key $name] \
2389            -font "Arial 9"
2390        Rappture::Tooltip::for $inner.part$row $info(description)
2391        blt::table $inner $row,0 $inner.part$row -anchor w
2392        if { !$_settings($this-particles-$name) } {
2393            $inner.part$row select
2394        }
2395        incr row
2396    }
2397    set boxes [$flowobj boxes]
2398    if { [llength $boxes] > 0 } {
2399        blt::table $inner $row,0 $inner.boxes  -anchor w
2400        incr row
2401    }
2402    foreach box $boxes {
2403        array unset info
2404        array set info $box
2405        set name $info(name)
2406        if { ![info exists _settings($this-box-$name)] } {
2407            set _settings($this-box-$name) $info(hide)
2408        }
2409        checkbutton $inner.box$row -text $info(label) \
2410            -variable [itcl::scope _settings($this-box-$name)] \
2411            -onvalue 0 -offvalue 1 \
2412            -command [itcl::code $this box $key $name] \
2413            -font "Arial 9"
2414        Rappture::Tooltip::for $inner.box$row $info(description)
2415        blt::table $inner $row,0 $inner.box$row -anchor w
2416        if { !$_settings($this-box-$name) } {
2417            $inner.box$row select
2418        }
2419        incr row
2420    }
2421    blt::table configure $inner r* -resize none
2422    blt::table configure $inner r$row -resize expand
2423    blt::table configure $inner c3 -resize expand
2424    event generate [winfo parent [winfo parent $w]] <Configure>
2425}
2426
2427itcl::body Rappture::FlowvisViewer::particles { tag name } {
2428    set bool $_settings($this-particles-$name)
2429    SendCmd "$tag particles configure {$name} -hide $bool"
2430}
2431
2432itcl::body Rappture::FlowvisViewer::box { tag name } {
2433    set bool $_settings($this-box-$name)
2434    SendCmd "$tag box configure {$name} -hide $bool"
2435}
2436
2437itcl::body Rappture::FlowvisViewer::streams { tag name } {
2438    set bool $_settings($this-streams)
2439    SendCmd "$tag configure -slice $bool"
2440}
2441
2442# ----------------------------------------------------------------------
2443# USAGE: Slice move x|y|z <newval>
2444#
2445# Called automatically when the user drags the slider to move the
2446# cut plane that slices 3D data.  Gets the current value from the
2447# slider and moves the cut plane to the appropriate point in the
2448# data set.
2449# ----------------------------------------------------------------------
2450itcl::body Rappture::FlowvisViewer::Slice {option args} {
2451    switch -- $option {
2452        move {
2453            if {[llength $args] != 2} {
2454                error "wrong # args: should be \"Slice move x|y|z newval\""
2455            }
2456            set axis [lindex $args 0]
2457            set newval [lindex $args 1]
2458            set newpos [expr {0.01*$newval}]
2459
2460            # show the current value in the readout
2461
2462            set ids [CurrentVolumeIds -cutplanes]
2463            SendCmd "cutplane position $newpos $axis $ids"
2464        }
2465        default {
2466            error "bad option \"$option\": should be axis, move, or volume"
2467        }
2468    }
2469}
2470
2471# ----------------------------------------------------------------------
2472# USAGE: SlicerTip <axis>
2473#
2474# Used internally to generate a tooltip for the x/y/z slicer controls.
2475# Returns a message that includes the current slicer value.
2476# ----------------------------------------------------------------------
2477itcl::body Rappture::FlowvisViewer::SlicerTip {axis} {
2478    set val [$itk_component(${axis}CutScale) get]
2479#    set val [expr {0.01*($val-50)
2480#        *($_limits(${axis}max)-$_limits(${axis}min))
2481#          + 0.5*($_limits(${axis}max)+$_limits(${axis}min))}]
2482    return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
2483}
2484
2485
2486itcl::body Rappture::FlowvisViewer::DoResize {} {
2487    SendCmd "screen $_width $_height"
2488    set _resizePending 0
2489}
2490
2491itcl::body Rappture::FlowvisViewer::EventuallyResize { w h } {
2492    set _width $w
2493    set _height $h
2494    if { !$_resizePending } {
2495        $_dispatcher event -idle !resize
2496        set _resizePending 1
2497    }
2498}
2499
2500itcl::body Rappture::FlowvisViewer::EventuallyResizeLegend {} {
2501    if { !$_resizeLegendPending } {
2502        $_dispatcher event -idle !legend
2503        set _resizeLegendPending 1
2504    }
2505}
2506
2507#  camera --
2508itcl::body Rappture::FlowvisViewer::camera {option args} {
2509    switch -- $option {
2510        "show" {
2511            puts [array get _view]
2512        }
2513        "set" {
2514            set who [lindex $args 0]
2515            set x $_settings($this-$who)
2516            set code [catch { string is double $x } result]
2517            if { $code != 0 || !$result } {
2518                set _settings($this-$who) $_view($who)
2519                return
2520            }
2521            switch -- $who {
2522                "pan-x" - "pan-y" {
2523                    set _view($who) $_settings($this-$who)
2524                    PanCamera
2525                }
2526                "phi" - "theta" - "psi" {
2527                    set _view($who) $_settings($this-$who)
2528                    set xyz [Euler2XYZ $_view(theta) $_view(phi) $_view(psi)]
2529                    SendCmd "camera angle $xyz"
2530                }
2531                "zoom" {
2532                    set _view($who) $_settings($this-$who)
2533                    SendCmd "camera zoom $_view(zoom)"
2534                }
2535            }
2536        }
2537    }
2538}
2539
2540itcl::body Rappture::FlowvisViewer::FlowCmd { dataobj comp nbytes extents } {
2541    set tag "$dataobj-$comp"
2542    if { ![info exists _obj2flow($tag)] } {
2543        append cmd "flow add $tag\n"
2544        append cmd "$tag data follows $nbytes $extents\n"
2545        return $cmd
2546    }
2547    set flowobj $_obj2flow($tag)
2548    if { $flowobj == "" } {
2549        puts stderr "no flowobj"
2550        return ""
2551    }
2552    set cmd {}
2553    append cmd "if {\[flow exists $tag\]} {flow delete $tag}\n"
2554    array set info  [$flowobj hints]
2555    append cmd "flow add $tag -position $info(position) -axis $info(axis) "
2556    append cmd "-volume $info(volume) -outline $info(outline) "
2557    append cmd "-slice $info(streams)\n"
2558    foreach part [$flowobj particles] {
2559        array unset info
2560        array set info $part
2561        set color [Color2RGB $info(color)]
2562        append cmd "$tag particles add $info(name) -position $info(position) "
2563        append cmd "-axis $info(axis) -color {$color}\n"
2564    }
2565    foreach box [$flowobj boxes] {
2566        array unset info
2567        set info(corner1) ""
2568        set info(corner2) ""
2569        array set info $box
2570        if { $info(corner1) == "" || $info(corner2) == "" } {
2571            continue
2572        }
2573        set color [Color2RGB $info(color)]
2574        append cmd "$tag box add $info(name) -color {$color} "
2575        append cmd "-hide $info(hide) "
2576        append cmd "-corner1 {$info(corner1)} -corner2 {$info(corner2)}\n"
2577    }   
2578    append cmd "$tag data follows $nbytes $extents\n"
2579    return $cmd
2580}
2581
2582
2583#
2584# flow --
2585#
2586# Called when the user clicks on the stop or play buttons
2587# for flow visualization.
2588#
2589#       $this flow play
2590#       $this flow stop
2591#       $this flow toggle
2592#       $this flow reset
2593#       $this flow pause
2594#       $this flow next
2595#
2596itcl::body Rappture::FlowvisViewer::flow { args } {
2597    set option [lindex $args 0]
2598    switch -- $option {
2599        "speed" {
2600            set speed [$itk_component(speed) value]
2601            set _flow(delay) [expr int(round(500.0/$speed))]
2602        }
2603        "duration" {
2604            set value $_settings($this-duration)
2605            set pattern1 {^ *([0-9]+):([0-5][0-9]) *$}
2606            set pattern2 {^ *:([0-5][0-9]) *$}
2607            if { [string is int $value] } {
2608                set _flow(duration) [expr $value * 1000]
2609            } elseif { [regexp $pattern1 $value match mins secs] } {
2610                set _flow(duration) [expr (($mins * 60) + $secs) * 1000]
2611            } elseif { [regexp $pattern2 $value match secs] } {
2612                set _flow(duration) [expr $secs * 1000]
2613            } else {
2614                bell
2615                return
2616            }
2617            if { $_flow(duration) > 600000 } {
2618                set _flow(duration) 600000
2619            }
2620            set min [expr $_flow(duration) / 60000]
2621            set sec [expr ($_flow(duration) - ($min*60000)) / 1000]
2622            set _settings($this-duration) [format %02d:%02d $min $sec]
2623            $itk_component(frame) configure -to $_flow(duration)
2624        }
2625        "off" {
2626            set _flow(state) 0
2627            $_dispatcher cancel !play
2628            $itk_component(play) deselect
2629        }
2630        "on" {
2631            flow speed
2632            flow duration
2633            set _flow(state) 1
2634            set _flow(time) 0
2635            $itk_component(play) select
2636        }
2637        "stop" {
2638            if { $_flow(state) } {
2639                flow off
2640                flow reset
2641            }
2642        }
2643        "pause" {
2644            if { $_flow(state) } {
2645                flow off
2646            }
2647        }
2648        "play" {
2649            # If the flow is currently off, then restart it.
2650            if { !$_flow(state) } {
2651                flow on
2652                # If we're at the end of the flow, reset the flow.
2653                incr _flow(time) $_flow(delay)
2654                if { $_flow(time) >= $_flow(duration) } {
2655                    set _settings($this-step) 1
2656                    SendCmd "flow reset"
2657                }
2658                flow next
2659            }
2660        }
2661        "toggle" {
2662            if { $_settings($this-play) } {
2663                flow play
2664            } else {
2665                flow pause
2666            }
2667        }
2668        "reset" {
2669            set _flow(time) 0
2670            set _settings($this-currenttime) 0
2671            SendCmd "flow reset"
2672            if { !$_flow(state) } {
2673                SendCmd "flow next"
2674            }
2675        }
2676        "next" {
2677            set w $itk_component(3dview)
2678            while { $w != "" }  {
2679                if { ![winfo ismapped $w] } {
2680                    flow stop
2681                    puts stderr "$w isn't mapped"
2682                    return
2683                }
2684                set w [winfo parent $w]
2685                if { [winfo toplevel $w] == $w } {
2686                    break
2687                }
2688            }
2689            incr _flow(time) $_flow(delay)
2690            if { $_flow(time) >= $_flow(duration) } {
2691                if { !$_settings($this-loop) } {
2692                    flow off
2693                    return
2694                }
2695                flow reset
2696            } else {
2697                SendCmd "flow next"
2698            }
2699            set _settings($this-currenttime) $_flow(time)
2700            $_dispatcher event -after $_flow(delay) !play
2701        }
2702        default {
2703            error "bad option \"$option\": should be play, stop, toggle, or reset."
2704        }
2705    }
2706}
2707
2708itcl::body Rappture::FlowvisViewer::WaitIcon  { option widget } {
2709    switch -- $option {
2710        "start" {
2711            $_dispatcher dispatch $this !waiticon \
2712                "[itcl::code $this WaitIcon "next" $widget] ; list"
2713            set _icon 0
2714            $widget configure -image [Rappture::icon bigroller${_icon}]
2715            $_dispatcher event -after 100 !waiticon
2716        }
2717        "next" {
2718            incr _icon
2719            if { $_icon >= 8 } {
2720                set _icon 0
2721            }
2722            $widget configure -image [Rappture::icon bigroller${_icon}]
2723            $_dispatcher event -after 100 !waiticon
2724        }
2725        "stop" {
2726            $_dispatcher cancel !waiticon
2727        }
2728    }
2729}
2730
2731itcl::body Rappture::FlowvisViewer::GetMovie { widget width height } {
2732    set token "movie[incr _nextToken]"
2733    set var ::Rappture::MolvisViewer::_hardcopy($this-$token)
2734    set $var ""
2735
2736    # Setup an automatic timeout procedure.
2737    $_dispatcher dispatch $this !movietimeout "set $var {} ; list"
2738
2739    set popup [Rappture::Balloon .movie -title "Generating video..."]
2740    set inner [$popup component inner]
2741    label $inner.title -text "Generating Hardcopy" -font "Arial 10 bold"
2742    label $inner.please -text "This may take a few minutes." -font "Arial 10"
2743    label $inner.icon -image [Rappture::icon bigroller0]
2744    button $inner.cancel -text "Cancel" -font "Arial 10 bold" \
2745        -command [list set $var ""]
2746    $_dispatcher event -after 60000 !movietimeout
2747    WaitIcon start $inner.icon
2748    bind $inner.cancel <KeyPress-Return> [list $inner.cancel invoke]
2749   
2750    blt::table $inner \
2751        0,0 $inner.title -columnspan 2 \
2752        1,0 $inner.please -anchor w \
2753        1,1 $inner.icon -anchor e  \
2754        2,0 $inner.cancel -columnspan 2
2755    blt::table configure $inner r0 -pady 4
2756    blt::table configure $inner r2 -pady 4
2757    grab set -local $inner
2758    focus $inner.cancel
2759   
2760    flow duration
2761    flow speed
2762    set nframes [expr $_flow(duration) / $_flow(delay)]
2763    set framerate [expr 1000.0 / $_flow(delay)]
2764    set bitrate 2000
2765
2766    SendCmd "flow video $width $height $nframes $framerate $bitrate"
2767   
2768    $popup activate $widget below
2769    update
2770    # We wait here for either
2771    #  1) the png to be delivered or
2772    #  2) timeout or 
2773    #  3) user cancels the operation.
2774    tkwait variable $var
2775
2776    # Clean up.
2777    $_dispatcher cancel !pngtimeout
2778    WaitIcon stop $inner.icon
2779    grab release $inner
2780    $popup deactivate
2781    destroy $popup
2782    update
2783
2784    if { $_hardcopy($this-$token) != "" } {
2785        return [list .png $_hardcopy($this-$token)]
2786    }
2787    return ""
2788}
2789
Note: See TracBrowser for help on using the repository browser.