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

Last change on this file since 4749 was 4749, checked in by ldelgass, 10 years ago

Fix reporting of tool info to render servers

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