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

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

Fix camera reset for nanovis. Includes refactoring of vector/matrix classes
in nanovis to consolidate into vrmath library. Also add preliminary canonical
view control to clients for testing.

File size: 104.5 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 {}
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        pan-x   0
228        pan-y   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-pan-x             $_view(pan-x)
245        $this-pan-y             $_view(pan-y)
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            return $popup
814        }
815        now {
816            if { [winfo exists $popup] } {
817                $popup deactivate
818            }
819            switch -- $_downloadPopup(format) {
820                draft {
821                    # Get the image data (as base64) and decode it back to
822                    # binary.  This is better than writing to temporary
823                    # files.  When we switch to the BLT picture image it
824                    # won't be necessary to decode the image data.
825                    set bytes [$_image(plot) data -format "jpeg -quality 100"]
826                    set bytes [Rappture::encoding::decode -as b64 $bytes]
827                    return [list .jpg $bytes]
828                }
829                "640x480" {
830                    return [$this GetMovie [lindex $args 0] 640 480]
831                }
832                "1024x768" {
833                    return [$this GetMovie [lindex $args 0] 1024 768]
834                }
835                default {
836                    error "bad download format $_downloadPopup(format)"
837                }
838            }
839        }
840        default {
841            error "bad option \"$option\": should be coming, controls, now"
842        }
843    }
844}
845
846# ----------------------------------------------------------------------
847# USAGE: Connect ?<host:port>,<host:port>...?
848#
849# Clients use this method to establish a connection to a new
850# server, or to reestablish a connection to the previous server.
851# Any existing connection is automatically closed.
852# ----------------------------------------------------------------------
853itcl::body Rappture::FlowvisViewer::Connect {} {
854    set _hosts [GetServerList "nanovis"]
855    if { "" == $_hosts } {
856        return 0
857    }
858    set _reset 1
859    set result [VisViewer::Connect $_hosts]
860    if { $result } {
861        set w [winfo width $itk_component(3dview)]
862        set h [winfo height $itk_component(3dview)]
863        EventuallyResize $w $h
864    }
865    return $result
866}
867
868#
869# isconnected --
870#
871#       Indicates if we are currently connected to the visualization server.
872#
873itcl::body Rappture::FlowvisViewer::isconnected {} {
874    return [VisViewer::IsConnected]
875}
876
877#
878# disconnect --
879#
880itcl::body Rappture::FlowvisViewer::disconnect {} {
881    Disconnect
882}
883
884#
885# Disconnect --
886#
887#       Clients use this method to disconnect from the current rendering
888#       server.
889#
890itcl::body Rappture::FlowvisViewer::Disconnect {} {
891    VisViewer::Disconnect
892
893    # disconnected -- no more data sitting on server
894    array unset _serverObjs
895    set _sendobjs ""
896}
897
898# ----------------------------------------------------------------------
899# USAGE: SendDataObjs
900#
901# Used internally to send a series of volume objects off to the
902# server.  Sends each object, a little at a time, with updates in
903# between so the interface doesn't lock up.
904# ----------------------------------------------------------------------
905itcl::body Rappture::FlowvisViewer::SendDataObjs {} {
906    blt::busy hold $itk_component(hull)
907    foreach dataobj $_sendobjs {
908        foreach comp [$dataobj components] {
909            # Send the data as one huge base64-encoded mess -- yuck!
910            set data [$dataobj blob $comp]
911            set nbytes [string length $data]
912            set extents [$dataobj extents $comp]
913
914            # I have a field. Is a vector field or a volume field?
915            if { $extents == 1 } {
916                set cmd "volume data follows $nbytes $dataobj-$comp\n"
917            } else {
918                set cmd [FlowCmd $dataobj $comp $nbytes $extents]
919                if { $cmd == "" } {
920                    puts stderr "no command"
921                    continue
922                }
923            }
924            f { ![SendBytes $cmd] } {
925                puts stderr "can't send"
926                return
927            }
928            if { ![SendBytes $data] } {
929                puts stderr "can't send"
930                return
931            }
932            NameTransferFunc $dataobj $comp
933            set _recvObjs($dataobj-$comp) 1
934        }
935    }
936    set _sendobjs ""
937    blt::busy release $itk_component(hull)
938
939    # Turn on buffering of commands to the server.  We don't want to
940    # be preempted by a server disconnect/reconnect (which automatically
941    # generates a new call to Rebuild).   
942    StartBufferingCommands
943
944    # activate the proper volume
945    set _first [lindex [get] 0]
946    if { "" != $_first } {
947        set axis [$_first hints updir]
948        if {"" != $axis} {
949            SendCmd "up $axis"
950        }
951
952        if 0 {
953        set location [$_first hints camera]
954        if { $location != "" } {
955            array set _view $location
956        }
957        set _settings($this-qw)    $_view(qw)
958        set _settings($this-qx)    $_view(qx)
959        set _settings($this-qy)    $_view(qy)
960        set _settings($this-qz)    $_view(qz)
961        set _settings($this-pan-x) $_view(pan-x)
962        set _settings($this-pan-y) $_view(pan-y)
963        set _settings($this-zoom)  $_view(zoom)
964        set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
965        $_arcball quaternion $q
966        SendCmd "camera orient $q"
967        SendCmd "camera reset"
968        PanCamera
969        SendCmd "camera zoom $_view(zoom)"
970        }
971        # The active transfer function is by default the first component of
972        # the first data object.  This assumes that the data is always
973        # successfully transferred.
974        set comp [lindex [$_first components] 0]
975        set _activeTf [lindex $_obj2style($_first-$comp) 0]
976    }
977
978    SendCmd "flow reset"
979    StopBufferingCommands
980}
981
982# ----------------------------------------------------------------------
983# USAGE: SendTransferFuncs
984# ----------------------------------------------------------------------
985itcl::body Rappture::FlowvisViewer::SendTransferFuncs {} {
986    if { $_activeTf == "" } {
987        puts stderr "no active tf"
988        return
989    }
990    set tf $_activeTf
991    if { $_first == "" } {
992        puts stderr "no first"
993        return
994    }
995
996    # Ensure that the global opacity and thickness settings (in the slider
997    # settings widgets) are used for the active transfer-function.  Update the
998    # values in the _settings varible.
999    set value $_settings($this-opacity)
1000    set opacity [expr { double($value) * 0.01 }]
1001    set _settings($this-$tf-opacity) $opacity
1002    set value $_settings($this-thickness)
1003    # Scale values between 0.00001 and 0.01000
1004    set thickness [expr {double($value) * 0.0001}]
1005    set _settings($this-$tf-thickness) $thickness
1006
1007    foreach key [array names _obj2style $_first-*] {
1008        if { [info exists _obj2style($key)] } {
1009            foreach tf $_obj2style($key) {
1010                ComputeTransferFunc $tf
1011            }
1012        }
1013    }
1014    EventuallyResizeLegend
1015}
1016
1017# ----------------------------------------------------------------------
1018# USAGE: ReceiveImage -bytes $size -type $type -token $token
1019#
1020# Invoked automatically whenever the "image" command comes in from
1021# the rendering server.  Indicates that binary image data with the
1022# specified <size> will follow.
1023# ----------------------------------------------------------------------
1024itcl::body Rappture::FlowvisViewer::ReceiveImage { args } {
1025    array set info {
1026        -token "???"
1027        -bytes 0
1028        -type image
1029    }
1030    array set info $args
1031    set bytes [ReceiveBytes $info(-bytes)]
1032    ReceiveEcho <<line "<read $info(-bytes) bytes"
1033    switch -- $info(-type)  {
1034        "image" {
1035            $_image(plot) configure -data $bytes
1036            #puts stderr "image received [image width $_image(plot)] by [image height $_image(plot)]"
1037        }
1038        "print" {
1039            set tag $this-$info(-token)
1040            set _hardcopy($tag) $bytes
1041        }
1042        "movie" {
1043            set tag $this-$info(-token)
1044            set _hardcopy($tag) $bytes
1045        }
1046        default {
1047            puts stderr "unknown download type $info(-type)"
1048        }
1049    }
1050}
1051
1052#
1053# ReceiveLegend --
1054#
1055#       The procedure is the response from the render server to each "legend"
1056#       command.  The server sends back a "legend" command invoked our
1057#       the slave interpreter.  The purpose is to collect data of the image
1058#       representing the legend in the canvas.  In addition, the isomarkers
1059#       of the active transfer function are displayed.
1060#
1061#       I don't know is this is the right place to display the isomarkers.
1062#       I don't know all the different paths used to draw the plot. There's
1063#       "Rebuild", "add", etc.
1064#
1065itcl::body Rappture::FlowvisViewer::ReceiveLegend { tag vmin vmax size } {
1066    if { ![isconnected] } {
1067        return
1068    }
1069    #puts stderr "receive legend $tag $vmin $vmax $size"
1070    set bytes [ReceiveBytes $size]
1071    $_image(legend) configure -data $bytes
1072    ReceiveEcho <<line "<read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
1073
1074    set c $itk_component(legend)
1075    set w [winfo width $c]
1076    set h [winfo height $c]
1077    set lx 10
1078    # FIXME:  I don't know what I have to do this for the 2D flow
1079    #         example.  Otherwise the canvas background is white.
1080    #         I'll get to this when we add background changes into
1081    #         nanvis.
1082    $c configure -background black
1083    set ly [expr {$h - 1}]
1084    if {"" == [$c find withtag transfunc]} {
1085        $c create image 10 10 -anchor nw \
1086            -image $_image(legend) -tags transfunc
1087        $c create text $lx $ly -anchor sw \
1088            -fill $itk_option(-plotforeground) -tags "limits vmin"
1089        $c create text [expr {$w-$lx}] $ly -anchor se \
1090            -fill $itk_option(-plotforeground) -tags "limits vmax"
1091        $c lower transfunc
1092        $c bind transfunc <ButtonRelease-1> \
1093            [itcl::code $this AddIsoMarker %x %y]
1094    }
1095    # Display the markers used by the active transfer function.
1096    set tf $_obj2style($tag)
1097    array set limits [limits $tf]
1098    $c itemconfigure vmin -text [format %.2g $limits(vmin)]
1099    $c coords vmin $lx $ly
1100
1101    $c itemconfigure vmax -text [format %.2g $limits(vmax)]
1102    $c coords vmax [expr {$w-$lx}] $ly
1103
1104    if { [info exists _isomarkers($tf)] } {
1105        foreach m $_isomarkers($tf) {
1106            $m visible yes
1107        }
1108    }
1109}
1110
1111#
1112# ReceiveData --
1113#
1114#       The procedure is the response from the render server to each "data
1115#       follows" command.  The server sends back a "data" command invoked our
1116#       the slave interpreter.  The purpose is to collect the min/max of the
1117#       volume sent to the render server.  Since the client (flowvisviewer)
1118#       doesn't parse 3D data formats, we rely on the server (flowvis) to
1119#       tell us what the limits are.  Once we've received the limits to all
1120#       the data we've sent (tracked by _recvObjs) we can then determine
1121#       what the transfer functions are for these # volumes.
1122#
1123#       Note: There is a considerable tradeoff in having the server report
1124#             back what the data limits are.  It means that much of the code
1125#             having to do with transfer-functions has to wait for the data
1126#             to come back, since the isomarkers are calculated based upon
1127#             the data limits.  The client code is much messier because of
1128#             this.  The alternative is to parse any of the 3D formats on the
1129#             client side.
1130#
1131itcl::body Rappture::FlowvisViewer::ReceiveData { args } {
1132    if { ![isconnected] } {
1133        return
1134    }
1135    # Arguments from server are name value pairs. Stuff them in an array.
1136    array set values $args
1137    set tag $values(tag)
1138    set parts [split $tag -]
1139    set dataobj [lindex $parts 0]
1140    set _serverObjs($tag) 0
1141    set _limits($tag-min)  $values(min);  # Minimum value of the volume.
1142    set _limits($tag-max)  $values(max);  # Maximum value of the volume.
1143    unset _recvObjs($tag)
1144    if { [array size _recvObjs] == 0 } {
1145        updatetransferfuncs
1146    }
1147}
1148
1149#
1150# Rebuild --
1151#
1152# Called automatically whenever something changes that affects the data
1153# in the widget.  Clears any existing data and rebuilds the widget to
1154# display new data. 
1155#
1156itcl::body Rappture::FlowvisViewer::Rebuild {} {
1157
1158    # Hide all the isomarkers. Can't remove them. Have to remember the
1159    # settings since the user may have created/deleted/moved markers.
1160
1161    foreach tf [array names _isomarkers] {
1162        foreach m $_isomarkers($tf) {
1163            $m visible no
1164        }
1165    }
1166
1167    set _first ""
1168    # Turn on buffering of commands to the server.  We don't want to
1169    # be preempted by a server disconnect/reconnect (which automatically
1170    # generates a new call to Rebuild).   
1171    StartBufferingCommands
1172
1173    if { $_reset } {
1174        if { $_reportClientInfo }  {
1175            # Tell the server the name of the tool, the version, and
1176            # dataset that we are rendering.  Have to do it here because
1177            # we don't know what data objects are using the renderer until
1178            # be get here.
1179            global env
1180
1181            set info {}
1182            set user "???"
1183            if { [info exists env(USER)] } {
1184                set user $env(USER)
1185            }
1186            set session "???"
1187            if { [info exists env(SESSION)] } {
1188                set session $env(SESSION)
1189            }
1190            lappend info "hub" [exec hostname]
1191            lappend info "client" "flowvisviewer"
1192            lappend info "user" $user
1193            lappend info "session" $session
1194            SendCmd "clientinfo [list $info]"
1195        }
1196        set _width [winfo width $itk_component(3dview)]
1197        set _height [winfo height $itk_component(3dview)]
1198        Resize
1199    }
1200    foreach dataobj [get] {
1201        foreach comp [$dataobj components] {
1202            set tag $dataobj-$comp
1203            # Send the data as one huge base64-encoded mess -- yuck!
1204            set data [$dataobj blob $comp]
1205            set nbytes [string length $data]
1206            if { $_reportClientInfo }  {
1207                set info {}
1208                lappend info "tool_id"       [$dataobj hints toolId]
1209                lappend info "tool_name"     [$dataobj hints toolName]
1210                lappend info "tool_version"  [$dataobj hints toolRevision]
1211                lappend info "tool_title"    [$dataobj hints toolTitle]
1212                lappend info "dataset_label" [$dataobj hints label]
1213                lappend info "dataset_size"  $nbytes
1214                lappend info "dataset_tag"   $tag
1215                SendCmd "clientinfo [list $info]"
1216            }
1217            set extents [$dataobj extents $comp]
1218            # I have a field. Is a vector field or a volume field?
1219            if { $extents == 1 } {
1220                set cmd "volume data follows $nbytes $tag\n"
1221            } else {
1222                set cmd [FlowCmd $dataobj $comp $nbytes $extents]
1223                if { $cmd == "" } {
1224                    puts stderr "no command"
1225                    continue
1226                }
1227            }
1228            append _outbuf $cmd
1229            append _outbuf $data
1230            NameTransferFunc $dataobj $comp
1231            set _recvObjs($tag) 1
1232        }
1233    }
1234
1235    set _first [lindex [get] 0]
1236
1237    # Reset the camera and other view parameters
1238    InitSettings isosurface grid axes volume outline light2side light transp
1239   
1240    # nothing to send -- activate the proper volume
1241    if {"" != $_first} {
1242        AdjustSetting light
1243        AdjustSetting transp
1244        set axis [$_first hints updir]
1245        if {"" != $axis} {
1246            SendCmd "up $axis"
1247        }
1248        set location [$_first hints camera]
1249        if { $location != "" } {
1250            array set _view $location
1251        }
1252
1253    }
1254    set _settings($this-qw)    $_view(qw)
1255    set _settings($this-qx)    $_view(qx)
1256    set _settings($this-qy)    $_view(qy)
1257    set _settings($this-qz)    $_view(qz)
1258    set _settings($this-pan-x) $_view(pan-x)
1259    set _settings($this-pan-y) $_view(pan-y)
1260    set _settings($this-zoom)  $_view(zoom)
1261
1262    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1263    $_arcball quaternion $q
1264    SendCmd "camera orient $q"
1265    SendCmd "camera reset"
1266    PanCamera
1267    SendCmd "camera zoom $_view(zoom)"
1268
1269    foreach dataobj [get] {
1270        foreach comp [$dataobj components] {
1271            NameTransferFunc $dataobj $comp
1272        }
1273    }
1274
1275    # nothing to send -- activate the proper ivol
1276    set _first [lindex [get] 0]
1277    if {"" != $_first} {
1278        set axis [$_first hints updir]
1279        if {"" != $axis} {
1280            SendCmd "up $axis"
1281        }
1282        set location [$_first hints camera]
1283        if { $location != "" } {
1284            array set _view $location
1285        }
1286        set comp [lindex [$_first components] 0]
1287        set _activeTf [lindex $_obj2style($_first-$comp) 0]
1288    }
1289
1290
1291    # sync the state of slicers
1292    set vols [CurrentVolumeIds -cutplanes]
1293    foreach axis {x y z} {
1294        SendCmd "cutplane state $_settings($this-${axis}cutplane) $axis $vols"
1295        set pos [expr {0.01*$_settings($this-${axis}cutposition)}]
1296        SendCmd "cutplane position $pos $axis $vols"
1297    }
1298    SendCmd "volume data state $_settings($this-volume)"
1299    EventuallyResizeLegend
1300
1301    # Actually write the commands to the server socket.  If it fails, we don't
1302    # care.  We're finished here.
1303    blt::busy hold $itk_component(hull)
1304    StopBufferingCommands
1305    blt::busy release $itk_component(hull)
1306    set _reset 0
1307}
1308
1309# ----------------------------------------------------------------------
1310# USAGE: CurrentVolumeIds ?-cutplanes?
1311#
1312# Returns a list of volume server IDs for the current volume being
1313# displayed.  This is normally a single ID, but it might be a list
1314# of IDs if the current data object has multiple components.
1315# ----------------------------------------------------------------------
1316itcl::body Rappture::FlowvisViewer::CurrentVolumeIds {{what -all}} {
1317    return ""
1318    if { $_first == "" } {
1319        return
1320    }
1321    foreach key [array names _serverObjs *-*] {
1322        if {[string match $_first-* $key]} {
1323            array set style {
1324                -cutplanes 1
1325            }
1326            foreach {dataobj comp} [split $key -] break
1327            array set style [lindex [$dataobj components -style $comp] 0]
1328            if {$what != "-cutplanes" || $style(-cutplanes)} {
1329                lappend rlist $_serverObjs($key)
1330            }
1331        }
1332    }
1333    return $rlist
1334}
1335
1336# ----------------------------------------------------------------------
1337# USAGE: Zoom in
1338# USAGE: Zoom out
1339# USAGE: Zoom reset
1340#
1341# Called automatically when the user clicks on one of the zoom
1342# controls for this widget.  Changes the zoom for the current view.
1343# ----------------------------------------------------------------------
1344itcl::body Rappture::FlowvisViewer::Zoom {option} {
1345    switch -- $option {
1346        "in" {
1347            set _view(zoom) [expr {$_view(zoom)*1.25}]
1348            set _settings($this-zoom) $_view(zoom)
1349            SendCmd "camera zoom $_view(zoom)"
1350        }
1351        "out" {
1352            set _view(zoom) [expr {$_view(zoom)*0.8}]
1353            set _settings($this-zoom) $_view(zoom)
1354            SendCmd "camera zoom $_view(zoom)"
1355        }
1356        "reset" {
1357            array set _view {
1358                qw      0.853553
1359                qx      -0.353553
1360                qy      0.353553
1361                qz      0.146447
1362                zoom    1.0
1363                pan-x   0
1364                pan-y   0
1365            }
1366            if { $_first != "" } {
1367                set location [$_first hints camera]
1368                if { $location != "" } {
1369                    array set _view $location
1370                }
1371            }
1372            set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1373            $_arcball quaternion $q
1374            SendCmd "camera orient $q"
1375            SendCmd "camera reset"
1376            set _settings($this-qw)    $_view(qw)
1377            set _settings($this-qx)    $_view(qx)
1378            set _settings($this-qy)    $_view(qy)
1379            set _settings($this-qz)    $_view(qz)
1380            set _settings($this-pan-x) $_view(pan-x)
1381            set _settings($this-pan-y) $_view(pan-y)
1382            set _settings($this-zoom)  $_view(zoom)
1383            $itk_component(orientation) value "default"
1384        }
1385    }
1386}
1387
1388itcl::body Rappture::FlowvisViewer::PanCamera {} {
1389    #set x [expr ($_view(pan-x)) / $_limits(xrange)]
1390    #set y [expr ($_view(pan-y)) / $_limits(yrange)]
1391    set x $_view(pan-x)
1392    set y $_view(pan-y)
1393    SendCmd "camera pan $x $y"
1394}
1395
1396# ----------------------------------------------------------------------
1397# USAGE: Rotate click <x> <y>
1398# USAGE: Rotate drag <x> <y>
1399# USAGE: Rotate release <x> <y>
1400#
1401# Called automatically when the user clicks/drags/releases in the
1402# plot area.  Moves the plot according to the user's actions.
1403# ----------------------------------------------------------------------
1404itcl::body Rappture::FlowvisViewer::Rotate {option x y} {
1405    switch -- $option {
1406        click {
1407            $itk_component(3dview) configure -cursor fleur
1408            set _click(x) $x
1409            set _click(y) $y
1410        }
1411        drag {
1412            if {[array size _click] == 0} {
1413                Rotate click $x $y
1414            } else {
1415                set w [winfo width $itk_component(3dview)]
1416                set h [winfo height $itk_component(3dview)]
1417                if {$w <= 0 || $h <= 0} {
1418                    return
1419                }
1420
1421                if {[catch {
1422                    # this fails sometimes for no apparent reason
1423                    set dx [expr {double($x-$_click(x))/$w}]
1424                    set dy [expr {double($y-$_click(y))/$h}]
1425                }]} {
1426                    return
1427                }
1428
1429                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1430                foreach { _view(qw) _view(qx) _view(qy) _view(qz) } $q break
1431                set _settings($this-qw) $_view(qw)
1432                set _settings($this-qx) $_view(qx)
1433                set _settings($this-qy) $_view(qy)
1434                set _settings($this-qz) $_view(qz)
1435                SendCmd "camera orient $q"
1436
1437                set _click(x) $x
1438                set _click(y) $y
1439            }
1440        }
1441        release {
1442            Rotate drag $x $y
1443            $itk_component(3dview) configure -cursor ""
1444            catch {unset _click}
1445        }
1446        default {
1447            error "bad option \"$option\": should be click, drag, release"
1448        }
1449    }
1450}
1451
1452# ----------------------------------------------------------------------
1453# USAGE: $this Pan click x y
1454#        $this Pan drag x y
1455#        $this Pan release x y
1456#
1457# Called automatically when the user clicks on one of the zoom
1458# controls for this widget.  Changes the zoom for the current view.
1459# ----------------------------------------------------------------------
1460itcl::body Rappture::FlowvisViewer::Pan {option x y} {
1461    # Experimental stuff
1462    set w [winfo width $itk_component(3dview)]
1463    set h [winfo height $itk_component(3dview)]
1464    if { $option == "set" } {
1465        set x [expr $x / double($w)]
1466        set y [expr $y / double($h)]
1467        set _view(pan-x) [expr $_view(pan-x) + $x]
1468        set _view(pan-y) [expr $_view(pan-y) + $y]
1469        PanCamera
1470        set _settings($this-pan-x) $_view(pan-x)
1471        set _settings($this-pan-y) $_view(pan-y)
1472        return
1473    }
1474    if { $option == "click" } {
1475        set _click(x) $x
1476        set _click(y) $y
1477        $itk_component(3dview) configure -cursor hand1
1478    }
1479    if { $option == "drag" || $option == "release" } {
1480        set dx [expr ($_click(x) - $x)/double($w)]
1481        set dy [expr ($_click(y) - $y)/double($h)]
1482        set _click(x) $x
1483        set _click(y) $y
1484        set _view(pan-x) [expr $_view(pan-x) - $dx]
1485        set _view(pan-y) [expr $_view(pan-y) - $dy]
1486        PanCamera
1487        set _settings($this-pan-x) $_view(pan-x)
1488        set _settings($this-pan-y) $_view(pan-y)
1489    }
1490    if { $option == "release" } {
1491        $itk_component(3dview) configure -cursor ""
1492    }
1493}
1494
1495
1496# ----------------------------------------------------------------------
1497# USAGE: Flow movie record|stop|play ?on|off|toggle?
1498#
1499# Called when the user clicks on the record, stop or play buttons
1500# for flow visualization.
1501# ----------------------------------------------------------------------
1502itcl::body Rappture::FlowvisViewer::Flow {option args} {
1503    switch -- $option {
1504        movie {
1505            if {[llength $args] < 1 || [llength $args] > 2} {
1506                error "wrong # args: should be \"Flow movie record|stop|play ?on|off|toggle?\""
1507            }
1508            set action [lindex $args 0]
1509            set op [lindex $args 1]
1510            if {$op == ""} { set op "on" }
1511
1512            set current [State $action]
1513            if {$op == "toggle"} {
1514                if {$current == "on"} {
1515                    set op "off"
1516                } else {
1517                    set op "on"
1518                }
1519            }
1520            set cmds ""
1521            switch -- $action {
1522                record {
1523                    if { [$itk_component(rewind) cget -relief] != "sunken" } {
1524                        $itk_component(rewind) configure -relief sunken
1525                        $itk_component(stop) configure -relief raised
1526                        $itk_component(play) configure -relief raised
1527                        set inner $itk_component(settingsFrame)
1528                        set frames [$inner.framecnt value]
1529                        set _settings(nsteps) $frames
1530                        set cmds "flow capture $frames"
1531                        SendCmd $cmds
1532                    }
1533                }
1534                stop {
1535                    if { [$itk_component(stop) cget -relief] != "sunken" } {
1536                        $itk_component(rewind) configure -relief raised
1537                        $itk_component(stop) configure -relief sunken
1538                        $itk_component(play) configure -relief raised
1539                        _pause
1540                        set cmds "flow reset"
1541                        SendCmd $cmds
1542                    }
1543                }
1544                play {
1545                    if { [$itk_component(play) cget -relief] != "sunken" } {
1546                        $itk_component(rewind) configure -relief raised
1547                        $itk_component(stop) configure -relief raised
1548                        $itk_component(play) configure \
1549                            -image [Rappture::icon flow-pause] \
1550                            -relief sunken
1551                        bind $itk_component(play) <ButtonPress> \
1552                            [itcl::code $this _pause]
1553                        flow next
1554                    }
1555                }
1556                default {
1557                    error "bad option \"$option\": should be one of record|stop|play"
1558                }
1559
1560            }
1561        }
1562        default {
1563            error "bad option \"$option\": should be movie"
1564        }
1565    }
1566}
1567
1568# ----------------------------------------------------------------------
1569# USAGE: Play
1570#
1571# ----------------------------------------------------------------------
1572itcl::body Rappture::FlowvisViewer::Play {} {
1573    SendCmd "flow next"
1574    set delay [expr {int(ceil(pow($_settings(speed)/10.0+2,2.0)*15))}]
1575    $_dispatcher event -after $delay !play
1576}
1577
1578# ----------------------------------------------------------------------
1579# USAGE: Pause
1580#
1581# Invoked when the user hits the "pause" button to stop playing the
1582# current sequence of frames as a movie.
1583# ----------------------------------------------------------------------
1584itcl::body Rappture::FlowvisViewer::Pause {} {
1585    $_dispatcher cancel !play
1586
1587    # Toggle the button to "play" mode
1588    $itk_component(play) configure \
1589        -image [Rappture::icon flow-start] \
1590        -relief raised
1591    bind $itk_component(play) <ButtonPress> \
1592        [itcl::code $this Flow movie play toggle]
1593}
1594
1595# ----------------------------------------------------------------------
1596# USAGE: InitSettings <what> ?<value>?
1597#
1598# Used internally to update rendering settings whenever parameters
1599# change in the popup settings panel.  Sends the new settings off
1600# to the back end.
1601# ----------------------------------------------------------------------
1602itcl::body Rappture::FlowvisViewer::InitSettings { args } {
1603    foreach arg $args {
1604        AdjustSetting $arg
1605    }
1606}
1607
1608# ----------------------------------------------------------------------
1609# USAGE: AdjustSetting <what> ?<value>?
1610#
1611# Used internally to update rendering settings whenever parameters
1612# change in the popup settings panel.  Sends the new settings off
1613# to the back end.
1614# ----------------------------------------------------------------------
1615itcl::body Rappture::FlowvisViewer::AdjustSetting {what {value ""}} {
1616    switch -- $what {
1617        colormap {
1618            set color [$itk_component(colormap) value]
1619            set _settings(colormap) $color
1620            #ResetColormap $color
1621        }
1622        light {
1623            if { $_first != "" } {
1624                set comp [lindex [$_first components] 0]
1625                set tag $_first-$comp
1626                set diffuse [expr {0.01*$_settings($this-light)}]
1627                set ambient [expr {1.0 - $diffuse}]
1628                set specularLevel 0.3
1629                set specularExp 90.0
1630                SendCmd "$tag configure -ambient $ambient -diffuse $diffuse -specularLevel $specularLevel -specularExp $specularExp"
1631            }
1632        }
1633        light2side {
1634            if { $_first != "" } {
1635                set comp [lindex [$_first components] 0]
1636                set tag $_first-$comp
1637                set val $_settings($this-light2side)
1638                SendCmd "$tag configure -light2side $val"
1639            }
1640        }
1641        transp {
1642            if { $_first != "" } {
1643                set comp [lindex [$_first components] 0]
1644                set tag $_first-$comp
1645                set opacity [expr { 0.01 * double($_settings($this-transp)) }]
1646                SendCmd "$tag configure -opacity $opacity"
1647            }
1648        }
1649        opacity {
1650            if { $_first != "" && $_activeTf != "" } {
1651                set opacity [expr { 0.01 * double($_settings($this-opacity)) }]
1652                set tf $_activeTf
1653                set _settings($this-$tf-opacity) $opacity
1654                updatetransferfuncs
1655            }
1656        }
1657
1658        thickness {
1659            if { $_first != "" && $_activeTf != "" } {
1660                set val $_settings($this-thickness)
1661                # Scale values between 0.00001 and 0.01000
1662                set sval [expr {0.0001*double($val)}]
1663                set tf $_activeTf
1664                set _settings($this-$tf-thickness) $sval
1665                updatetransferfuncs
1666            }
1667        }
1668        "outline" {
1669            if { $_first != "" } {
1670                set comp [lindex [$_first components] 0]
1671                set tag $_first-$comp
1672                SendCmd "$tag configure -outline $_settings($this-outline)"
1673            }
1674        }
1675        "isosurface" {
1676            if { [isconnected] } {
1677                SendCmd "volume shading isosurface $_settings($this-isosurface)"
1678            }
1679        }
1680        "grid" {
1681            if { [isconnected] } {
1682                SendCmd "grid visible $_settings($this-grid)"
1683            }
1684        }
1685        "axes" {
1686            if { [isconnected] } {
1687                SendCmd "axis visible $_settings($this-axes)"
1688            }
1689        }
1690        "legend" {
1691            if { $_settings($this-legend) } {
1692                blt::table $itk_component(plotarea) \
1693                    0,0 $itk_component(3dview) -fill both \
1694                    1,0 $itk_component(legend) -fill x
1695                blt::table configure $itk_component(plotarea) r1 -resize none
1696            } else {
1697                blt::table forget $itk_component(legend)
1698            }
1699        }
1700        "volume" {
1701            if { $_first != "" } {
1702                set comp [lindex [$_first components] 0]
1703                set tag $_first-$comp
1704                SendCmd "$tag configure -volume $_settings($this-volume)"
1705            }
1706        }
1707        "xcutplane" - "ycutplane" - "zcutplane" {
1708            set axis [string range $what 0 0]
1709            set bool $_settings($this-$what)
1710            if { [isconnected] } {
1711                set vols [CurrentVolumeIds -cutplanes]
1712                SendCmd "cutplane state $bool $axis $vols"
1713            }
1714            if { $bool } {
1715                $itk_component(${axis}CutScale) configure -state normal \
1716                    -troughcolor white
1717            } else {
1718                $itk_component(${axis}CutScale) configure -state disabled \
1719                    -troughcolor grey82
1720            }
1721        }
1722        default {
1723            error "don't know how to fix $what"
1724        }
1725    }
1726}
1727
1728# ----------------------------------------------------------------------
1729# USAGE: ResizeLegend
1730#
1731# Used internally to update the legend area whenever it changes size
1732# or when the field changes.  Asks the server to send a new legend
1733# for the current field.
1734# ----------------------------------------------------------------------
1735itcl::body Rappture::FlowvisViewer::ResizeLegend {} {
1736    set _resizeLegendPending 0
1737    set lineht [font metrics $itk_option(-font) -linespace]
1738    set w [expr {$_width-20}]
1739    set h [expr {[winfo height $itk_component(legend)]-20-$lineht}]
1740
1741    if { $_first == "" } {
1742        return
1743    }
1744    set comp [lindex [$_first components] 0]
1745    set tag $_first-$comp
1746    #set _activeTf [lindex $_obj2style($tag) 0]
1747    if {$w > 0 && $h > 0 && "" != $_activeTf} {
1748        #SendCmd "legend $_activeTf $w $h"
1749        SendCmd "$tag legend $w $h"
1750    } else {
1751    # Can't do this as this will remove the items associated with the
1752    # isomarkers.
1753
1754    #$itk_component(legend) delete all
1755    }
1756}
1757
1758#
1759# NameTransferFunc --
1760#
1761#       Creates a transfer function name based on the <style> settings in the
1762#       library run.xml file. This placeholder will be used later to create
1763#       and send the actual transfer function once the data info has been sent
1764#       to us by the render server. [We won't know the volume limits until the
1765#       server parses the 3D data and sends back the limits via ReceiveData.]
1766#
1767#       FIXME: The current way we generate transfer-function names completely
1768#              ignores the -markers option.  The problem is that we are forced
1769#              to compute the name from an increasing complex set of values:
1770#              color, levels, marker, opacity.  I think we're stuck doing it
1771#              now.
1772#
1773itcl::body Rappture::FlowvisViewer::NameTransferFunc { dataobj comp } {
1774    array set style {
1775        -color BCGYR
1776        -levels 6
1777        -opacity 1.0
1778        -light 40
1779        -transp 50
1780    }
1781    array set style [lindex [$dataobj components -style $comp] 0]
1782    set _settings($this-light) $style(-light)
1783    set _settings($this-transp) $style(-transp)
1784    set _settings($this-opacity) [expr $style(-opacity) * 100]
1785    set tf "$style(-color):$style(-levels):$style(-opacity)"
1786    set _obj2style($dataobj-$comp) $tf
1787    lappend _style2objs($tf) $dataobj $comp
1788    return $tf
1789}
1790
1791#
1792# ComputeTransferFunc --
1793#
1794#   Computes and sends the transfer function to the render server.  It's
1795#   assumed that the volume data limits are known and that the global
1796#   transfer-functions slider values have be setup.  Both parts are
1797#   needed to compute the relative value (location) of the marker, and
1798#   the alpha map of the transfer function.
1799#
1800itcl::body Rappture::FlowvisViewer::ComputeTransferFunc { tf } {
1801    array set style {
1802        -color BCGYR
1803        -levels 6
1804        -opacity 1.0
1805        -light 40
1806        -transp 50
1807    }
1808    set dataobj ""; set comp ""
1809    foreach {dataobj comp} $_style2objs($tf) break
1810    if { $dataobj == "" } {
1811        return 0
1812    }
1813    array set style [lindex [$dataobj components -style $comp] 0]
1814
1815
1816    # We have to parse the style attributes for a volume using this
1817    # transfer-function *once*.  This sets up the initial isomarkers for the
1818    # transfer function.  The user may add/delete markers, so we have to
1819    # maintain a list of markers for each transfer-function.  We use the one
1820    # of the volumes (the first in the list) using the transfer-function as a
1821    # reference.
1822    #
1823    # FIXME: The current way we generate transfer-function names completely
1824    #        ignores the -markers option.  The problem is that we are forced
1825    #        to compute the name from an increasing complex set of values:
1826    #        color, levels, marker, opacity.  I think the cow's out of the
1827    #        barn on this one.
1828
1829    if { ![info exists _isomarkers($tf)] } {
1830        # Have to defer creation of isomarkers until we have data limits
1831        if { [info exists style(-markers)] &&
1832             [llength $style(-markers)] > 0  } {
1833            ParseMarkersOption $tf $style(-markers)
1834        } else {
1835            ParseLevelsOption $tf $style(-levels)
1836        }
1837    }
1838    if { [info exists style(-nonuniformcolors)] } {
1839        foreach { value color } $style(-nonuniformcolors) {
1840            append cmap "$value [Color2RGB $color] "
1841        }
1842    } else {
1843        set cmap [ColorsToColormap $style(-color)]
1844    }
1845    set tag $this-$tf
1846    if { ![info exists _settings($tag-opacity)] } {
1847        set _settings($tag-opacity) $style(-opacity)
1848    }
1849    set max 1.0 ;#$_settings($tag-opacity)
1850   
1851    set isovalues {}
1852    foreach m $_isomarkers($tf) {
1853        lappend isovalues [$m relval]
1854    }
1855    # Sort the isovalues
1856    set isovalues [lsort -real $isovalues]
1857
1858    if { ![info exists _settings($tag-thickness)]} {
1859        set _settings($tag-thickness) 0.005
1860    }
1861    set delta $_settings($tag-thickness)
1862
1863    set first [lindex $isovalues 0]
1864    set last [lindex $isovalues end]
1865    set wmap ""
1866    if { $first == "" || $first != 0.0 } {
1867        lappend wmap 0.0 0.0
1868    }
1869    foreach x $isovalues {
1870        set x1 [expr {$x-$delta-0.00001}]
1871        set x2 [expr {$x-$delta}]
1872        set x3 [expr {$x+$delta}]
1873        set x4 [expr {$x+$delta+0.00001}]
1874        if { $x1 < 0.0 } {
1875            set x1 0.0
1876        } elseif { $x1 > 1.0 } {
1877            set x1 1.0
1878        }
1879        if { $x2 < 0.0 } {
1880            set x2 0.0
1881        } elseif { $x2 > 1.0 } {
1882            set x2 1.0
1883        }
1884        if { $x3 < 0.0 } {
1885            set x3 0.0
1886        } elseif { $x3 > 1.0 } {
1887            set x3 1.0
1888        }
1889        if { $x4 < 0.0 } {
1890            set x4 0.0
1891        } elseif { $x4 > 1.0 } {
1892            set x4 1.0
1893        }
1894        # add spikes in the middle
1895        lappend wmap $x1 0.0
1896        lappend wmap $x2 $max
1897        lappend wmap $x3 $max
1898        lappend wmap $x4 0.0
1899    }
1900    if { $last == "" || $last != 1.0 } {
1901        lappend wmap 1.0 0.0
1902    }
1903    SendCmd "transfunc define $tf { $cmap } { $wmap }"
1904    return [SendCmd "$dataobj-$comp configure -transferfunction $tf"]
1905}
1906
1907# ----------------------------------------------------------------------
1908# CONFIGURATION OPTION: -plotbackground
1909# ----------------------------------------------------------------------
1910itcl::configbody Rappture::FlowvisViewer::plotbackground {
1911    if { [isconnected] } {
1912        foreach {r g b} [Color2RGB $itk_option(-plotbackground)] break
1913        #fix this!
1914        #SendCmd "color background $r $g $b"
1915    }
1916}
1917
1918# ----------------------------------------------------------------------
1919# CONFIGURATION OPTION: -plotforeground
1920# ----------------------------------------------------------------------
1921itcl::configbody Rappture::FlowvisViewer::plotforeground {
1922    if { [isconnected] } {
1923        foreach {r g b} [Color2RGB $itk_option(-plotforeground)] break
1924        #fix this!
1925        #SendCmd "color background $r $g $b"
1926    }
1927}
1928
1929# ----------------------------------------------------------------------
1930# CONFIGURATION OPTION: -plotoutline
1931# ----------------------------------------------------------------------
1932itcl::configbody Rappture::FlowvisViewer::plotoutline {
1933    # Must check if we are connected because this routine is called from the
1934    # class body when the -plotoutline itk_option is defined.  At that point
1935    # the FlowvisViewer class constructor hasn't been called, so we can't
1936    # start sending commands to visualization server.
1937    if { [isconnected] } {
1938        if {"" == $itk_option(-plotoutline)} {
1939            SendCmd "volume outline state off"
1940        } else {
1941            SendCmd "volume outline state on"
1942            SendCmd "volume outline color [Color2RGB $itk_option(-plotoutline)]"
1943        }
1944    }
1945}
1946
1947#
1948# The -levels option takes a single value that represents the number
1949# of evenly distributed markers based on the current data range. Each
1950# marker is a relative value from 0.0 to 1.0.
1951#
1952itcl::body Rappture::FlowvisViewer::ParseLevelsOption { tf levels } {
1953    set c $itk_component(legend)
1954    regsub -all "," $levels " " levels
1955    if {[string is int $levels]} {
1956        for {set i 1} { $i <= $levels } {incr i} {
1957            set x [expr {double($i)/($levels+1)}]
1958            set m [Rappture::IsoMarker \#auto $c $this $tf]
1959            $m relval $x
1960            lappend _isomarkers($tf) $m
1961        }
1962    } else {
1963        foreach x $levels {
1964            set m [Rappture::IsoMarker \#auto $c $this $tf]
1965            $m relval $x
1966            lappend _isomarkers($tf) $m
1967        }
1968    }
1969}
1970
1971#
1972# The -markers option takes a list of zero or more values (the values
1973# may be separated either by spaces or commas) that have the following
1974# format:
1975#
1976#   N%  Percent of current total data range.  Converted to
1977#       to a relative value between 0.0 and 1.0.
1978#   N   Absolute value of marker.  If the marker is outside of
1979#       the current range, it will be displayed on the outer
1980#       edge of the legends, but it range it represents will
1981#       not be seen.
1982#
1983itcl::body Rappture::FlowvisViewer::ParseMarkersOption { tf markers } {
1984    set c $itk_component(legend)
1985    regsub -all "," $markers " " markers
1986    foreach marker $markers {
1987        set n [scan $marker "%g%s" value suffix]
1988        if { $n == 2 && $suffix == "%" } {
1989            # ${n}% : Set relative value.
1990            set value [expr {$value * 0.01}]
1991            set m [Rappture::IsoMarker \#auto $c $this $tf]
1992            $m relval $value
1993            lappend _isomarkers($tf) $m
1994        } else {
1995            # ${n} : Set absolute value.
1996            set m [Rappture::IsoMarker \#auto $c $this $tf]
1997            $m absval $value
1998            lappend _isomarkers($tf) $m
1999        }
2000    }
2001}
2002
2003# ----------------------------------------------------------------------
2004# USAGE: UndateTransferFuncs
2005# ----------------------------------------------------------------------
2006itcl::body Rappture::FlowvisViewer::updatetransferfuncs {} {
2007    $_dispatcher event -after 100 !send_transfunc
2008}
2009
2010itcl::body Rappture::FlowvisViewer::AddIsoMarker { x y } {
2011    if { $_activeTf == "" } {
2012        error "active transfer function isn't set"
2013    }
2014    set tf $_activeTf
2015    set c $itk_component(legend)
2016    set m [Rappture::IsoMarker \#auto $c $this $tf]
2017    set w [winfo width $c]
2018    $m relval [expr {double($x-10)/($w-20)}]
2019    lappend _isomarkers($tf) $m
2020    updatetransferfuncs
2021    return 1
2022}
2023
2024itcl::body Rappture::FlowvisViewer::rmdupmarker { marker x } {
2025    set tf [$marker transferfunc]
2026    set bool 0
2027    if { [info exists _isomarkers($tf)] } {
2028        set list {}
2029        set marker [namespace tail $marker]
2030        foreach m $_isomarkers($tf) {
2031            set sx [$m screenpos]
2032            if { $m != $marker } {
2033                if { $x >= ($sx-3) && $x <= ($sx+3) } {
2034                    $marker relval [$m relval]
2035                    itcl::delete object $m
2036                    bell
2037                    set bool 1
2038                    continue
2039                }
2040            }
2041            lappend list $m
2042        }
2043        set _isomarkers($tf) $list
2044        updatetransferfuncs
2045    }
2046    return $bool
2047}
2048
2049itcl::body Rappture::FlowvisViewer::overmarker { marker x } {
2050    set tf [$marker transferfunc]
2051    if { [info exists _isomarkers($tf)] } {
2052        set marker [namespace tail $marker]
2053        foreach m $_isomarkers($tf) {
2054            set sx [$m screenpos]
2055            if { $m != $marker } {
2056                set bool [expr { $x >= ($sx-3) && $x <= ($sx+3) }]
2057                $m activate $bool
2058            }
2059        }
2060    }
2061    return ""
2062}
2063
2064itcl::body Rappture::FlowvisViewer::limits { tf } {
2065    set _limits(vmin) 0.0
2066    set _limits(vmax) 1.0
2067    if { ![info exists _style2objs($tf)] } {
2068        puts stderr "no style2objs for $tf tf=($tf)"
2069        return [array get _limits]
2070    }
2071    set min ""; set max ""
2072    foreach {dataobj comp} $_style2objs($tf) {
2073        set tag $dataobj-$comp
2074        if { ![info exists _serverObjs($tag)] } {
2075            puts stderr "$tag not in serverObjs?"
2076            continue
2077        }
2078        if { ![info exists _limits($tag-min)] } {
2079            puts stderr "$tag no min?"
2080            continue
2081        }
2082        if { $min == "" || $min > $_limits($tag-min) } {
2083            set min $_limits($tag-min)
2084        }
2085        if { $max == "" || $max < $_limits($tag-max) } {
2086            set max $_limits($tag-max)
2087        }
2088    }
2089    if { $min != "" } {
2090        set _limits(vmin) $min
2091    }
2092    if { $max != "" } {
2093        set _limits(vmax) $max
2094    }
2095    return [array get _limits]
2096}
2097
2098itcl::body Rappture::FlowvisViewer::BuildViewTab {} {
2099    foreach { key value } {
2100        grid            0
2101        axes            0
2102        outline         1
2103        volume          1
2104        legend          1
2105        particles       1
2106        lic             1
2107    } {
2108        set _settings($this-$key) $value
2109    }
2110
2111    set fg [option get $itk_component(hull) font Font]
2112    #set bfg [option get $itk_component(hull) boldFont Font]
2113
2114    set inner [$itk_component(main) insert end \
2115        -title "View Settings" \
2116        -icon [Rappture::icon wrench]]
2117    $inner configure -borderwidth 4
2118
2119    set ::Rappture::FlowvisViewer::_settings($this-isosurface) 0
2120    checkbutton $inner.isosurface \
2121        -text "Isosurface shading" \
2122        -variable [itcl::scope _settings($this-isosurface)] \
2123        -command [itcl::code $this AdjustSetting isosurface] \
2124        -font "Arial 9"
2125
2126    checkbutton $inner.axes \
2127        -text "Axes" \
2128        -variable [itcl::scope _settings($this-axes)] \
2129        -command [itcl::code $this AdjustSetting axes] \
2130        -font "Arial 9"
2131
2132    checkbutton $inner.grid \
2133        -text "Grid" \
2134        -variable [itcl::scope _settings($this-grid)] \
2135        -command [itcl::code $this AdjustSetting grid] \
2136        -font "Arial 9"
2137
2138    checkbutton $inner.outline \
2139        -text "Outline" \
2140        -variable [itcl::scope _settings($this-outline)] \
2141        -command [itcl::code $this AdjustSetting outline] \
2142        -font "Arial 9"
2143
2144    checkbutton $inner.legend \
2145        -text "Legend" \
2146        -variable [itcl::scope _settings($this-legend)] \
2147        -command [itcl::code $this AdjustSetting legend] \
2148        -font "Arial 9"
2149
2150    checkbutton $inner.volume \
2151        -text "Volume" \
2152        -variable [itcl::scope _settings($this-volume)] \
2153        -command [itcl::code $this AdjustSetting volume] \
2154        -font "Arial 9"
2155
2156    checkbutton $inner.particles \
2157        -text "Particles" \
2158        -variable [itcl::scope _settings($this-particles)] \
2159        -command [itcl::code $this AdjustSetting particles] \
2160        -font "Arial 9"
2161
2162    checkbutton $inner.lic \
2163        -text "Lic" \
2164        -variable [itcl::scope _settings($this-lic)] \
2165        -command [itcl::code $this AdjustSetting lic] \
2166        -font "Arial 9"
2167
2168    frame $inner.frame
2169
2170    blt::table $inner \
2171        0,0 $inner.axes  -cspan 2 -anchor w \
2172        1,0 $inner.grid  -cspan 2 -anchor w \
2173        2,0 $inner.outline  -cspan 2 -anchor w \
2174        3,0 $inner.volume  -cspan 2 -anchor w \
2175        4,0 $inner.legend  -cspan 2 -anchor w
2176
2177    bind $inner <Map> [itcl::code $this GetFlowInfo $inner]
2178
2179    blt::table configure $inner r* -resize none
2180    blt::table configure $inner r5 -resize expand
2181}
2182
2183itcl::body Rappture::FlowvisViewer::BuildVolumeTab {} {
2184    foreach { key value } {
2185        light2side      0
2186        light           40
2187        transp          50
2188        opacity         100
2189        thickness       350
2190    } {
2191        set _settings($this-$key) $value
2192    }
2193
2194    set inner [$itk_component(main) insert end \
2195        -title "Volume Settings" \
2196        -icon [Rappture::icon volume-on]]
2197    $inner configure -borderwidth 4
2198
2199    set fg [option get $itk_component(hull) font Font]
2200    #set bfg [option get $itk_component(hull) boldFont Font]
2201
2202    checkbutton $inner.vol -text "Show volume" -font $fg \
2203        -text "Volume" \
2204        -variable [itcl::scope _settings($this-volume)] \
2205        -command [itcl::code $this AdjustSetting volume] \
2206        -font "Arial 9"
2207
2208    label $inner.shading -text "Shading:" -font $fg
2209
2210    checkbutton $inner.light2side -text "Two-sided lighting" -font $fg \
2211        -variable [itcl::scope _settings($this-light2side)] \
2212        -command [itcl::code $this AdjustSetting light2side]
2213
2214    label $inner.dim -text "Glow" -font $fg
2215    ::scale $inner.light -from 0 -to 100 -orient horizontal \
2216        -variable [itcl::scope _settings($this-light)] \
2217        -width 10 \
2218        -showvalue off -command [itcl::code $this AdjustSetting light]
2219    label $inner.bright -text "Surface" -font $fg
2220
2221    label $inner.fog -text "Clear" -font $fg
2222    ::scale $inner.transp -from 0 -to 100 -orient horizontal \
2223        -variable [itcl::scope _settings($this-transp)] \
2224        -width 10 \
2225        -showvalue off -command [itcl::code $this AdjustSetting transp]
2226    label $inner.plastic -text "Opaque" -font $fg
2227
2228    label $inner.clear -text "Clear" -font $fg
2229    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
2230        -variable [itcl::scope _settings($this-opacity)] \
2231        -width 10 \
2232        -showvalue off -command [itcl::code $this AdjustSetting opacity]
2233    label $inner.opaque -text "Opaque" -font $fg
2234
2235    label $inner.thin -text "Thin" -font $fg
2236    ::scale $inner.thickness -from 0 -to 1000 -orient horizontal \
2237        -variable [itcl::scope _settings($this-thickness)] \
2238        -width 10 \
2239        -showvalue off -command [itcl::code $this AdjustSetting thickness]
2240    label $inner.thick -text "Thick" -font $fg
2241
2242    label $inner.colormap_l -text "Colormap" -font "Arial 9"
2243    itk_component add colormap {
2244        Rappture::Combobox $inner.colormap -width 10 -editable no
2245    }
2246
2247    $inner.colormap choices insert end \
2248        "BCGYR"              "BCGYR"            \
2249        "BGYOR"              "BGYOR"            \
2250        "blue"               "blue"             \
2251        "blue-to-brown"      "blue-to-brown"    \
2252        "blue-to-orange"     "blue-to-orange"   \
2253        "blue-to-grey"       "blue-to-grey"     \
2254        "green-to-magenta"   "green-to-magenta" \
2255        "greyscale"          "greyscale"        \
2256        "nanohub"            "nanohub"          \
2257        "rainbow"            "rainbow"          \
2258        "spectral"           "spectral"         \
2259        "ROYGB"              "ROYGB"            \
2260        "RYGCB"              "RYGCB"            \
2261        "brown-to-blue"      "brown-to-blue"    \
2262        "grey-to-blue"       "grey-to-blue"     \
2263        "orange-to-blue"     "orange-to-blue"   \
2264        "none"               "none"
2265
2266    $itk_component(colormap) value "BCGYR"
2267    bind $inner.colormap <<Value>> \
2268        [itcl::code $this AdjustSetting colormap]
2269
2270    blt::table $inner \
2271        0,0 $inner.vol -cspan 4 -anchor w -pady 2 \
2272        1,0 $inner.shading -cspan 4 -anchor w -pady {10 2} \
2273        2,0 $inner.light2side -cspan 4 -anchor w -pady 2 \
2274        3,0 $inner.dim -anchor e -pady 2 \
2275        3,1 $inner.light -cspan 2 -pady 2 -fill x \
2276        3,3 $inner.bright -anchor w -pady 2 \
2277        4,0 $inner.fog -anchor e -pady 2 \
2278        4,1 $inner.transp -cspan 2 -pady 2 -fill x \
2279        4,3 $inner.plastic -anchor w -pady 2 \
2280        5,0 $inner.thin -anchor e -pady 2 \
2281        5,1 $inner.thickness -cspan 2 -pady 2 -fill x\
2282        5,3 $inner.thick -anchor w -pady 2
2283
2284    blt::table configure $inner c0 c1 c3 r* -resize none
2285    blt::table configure $inner r6 -resize expand
2286}
2287
2288itcl::body Rappture::FlowvisViewer::BuildCutplanesTab {} {
2289    set inner [$itk_component(main) insert end \
2290        -title "Cutplane Settings" \
2291        -icon [Rappture::icon cutbutton]]
2292    $inner configure -borderwidth 4
2293
2294    # X-value slicer...
2295    itk_component add xCutButton {
2296        Rappture::PushButton $inner.xbutton \
2297            -onimage [Rappture::icon x-cutplane] \
2298            -offimage [Rappture::icon x-cutplane] \
2299            -command [itcl::code $this AdjustSetting xcutplane] \
2300            -variable [itcl::scope _settings($this-xcutplane)]
2301    }
2302    Rappture::Tooltip::for $itk_component(xCutButton) \
2303        "Toggle the X cut plane on/off"
2304
2305    itk_component add xCutScale {
2306        ::scale $inner.xval -from 100 -to 0 \
2307            -width 10 -orient vertical -showvalue off \
2308            -borderwidth 1 -highlightthickness 0 \
2309            -command [itcl::code $this Slice move x] \
2310            -variable [itcl::scope _settings($this-xcutposition)]
2311    } {
2312        usual
2313        ignore -borderwidth -highlightthickness
2314    }
2315    # Set the default cutplane value before disabling the scale.
2316    $itk_component(xCutScale) set 50
2317    $itk_component(xCutScale) configure -state disabled
2318    Rappture::Tooltip::for $itk_component(xCutScale) \
2319        "@[itcl::code $this SlicerTip x]"
2320
2321    # Y-value slicer...
2322    itk_component add yCutButton {
2323        Rappture::PushButton $inner.ybutton \
2324            -onimage [Rappture::icon y-cutplane] \
2325            -offimage [Rappture::icon y-cutplane] \
2326            -command [itcl::code $this AdjustSetting ycutplane] \
2327            -variable [itcl::scope _settings($this-ycutplane)]
2328    }
2329    Rappture::Tooltip::for $itk_component(yCutButton) \
2330        "Toggle the Y cut plane on/off"
2331
2332    itk_component add yCutScale {
2333        ::scale $inner.yval -from 100 -to 0 \
2334            -width 10 -orient vertical -showvalue off \
2335            -borderwidth 1 -highlightthickness 0 \
2336            -command [itcl::code $this Slice move y] \
2337            -variable [itcl::scope _settings($this-ycutposition)]
2338    } {
2339        usual
2340        ignore -borderwidth -highlightthickness
2341    }
2342    Rappture::Tooltip::for $itk_component(yCutScale) \
2343        "@[itcl::code $this SlicerTip y]"
2344    # Set the default cutplane value before disabling the scale.
2345    $itk_component(yCutScale) set 50
2346    $itk_component(yCutScale) configure -state disabled
2347
2348    # Z-value slicer...
2349    itk_component add zCutButton {
2350        Rappture::PushButton $inner.zbutton \
2351            -onimage [Rappture::icon z-cutplane] \
2352            -offimage [Rappture::icon z-cutplane] \
2353            -command [itcl::code $this AdjustSetting zcutplane] \
2354            -variable [itcl::scope _settings($this-zcutplane)]
2355    }
2356    Rappture::Tooltip::for $itk_component(zCutButton) \
2357        "Toggle the Z cut plane on/off"
2358
2359    itk_component add zCutScale {
2360        ::scale $inner.zval -from 100 -to 0 \
2361            -width 10 -orient vertical -showvalue off \
2362            -borderwidth 1 -highlightthickness 0 \
2363            -command [itcl::code $this Slice move z] \
2364            -variable [itcl::scope _settings($this-zcutposition)]
2365    } {
2366        usual
2367        ignore -borderwidth -highlightthickness
2368    }
2369    $itk_component(zCutScale) set 50
2370    $itk_component(zCutScale) configure -state disabled
2371    #$itk_component(zCutScale) configure -state disabled
2372    Rappture::Tooltip::for $itk_component(zCutScale) \
2373        "@[itcl::code $this SlicerTip z]"
2374
2375    blt::table $inner \
2376        1,1 $itk_component(xCutButton) \
2377        1,2 $itk_component(yCutButton) \
2378        1,3 $itk_component(zCutButton) \
2379        0,1 $itk_component(xCutScale) \
2380        0,2 $itk_component(yCutScale) \
2381        0,3 $itk_component(zCutScale) \
2382
2383    blt::table configure $inner r0 r1 c* -resize none
2384    blt::table configure $inner r2 c4 -resize expand
2385    blt::table configure $inner c0 -width 2
2386    blt::table configure $inner c1 c2 c3 -padx 2
2387}
2388
2389itcl::body Rappture::FlowvisViewer::BuildCameraTab {} {
2390    set inner [$itk_component(main) insert end \
2391        -title "Camera Settings" \
2392        -icon [Rappture::icon camera]]
2393    $inner configure -borderwidth 4
2394
2395    set row 0
2396    label $inner.orientation_l -text "View" -font "Arial 9"
2397    itk_component add orientation {
2398        Rappture::Combobox $inner.orientation -width 10 -editable no
2399    }
2400    $inner.orientation choices insert end \
2401        "1 0 0 0" "front" \
2402        "0 0 1 0" "back" \
2403        "0.707107 -0.707107 0 0" "top" \
2404        "0.707107 0.707107 0 0" "bottom" \
2405        "0.707107 0 -0.707107 0" "left" \
2406        "0.707107 0 0.707107 0" "right" \
2407        "0.853553 -0.353553 0.353553 0.146447" "default"
2408    $itk_component(orientation) value "default"
2409    bind $inner.orientation <<Value>> [itcl::code $this SetOrientation]
2410    if 1 {
2411    blt::table $inner \
2412            $row,0 $inner.orientation_l -anchor e -pady 2 \
2413            $row,1 $inner.orientation -anchor w -pady 2 -fill x
2414    blt::table configure $inner r$row -resize none
2415    incr row
2416    }
2417
2418    set labels { qw qx qy qz pan-x pan-y zoom }
2419    foreach tag $labels {
2420        label $inner.${tag}label -text $tag -font "Arial 9"
2421        entry $inner.${tag} -font "Arial 9"  -bg white \
2422            -textvariable [itcl::scope _settings($this-$tag)]
2423        bind $inner.${tag} <KeyPress-Return> \
2424            [itcl::code $this camera set ${tag}]
2425        blt::table $inner \
2426            $row,0 $inner.${tag}label -anchor e -pady 2 \
2427            $row,1 $inner.${tag} -anchor w -pady 2
2428        blt::table configure $inner r$row -resize none
2429        incr row
2430    }
2431    blt::table configure $inner c0 c1 -resize none
2432    blt::table configure $inner c2 -resize expand
2433    blt::table configure $inner r$row -resize expand
2434}
2435
2436itcl::body Rappture::FlowvisViewer::GetFlowInfo { w } {
2437    set flowobj ""
2438    foreach key [array names _obj2flow] {
2439        set flowobj $_obj2flow($key)
2440        break
2441    }
2442    if { $flowobj == "" } {
2443        return
2444    }
2445    if { [winfo exists $w.frame] } {
2446        destroy $w.frame
2447    }
2448    set inner [frame $w.frame]
2449    blt::table $w \
2450        5,0 $inner -fill both -cspan 2 -anchor nw
2451    array set hints [$flowobj hints]
2452    checkbutton $inner.showstreams -text "Streams Plane" \
2453        -variable [itcl::scope _settings($this-streams)] \
2454        -command  [itcl::code $this streams $key $hints(name)]  \
2455        -font "Arial 9"
2456    Rappture::Tooltip::for $inner.showstreams $hints(description)
2457
2458    checkbutton $inner.showarrows -text "Arrows" \
2459        -variable [itcl::scope _settings($this-arrows)] \
2460        -command  [itcl::code $this arrows $key $hints(name)]  \
2461        -font "Arial 9"
2462
2463    label $inner.particles -text "Particles"         -font "Arial 9 bold"
2464    label $inner.boxes -text "Boxes"         -font "Arial 9 bold"
2465
2466    blt::table $inner \
2467        1,0 $inner.showstreams  -anchor w \
2468        2,0 $inner.showarrows  -anchor w
2469    blt::table configure $inner c0 c1 -resize none
2470    blt::table configure $inner c2 -resize expand
2471
2472    set row 3
2473    set particles [$flowobj particles]
2474    if { [llength $particles] > 0 } {
2475        blt::table $inner $row,0 $inner.particles  -anchor w
2476        incr row
2477    }
2478    foreach part $particles {
2479        array unset info
2480        array set info $part
2481        set name $info(name)
2482        if { ![info exists _settings($this-particles-$name)] } {
2483            set _settings($this-particles-$name) $info(hide)
2484        }
2485        checkbutton $inner.part$row -text $info(label) \
2486            -variable [itcl::scope _settings($this-particles-$name)] \
2487            -onvalue 0 -offvalue 1 \
2488            -command [itcl::code $this particles $key $name] \
2489            -font "Arial 9"
2490        Rappture::Tooltip::for $inner.part$row $info(description)
2491        blt::table $inner $row,0 $inner.part$row -anchor w
2492        if { !$_settings($this-particles-$name) } {
2493            $inner.part$row select
2494        }
2495        incr row
2496    }
2497    set boxes [$flowobj boxes]
2498    if { [llength $boxes] > 0 } {
2499        blt::table $inner $row,0 $inner.boxes  -anchor w
2500        incr row
2501    }
2502    foreach box $boxes {
2503        array unset info
2504        array set info $box
2505        set name $info(name)
2506        if { ![info exists _settings($this-box-$name)] } {
2507            set _settings($this-box-$name) $info(hide)
2508        }
2509        checkbutton $inner.box$row -text $info(label) \
2510            -variable [itcl::scope _settings($this-box-$name)] \
2511            -onvalue 0 -offvalue 1 \
2512            -command [itcl::code $this box $key $name] \
2513            -font "Arial 9"
2514        Rappture::Tooltip::for $inner.box$row $info(description)
2515        blt::table $inner $row,0 $inner.box$row -anchor w
2516        if { !$_settings($this-box-$name) } {
2517            $inner.box$row select
2518        }
2519        incr row
2520    }
2521    blt::table configure $inner r* -resize none
2522    blt::table configure $inner r$row -resize expand
2523    blt::table configure $inner c3 -resize expand
2524    event generate [winfo parent [winfo parent $w]] <Configure>
2525}
2526
2527itcl::body Rappture::FlowvisViewer::particles { tag name } {
2528    set bool $_settings($this-particles-$name)
2529    SendCmd "$tag particles configure {$name} -hide $bool"
2530}
2531
2532itcl::body Rappture::FlowvisViewer::box { tag name } {
2533    set bool $_settings($this-box-$name)
2534    SendCmd "$tag box configure {$name} -hide $bool"
2535}
2536
2537itcl::body Rappture::FlowvisViewer::streams { tag name } {
2538    set bool $_settings($this-streams)
2539    SendCmd "$tag configure -slice $bool"
2540}
2541
2542itcl::body Rappture::FlowvisViewer::arrows { tag name } {
2543    set bool $_settings($this-arrows)
2544    SendCmd "$tag configure -arrows $bool"
2545}
2546
2547# ----------------------------------------------------------------------
2548# USAGE: Slice move x|y|z <newval>
2549#
2550# Called automatically when the user drags the slider to move the
2551# cut plane that slices 3D data.  Gets the current value from the
2552# slider and moves the cut plane to the appropriate point in the
2553# data set.
2554# ----------------------------------------------------------------------
2555itcl::body Rappture::FlowvisViewer::Slice {option args} {
2556    switch -- $option {
2557        move {
2558            if {[llength $args] != 2} {
2559                error "wrong # args: should be \"Slice move x|y|z newval\""
2560            }
2561            set axis [lindex $args 0]
2562            set newval [lindex $args 1]
2563            set newpos [expr {0.01*$newval}]
2564
2565            # show the current value in the readout
2566
2567            set ids [CurrentVolumeIds -cutplanes]
2568            SendCmd "cutplane position $newpos $axis $ids"
2569        }
2570        default {
2571            error "bad option \"$option\": should be axis, move, or volume"
2572        }
2573    }
2574}
2575
2576# ----------------------------------------------------------------------
2577# USAGE: SlicerTip <axis>
2578#
2579# Used internally to generate a tooltip for the x/y/z slicer controls.
2580# Returns a message that includes the current slicer value.
2581# ----------------------------------------------------------------------
2582itcl::body Rappture::FlowvisViewer::SlicerTip {axis} {
2583    set val [$itk_component(${axis}CutScale) get]
2584#    set val [expr {0.01*($val-50)
2585#        *($_limits(${axis}max)-$_limits(${axis}min))
2586#          + 0.5*($_limits(${axis}max)+$_limits(${axis}min))}]
2587    return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
2588}
2589
2590itcl::body Rappture::FlowvisViewer::Resize {} {
2591    $_arcball resize $_width $_height
2592    SendCmd "screen size $_width $_height"
2593    set _resizePending 0
2594}
2595
2596itcl::body Rappture::FlowvisViewer::EventuallyResize { w h } {
2597    set _width $w
2598    set _height $h
2599    $_arcball resize $w $h
2600    if { !$_resizePending } {
2601        $_dispatcher event -after 200 !resize
2602        set _resizePending 1
2603    }
2604}
2605
2606itcl::body Rappture::FlowvisViewer::EventuallyResizeLegend {} {
2607    if { !$_resizeLegendPending } {
2608        $_dispatcher event -after 100 !legend
2609        set _resizeLegendPending 1
2610    }
2611}
2612
2613itcl::body Rappture::FlowvisViewer::EventuallyGoto { nSteps } {
2614    set _flow(goto) $nSteps
2615    if { !$_gotoPending } {
2616        $_dispatcher event -after 1000 !goto
2617        set _gotoPending 1
2618    }
2619}
2620
2621#  camera --
2622itcl::body Rappture::FlowvisViewer::camera {option args} {
2623    switch -- $option {
2624        "show" {
2625            puts [array get _view]
2626        }
2627        "set" {
2628            set who [lindex $args 0]
2629            set x $_settings($this-$who)
2630            set code [catch { string is double $x } result]
2631            if { $code != 0 || !$result } {
2632                set _settings($this-$who) $_view($who)
2633                return
2634            }
2635            switch -- $who {
2636                "pan-x" - "pan-y" {
2637                    set _view($who) $_settings($this-$who)
2638                    PanCamera
2639                }
2640                "qx" - "qy" - "qz" - "qw" {
2641                    set _view($who) $_settings($this-$who)
2642                    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
2643                    $_arcball quaternion $q
2644                    SendCmd "camera orient $q"
2645                }
2646                "zoom" {
2647                    set _view($who) $_settings($this-$who)
2648                    SendCmd "camera zoom $_view(zoom)"
2649                }
2650            }
2651        }
2652    }
2653}
2654
2655itcl::body Rappture::FlowvisViewer::FlowCmd { dataobj comp nbytes extents } {
2656    set tag "$dataobj-$comp"
2657    if { ![info exists _obj2flow($tag)] } {
2658        append cmd "flow add $tag\n"
2659        append cmd "$tag data follows $nbytes $extents\n"
2660        return $cmd
2661    }
2662    set flowobj $_obj2flow($tag)
2663    if { $flowobj == "" } {
2664        puts stderr "no flowobj"
2665        return ""
2666    }
2667    set cmd {}
2668    append cmd "if {\[flow exists $tag\]} {flow delete $tag}\n"
2669    array set info  [$flowobj hints]
2670    set _settings($this-volume) $info(volume)
2671    set _settings($this-outline) $info(outline)
2672    set _settings($this-arrows) $info(arrows)
2673    set _settings($this-duration) $info(duration)
2674    $itk_component(speed) value $info(speed)
2675    append cmd "flow add $tag"
2676    append cmd " -position $info(position)"
2677    append cmd " -axis $info(axis)"
2678    append cmd " -volume $info(volume)"
2679    append cmd " -outline $info(outline)"
2680    append cmd " -slice $info(streams)"
2681    append cmd " -arrows $info(arrows)\n"
2682    foreach part [$flowobj particles] {
2683        array unset info
2684        array set info $part
2685        set color [Color2RGB $info(color)]
2686        append cmd "$tag particles add $info(name)"
2687        append cmd " -position $info(position)"
2688        append cmd " -hide $info(hide)"
2689        append cmd " -axis $info(axis)"
2690        append cmd " -color {$color}"
2691        append cmd " -size $info(size)\n"
2692    }
2693    foreach box [$flowobj boxes] {
2694        array unset info
2695        set info(corner1) ""
2696        set info(corner2) ""
2697        array set info $box
2698        if { $info(corner1) == "" || $info(corner2) == "" } {
2699            continue
2700        }
2701        set color [Color2RGB $info(color)]
2702        append cmd "$tag box add $info(name)"
2703        append cmd " -color {$color}"
2704        append cmd " -hide $info(hide)"
2705        append cmd " -linewidth $info(linewidth) "
2706        append cmd " -corner1 {$info(corner1)} "
2707        append cmd " -corner2 {$info(corner2)}\n"
2708    }   
2709    append cmd "$tag data follows $nbytes $extents\n"
2710    return $cmd
2711}
2712
2713
2714#
2715# flow --
2716#
2717# Called when the user clicks on the stop or play buttons
2718# for flow visualization.
2719#
2720#        $this flow play
2721#        $this flow stop
2722#        $this flow toggle
2723#        $this flow reset
2724#        $this flow pause
2725#        $this flow next
2726#
2727itcl::body Rappture::FlowvisViewer::flow { args } {
2728    set option [lindex $args 0]
2729    switch -- $option {
2730        "goto2" {
2731            puts stderr "actually sending \"flow goto $_flow(goto)\""
2732            SendCmd "flow goto $_flow(goto)"
2733            set _gotoPending 0
2734        }
2735        "goto" {
2736            puts stderr "flow goto to $_settings($this-currenttime)"
2737            # Figure out how many steps to the current time based upon
2738            # the speed and duration.
2739            set current $_settings($this-currenttime)
2740            set speed [$itk_component(speed) value]
2741            set time [str2millisecs $_settings($this-duration)]
2742            $itk_component(dial) configure -max $time
2743            set delay [expr int(round(500.0/$speed))]
2744            set timePerStep [expr {double($time) / $delay}]
2745            set nSteps [expr {int(ceil($current/$timePerStep))}]
2746            EventuallyGoto $nSteps
2747        }
2748        "speed" {
2749            set speed [$itk_component(speed) value]
2750            set _flow(delay) [expr int(round(500.0/$speed))]
2751        }
2752        "duration" {
2753            set max [str2millisecs $_settings($this-duration)]
2754            if { $max < 0 } {
2755                bell
2756                return
2757            }
2758            set _flow(duration) $max
2759            set _settings($this-duration) [millisecs2str $max]
2760            $itk_component(dial) configure -max $max
2761        }
2762        "off" {
2763            set _flow(state) 0
2764            $_dispatcher cancel !play
2765            $itk_component(play) deselect
2766        }
2767        "on" {
2768            flow speed
2769            flow duration
2770            set _flow(state) 1
2771            set _settings($this-currenttime) 0
2772            $itk_component(play) select
2773        }
2774        "stop" {
2775            if { $_flow(state) } {
2776                flow off
2777                flow reset
2778            }
2779        }
2780        "pause" {
2781            if { $_flow(state) } {
2782                flow off
2783            }
2784        }
2785        "play" {
2786            # If the flow is currently off, then restart it.
2787            if { !$_flow(state) } {
2788                flow on
2789                # If we're at the end of the flow, reset the flow.
2790                set _settings($this-currenttime) \
2791                    [expr {$_settings($this-currenttime) + $_flow(delay)}]
2792                if { $_settings($this-currenttime) >= $_flow(duration) } {
2793                    set _settings($this-step) 1
2794                    SendCmd "flow reset"
2795                }
2796                flow next
2797            }
2798        }
2799        "toggle" {
2800            if { $_settings($this-play) } {
2801                flow play
2802            } else {
2803                flow pause
2804            }
2805        }
2806        "reset" {
2807            set _settings($this-currenttime) 0
2808            SendCmd "flow reset"
2809            if { !$_flow(state) } {
2810                SendCmd "flow next"
2811            }
2812        }
2813        "next" {
2814            if { ![winfo viewable $itk_component(3dview)] } {
2815                flow stop
2816                return
2817            }
2818            set _settings($this-currenttime) \
2819                [expr {$_settings($this-currenttime) + $_flow(delay)}]
2820            if { $_settings($this-currenttime) >= $_flow(duration) } {
2821                if { !$_settings($this-loop) } {
2822                    flow off
2823                    return
2824                }
2825                flow reset
2826            } else {
2827                SendCmd "flow next"
2828            }
2829            $_dispatcher event -after $_flow(delay) !play
2830        }
2831        default {
2832            error "bad option \"$option\": should be play, stop, toggle, or reset."
2833        }
2834    }
2835}
2836
2837itcl::body Rappture::FlowvisViewer::WaitIcon  { option widget } {
2838    switch -- $option {
2839        "start" {
2840            $_dispatcher dispatch $this !waiticon \
2841                "[itcl::code $this WaitIcon "next" $widget] ; list"
2842            set _icon 0
2843            $widget configure -image [Rappture::icon bigroller${_icon}]
2844            $_dispatcher event -after 100 !waiticon
2845        }
2846        "next" {
2847            incr _icon
2848            if { $_icon >= 8 } {
2849                set _icon 0
2850            }
2851            $widget configure -image [Rappture::icon bigroller${_icon}]
2852            $_dispatcher event -after 100 !waiticon
2853        }
2854        "stop" {
2855            $_dispatcher cancel !waiticon
2856        }
2857    }
2858}
2859
2860itcl::body Rappture::FlowvisViewer::GetPngImage  { widget width height } {
2861    set token "print[incr _nextToken]"
2862    set var ::Rappture::FlowvisViewer::_hardcopy($this-$token)
2863    set $var ""
2864
2865    # Setup an automatic timeout procedure.
2866    $_dispatcher dispatch $this !pngtimeout "set $var {} ; list"
2867
2868    set popup .flowvisviewerprint
2869    if {![winfo exists $popup]} {
2870        Rappture::Balloon $popup -title "Generating file..."
2871        set inner [$popup component inner]
2872        label $inner.title -text "Generating hardcopy." -font "Arial 10 bold"
2873        label $inner.please -text "This may take a minute." -font "Arial 10"
2874        label $inner.icon -image [Rappture::icon bigroller0]
2875        button $inner.cancel -text "Cancel" -font "Arial 10 bold" \
2876            -command [list set $var ""]
2877        blt::table $inner \
2878            0,0 $inner.title -cspan 2 \
2879            1,0 $inner.please -anchor w \
2880            1,1 $inner.icon -anchor e  \
2881            2,0 $inner.cancel -cspan 2
2882        blt::table configure $inner r0 -pady 4
2883        blt::table configure $inner r2 -pady 4
2884        bind $inner.cancel <KeyPress-Return> [list $inner.cancel invoke]
2885    } else {
2886        set inner [$popup component inner]
2887    }
2888
2889    $_dispatcher event -after 60000 !pngtimeout
2890    WaitIcon start $inner.icon
2891    grab set $inner
2892    focus $inner.cancel
2893
2894    SendCmd "print $token $width $height"
2895
2896    $popup activate $widget below
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    # Timeout is set to 10 minutes.
2947    $_dispatcher event -after 600000 !movietimeout
2948    WaitIcon start $inner.icon
2949    grab set $inner
2950    focus $inner.cancel
2951   
2952    flow duration
2953    flow speed
2954    set nframes [expr round($_flow(duration) / $_flow(delay))]
2955    set framerate [expr 1000.0 / $_flow(delay)]
2956
2957    # These are specific to MPEG1 video generation
2958    set framerate 25.0
2959    set bitrate 6.0e+6
2960
2961    set start [clock seconds]
2962    SendCmd "flow video $token -width $w -height $h -numframes $nframes "
2963   
2964    $popup activate $widget below
2965    update
2966    # We wait here until
2967    #  1. the movie is delivered or
2968    #  2. we've timed out or 
2969    #  3. the user has canceled the operation.b
2970    tkwait variable $var
2971
2972    puts stderr "Video generated in [expr [clock seconds] - $start] seconds."
2973
2974    # Clean up.
2975    $_dispatcher cancel !movietimeout
2976    WaitIcon stop $inner.icon
2977    grab release $inner
2978    $popup deactivate
2979    destroy $popup
2980    update
2981
2982    # This will both cancel the movie generation (if it hasn't already
2983    # completed) and reset the flow.
2984    SendCmd "flow reset"
2985    if { $_hardcopy($this-$token) != "" } {
2986        return [list .mpg $_hardcopy($this-$token)]
2987    }
2988    return ""
2989}
2990
2991itcl::body Rappture::FlowvisViewer::str2millisecs { value } {
2992    set parts [split $value :]
2993    set secs 0
2994    set mins 0
2995    if { [llength $parts] == 1 } {
2996        scan [lindex $parts 0] "%d" secs
2997    } else {
2998        scan [lindex $parts 1] "%d" secs
2999        scan [lindex $parts 0] "%d" mins
3000    }
3001    set ms [expr {(($mins * 60) + $secs) * 1000.0}]
3002    if { $ms > 600000.0 } {
3003        set ms 600000.0
3004    }
3005    if { $ms == 0.0 } {
3006        set ms 60000.0
3007    }
3008    return $ms
3009}
3010
3011itcl::body Rappture::FlowvisViewer::millisecs2str { value } {
3012    set min [expr floor($value / 60000.0)]
3013    set sec [expr ($value - ($min*60000.0)) / 1000.0]
3014    return [format %02d:%02d [expr round($min)] [expr round($sec)]]
3015}
3016
3017itcl::body Rappture::FlowvisViewer::SetOrientation {} {
3018    set quat [$itk_component(orientation) value]
3019    set quat [$itk_component(orientation) translate $quat]
3020    foreach name { qw qx qy qz } comp $quat {
3021        set _view($name) $comp
3022        set _settings($this-$name) $comp
3023    }
3024    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
3025    $_arcball quaternion $q
3026    SendCmd "camera orient $q"
3027    SendCmd "camera reset"
3028    set $_view(pan-x) 0.0
3029    set $_view(pan-y) 0.0
3030    set $_view(zoom) 1.0
3031    set _settings($this-pan-x) $_view(pan-x)
3032    set _settings($this-pan-y) $_view(pan-y)
3033    set _settings($this-zoom)  $_view(zoom)
3034}
Note: See TracBrowser for help on using the repository browser.