source: branches/blt4/gui/scripts/flowvisviewer.tcl @ 2287

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