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

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

bgcolor fixes for nanovis clients

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