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

Last change on this file since 3592 was 3592, checked in by ldelgass, 11 years ago

Report clientinfo first thing after connecting to visualization server.

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