source: branches/1.4/gui/scripts/flowvisviewer.tcl @ 5183

Last change on this file since 5183 was 5183, checked in by ldelgass, 9 years ago

s/wmap/amap/

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