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

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