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

Last change on this file since 5275 was 5275, checked in by ldelgass, 6 years ago

merge r5258,r5270,r5274 from trunk

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