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

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

Remove check that is no longer needed since numComponents should be correct for
both (deprecated) extents tag and new elemsize tag.

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