source: branches/blt4/gui/scripts/flowvisviewer.tcl @ 1725

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