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

Last change on this file since 5095 was 5095, checked in by ldelgass, 8 years ago

merge r5090:r5094 from trunk

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