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

Last change on this file since 2606 was 2606, checked in by gah, 13 years ago
File size: 100.6 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).view -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    blt::busy hold $itk_component(hull)
916    foreach dataobj $_sendobjs {
917        foreach comp [$dataobj components] {
918            # Send the data as one huge base64-encoded mess -- yuck!
919            set data [$dataobj blob $comp]
920            set nbytes [string length $data]
921            set extents [$dataobj extents $comp]
922
923            # I have a field. Is a vector field or a volume field?
924            if { $extents == 1 } {
925                set cmd "volume data follows $nbytes $dataobj-$comp\n"
926            } else {
927                set cmd [FlowCmd $dataobj $comp $nbytes $extents]
928                if { $cmd == "" } {
929                    puts stderr "no command"
930                    continue
931                }
932            }
933            f { ![SendBytes $cmd] } {
934                puts stderr "can't send"
935                return
936            }
937            if { ![SendBytes $data] } {
938                puts stderr "can't send"
939                return
940            }
941            NameTransferFunc $dataobj $comp
942            set _recvObjs($dataobj-$comp) 1
943        }
944    }
945    set _sendobjs ""
946    blt::busy release $itk_component(hull)
947
948    # Turn on buffering of commands to the server.  We don't want to
949    # be preempted by a server disconnect/reconnect (which automatically
950    # generates a new call to Rebuild).   
951    set _buffering 1
952
953    # activate the proper volume
954    set _first [lindex [get] 0]
955    if { "" != $_first } {
956        set axis [$_first hints updir]
957        if {"" != $axis} {
958            SendCmd "up $axis"
959        }
960
961        if 0 {
962        set location [$_first hints camera]
963        if { $location != "" } {
964            array set _view $location
965        }
966        set _settings($this-theta) $_view(theta)
967        set _settings($this-phi)   $_view(phi)
968        set _settings($this-psi)   $_view(psi)
969        set _settings($this-pan-x) $_view(pan-x)
970        set _settings($this-pan-y) $_view(pan-y)
971        set _settings($this-zoom)  $_view(zoom)
972        set xyz [Euler2XYZ $_view(theta) $_view(phi) $_view(psi)]
973        SendCmd "camera angle $xyz"
974        PanCamera
975        SendCmd "camera zoom $_view(zoom)"
976        }
977        # The active transfer function is by default the first component of
978        # the first data object.  This assumes that the data is always
979        # successfully transferred.
980        set comp [lindex [$_first components] 0]
981        set _activeTf [lindex $_obj2style($_first-$comp) 0]
982    }
983
984    SendCmd "flow reset"
985
986    # Actually write the commands to the server socket.  If it fails, we don't
987    # care.  We're finished here.
988    SendBytes $_outbuf;                 
989    set _buffering 0;                   # Turn off buffering.
990    set _outbuf "";                     # Clear the buffer.             
991}
992
993# ----------------------------------------------------------------------
994# USAGE: SendTransferFuncs
995# ----------------------------------------------------------------------
996itcl::body Rappture::FlowvisViewer::SendTransferFuncs {} {
997    if { $_activeTf == "" } {
998        puts stderr "no active tf"
999        return
1000    }
1001    set tf $_activeTf
1002    if { $_first == "" } {
1003        puts stderr "no first"
1004        return
1005    }
1006
1007    # Insure that the global opacity and thickness settings (in the slider
1008    # settings widgets) are used for the active transfer-function.  Update the
1009    # values in the _settings varible.
1010    set value $_settings($this-opacity)
1011    set opacity [expr { double($value) * 0.01 }]
1012    set _settings($this-$tf-opacity) $opacity
1013    set value $_settings($this-thickness)
1014    # Scale values between 0.00001 and 0.01000
1015    set thickness [expr {double($value) * 0.0001}]
1016    set _settings($this-$tf-thickness) $thickness
1017
1018    foreach key [array names _obj2style $_first-*] {
1019        if { [info exists _obj2style($key)] } {
1020            foreach tf $_obj2style($key) {
1021                ComputeTransferFunc $tf
1022            }
1023        }
1024    }
1025    EventuallyResizeLegend
1026}
1027
1028# ----------------------------------------------------------------------
1029# USAGE: ReceiveImage -bytes $size -type $type -token $token
1030#
1031# Invoked automatically whenever the "image" command comes in from
1032# the rendering server.  Indicates that binary image data with the
1033# specified <size> will follow.
1034# ----------------------------------------------------------------------
1035itcl::body Rappture::FlowvisViewer::ReceiveImage { args } {
1036    array set info {
1037        -token "???"
1038        -bytes 0
1039        -type image
1040    }
1041    array set info $args
1042    set bytes [ReceiveBytes $info(-bytes)]
1043    ReceiveEcho <<line "<read $info(-bytes) bytes"
1044    switch -- $info(-type)  {
1045        "image" {
1046            $_image(plot) configure -data $bytes
1047            #puts stderr "image received [image width $_image(plot)] by [image height $_image(plot)]"
1048        }
1049        "print" {
1050            set tag $this-$info(-token)
1051            set _hardcopy($tag) $bytes
1052        }
1053        "movie" {
1054            puts stderr "read [string length $bytes] bytes type=$info(-type) token=$info(-token)"
1055            set tag $this-$info(-token)
1056            set _hardcopy($tag) $bytes
1057        }
1058        default {
1059            puts stderr "unknown download type $info(-type)"
1060        }
1061    }
1062}
1063
1064#
1065# ReceiveLegend --
1066#
1067#       The procedure is the response from the render server to each "legend"
1068#       command.  The server sends back a "legend" command invoked our
1069#       the slave interpreter.  The purpose is to collect data of the image
1070#       representing the legend in the canvas.  In addition, the isomarkers
1071#       of the active transfer function are displayed.
1072#
1073#       I don't know is this is the right place to display the isomarkers.
1074#       I don't know all the different paths used to draw the plot. There's
1075#       "Rebuild", "add", etc.
1076#
1077itcl::body Rappture::FlowvisViewer::ReceiveLegend { tag vmin vmax size } {
1078    if { ![isconnected] } {
1079        return
1080    }
1081    #puts stderr "receive legend $tag $vmin $vmax $size"
1082    set bytes [ReceiveBytes $size]
1083    $_image(legend) configure -data $bytes
1084    ReceiveEcho <<line "<read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
1085
1086    set c $itk_component(legend)
1087    set w [winfo width $c]
1088    set h [winfo height $c]
1089    set lx 10
1090    set ly [expr {$h - 1}]
1091    if {"" == [$c find withtag transfunc]} {
1092        $c create image 10 10 -anchor nw \
1093            -image $_image(legend) -tags transfunc
1094        $c create text $lx $ly -anchor sw \
1095            -fill $itk_option(-plotforeground) -tags "limits vmin"
1096        $c create text [expr {$w-$lx}] $ly -anchor se \
1097            -fill $itk_option(-plotforeground) -tags "limits vmax"
1098        $c lower transfunc
1099        $c bind transfunc <ButtonRelease-1> \
1100            [itcl::code $this AddIsoMarker %x %y]
1101    }
1102    # Display the markers used by the active transfer function.
1103    set tf $_obj2style($tag)
1104    array set limits [limits $tf]
1105    $c itemconfigure vmin -text [format %.2g $limits(vmin)]
1106    $c coords vmin $lx $ly
1107
1108    $c itemconfigure vmax -text [format %.2g $limits(vmax)]
1109    $c coords vmax [expr {$w-$lx}] $ly
1110
1111    if { [info exists _isomarkers($tf)] } {
1112        foreach m $_isomarkers($tf) {
1113            $m visible yes
1114        }
1115    }
1116}
1117
1118#
1119# ReceiveData --
1120#
1121#       The procedure is the response from the render server to each "data
1122#       follows" command.  The server sends back a "data" command invoked our
1123#       the slave interpreter.  The purpose is to collect the min/max of the
1124#       volume sent to the render server.  Since the client (flowvisviewer)
1125#       doesn't parse 3D data formats, we rely on the server (flowvis) to
1126#       tell us what the limits are.  Once we've received the limits to all
1127#       the data we've sent (tracked by _recvObjs) we can then determine
1128#       what the transfer functions are for these # volumes.
1129#
1130#       Note: There is a considerable tradeoff in having the server report
1131#             back what the data limits are.  It means that much of the code
1132#             having to do with transfer-functions has to wait for the data
1133#             to come back, since the isomarkers are calculated based upon
1134#             the data limits.  The client code is much messier because of
1135#             this.  The alternative is to parse any of the 3D formats on the
1136#             client side.
1137#
1138itcl::body Rappture::FlowvisViewer::ReceiveData { args } {
1139    if { ![isconnected] } {
1140        return
1141    }
1142    # Arguments from server are name value pairs. Stuff them in an array.
1143    array set values $args
1144    set tag $values(tag)
1145    set parts [split $tag -]
1146    set dataobj [lindex $parts 0]
1147    set _serverObjs($tag) 0
1148    set _limits($tag-min)  $values(min);  # Minimum value of the volume.
1149    set _limits($tag-max)  $values(max);  # Maximum value of the volume.
1150    unset _recvObjs($tag)
1151    if { [array size _recvObjs] == 0 } {
1152        updatetransferfuncs
1153    }
1154}
1155
1156#
1157# Rebuild --
1158#
1159# Called automatically whenever something changes that affects the data
1160# in the widget.  Clears any existing data and rebuilds the widget to
1161# display new data. 
1162#
1163itcl::body Rappture::FlowvisViewer::Rebuild {} {
1164
1165    # Hide all the isomarkers. Can't remove them. Have to remember the
1166    # settings since the user may have created/deleted/moved markers.
1167
1168    foreach tf [array names _isomarkers] {
1169        foreach m $_isomarkers($tf) {
1170            $m visible no
1171        }
1172    }
1173
1174    set _first ""
1175    # Turn on buffering of commands to the server.  We don't want to
1176    # be preempted by a server disconnect/reconnect (which automatically
1177    # generates a new call to Rebuild).   
1178    set _buffering 1
1179
1180    set w [winfo width $itk_component(3dview)]
1181    set h [winfo height $itk_component(3dview)]
1182    EventuallyResize $w $h
1183
1184    foreach dataobj [get] {
1185        foreach comp [$dataobj components] {
1186            # Send the data as one huge base64-encoded mess -- yuck!
1187            set data [$dataobj blob $comp]
1188            set nbytes [string length $data]
1189            set extents [$dataobj extents $comp]
1190            # I have a field. Is a vector field or a volume field?
1191            if { $extents == 1 } {
1192                set cmd "volume data follows $nbytes $dataobj-$comp\n"
1193            } else {
1194                set cmd [FlowCmd $dataobj $comp $nbytes $extents]
1195                if { $cmd == "" } {
1196                    puts stderr "no command"
1197                    continue
1198                }
1199            }
1200            append _outbuf $cmd
1201            append _outbuf $data
1202            NameTransferFunc $dataobj $comp
1203            set _recvObjs($dataobj-$comp) 1
1204        }
1205    }
1206
1207    set _first [lindex [get] 0]
1208
1209    # Reset the camera and other view parameters
1210    FixSettings isosurface
1211    FixSettings grid
1212    FixSettings axes
1213    FixSettings volume
1214    FixSettings outline
1215    FixSettings light
1216    FixSettings transp
1217   
1218    # nothing to send -- activate the proper volume
1219    if {"" != $_first} {
1220        FixSettings light
1221        FixSettings transp
1222        set axis [$_first hints updir]
1223        if {"" != $axis} {
1224            SendCmd "up $axis"
1225        }
1226        set location [$_first hints camera]
1227        if { $location != "" } {
1228            array set _view $location
1229        }
1230    }
1231    set _settings($this-theta) $_view(theta)
1232    set _settings($this-phi)   $_view(phi)
1233    set _settings($this-psi)   $_view(psi)
1234    set _settings($this-pan-x) $_view(pan-x)
1235    set _settings($this-pan-y) $_view(pan-y)
1236    set _settings($this-zoom)  $_view(zoom)
1237
1238    set xyz [Euler2XYZ $_view(theta) $_view(phi) $_view(psi)]
1239    SendCmd "camera angle $xyz"
1240    PanCamera
1241    SendCmd "camera zoom $_view(zoom)"
1242
1243    foreach dataobj [get] {
1244        foreach comp [$dataobj components] {
1245            NameTransferFunc $dataobj $comp
1246        }
1247    }
1248
1249    # nothing to send -- activate the proper ivol
1250    set _first [lindex [get] 0]
1251    if {"" != $_first} {
1252        set axis [$_first hints updir]
1253        if {"" != $axis} {
1254            SendCmd "up $axis"
1255        }
1256        set location [$_first hints camera]
1257        if { $location != "" } {
1258            array set _view $location
1259        }
1260        set comp [lindex [$_first components] 0]
1261        set _activeTf [lindex $_obj2style($_first-$comp) 0]
1262    }
1263
1264
1265    # sync the state of slicers
1266    set vols [CurrentVolumeIds -cutplanes]
1267    foreach axis {x y z} {
1268        SendCmd "cutplane state $_settings($this-${axis}cutplane) $axis $vols"
1269        set pos [expr {0.01*$_settings($this-${axis}cutposition)}]
1270        SendCmd "cutplane position $pos $axis $vols"
1271    }
1272    SendCmd "volume data state $_settings($this-volume)"
1273    EventuallyResizeLegend
1274
1275    # Actually write the commands to the server socket.  If it fails, we don't
1276    # care.  We're finished here.
1277    blt::busy hold $itk_component(hull)
1278    SendBytes $_outbuf
1279    blt::busy release $itk_component(hull)
1280    set _buffering 0;                   # Turn off buffering.
1281    set _outbuf "";                     # Clear the buffer.             
1282}
1283
1284# ----------------------------------------------------------------------
1285# USAGE: CurrentVolumeIds ?-cutplanes?
1286#
1287# Returns a list of volume server IDs for the current volume being
1288# displayed.  This is normally a single ID, but it might be a list
1289# of IDs if the current data object has multiple components.
1290# ----------------------------------------------------------------------
1291itcl::body Rappture::FlowvisViewer::CurrentVolumeIds {{what -all}} {
1292    return ""
1293    if { $_first == "" } {
1294        return
1295    }
1296    foreach key [array names _serverObjs *-*] {
1297        if {[string match $_first-* $key]} {
1298            array set style {
1299                -cutplanes 1
1300            }
1301            foreach {dataobj comp} [split $key -] break
1302            array set style [lindex [$dataobj components -style $comp] 0]
1303            if {$what != "-cutplanes" || $style(-cutplanes)} {
1304                lappend rlist $_serverObjs($key)
1305            }
1306        }
1307    }
1308    return $rlist
1309}
1310
1311# ----------------------------------------------------------------------
1312# USAGE: Zoom in
1313# USAGE: Zoom out
1314# USAGE: Zoom reset
1315#
1316# Called automatically when the user clicks on one of the zoom
1317# controls for this widget.  Changes the zoom for the current view.
1318# ----------------------------------------------------------------------
1319itcl::body Rappture::FlowvisViewer::Zoom {option} {
1320    switch -- $option {
1321        "in" {
1322            set _view(zoom) [expr {$_view(zoom)*1.25}]
1323            set _settings($this-zoom) $_view(zoom)
1324        }
1325        "out" {
1326            set _view(zoom) [expr {$_view(zoom)*0.8}]
1327            set _settings($this-zoom) $_view(zoom)
1328        }
1329        "reset" {
1330            array set _view {
1331                theta   45
1332                phi     45
1333                psi     0
1334                zoom    1.0
1335                pan-x   0
1336                pan-y   0
1337            }
1338            if { $_first != "" } {
1339                set location [$_first hints camera]
1340                if { $location != "" } {
1341                    array set _view $location
1342                }
1343            }
1344            set xyz [Euler2XYZ $_view(theta) $_view(phi) $_view(psi)]
1345            SendCmd "camera angle $xyz"
1346            PanCamera
1347            set _settings($this-theta) $_view(theta)
1348            set _settings($this-phi)   $_view(phi)
1349            set _settings($this-psi)   $_view(psi)
1350            set _settings($this-pan-x) $_view(pan-x)
1351            set _settings($this-pan-y) $_view(pan-y)
1352            set _settings($this-zoom)  $_view(zoom)
1353        }
1354    }
1355    SendCmd "camera zoom $_view(zoom)"
1356}
1357
1358itcl::body Rappture::FlowvisViewer::PanCamera {} {
1359    #set x [expr ($_view(pan-x)) / $_limits(xrange)]
1360    #set y [expr ($_view(pan-y)) / $_limits(yrange)]
1361    set x $_view(pan-x)
1362    set y $_view(pan-y)
1363    SendCmd "camera pan $x $y"
1364}
1365
1366# ----------------------------------------------------------------------
1367# USAGE: Rotate click <x> <y>
1368# USAGE: Rotate drag <x> <y>
1369# USAGE: Rotate release <x> <y>
1370#
1371# Called automatically when the user clicks/drags/releases in the
1372# plot area.  Moves the plot according to the user's actions.
1373# ----------------------------------------------------------------------
1374itcl::body Rappture::FlowvisViewer::Rotate {option x y} {
1375    switch -- $option {
1376        click {
1377            $itk_component(3dview) configure -cursor fleur
1378            set _click(x) $x
1379            set _click(y) $y
1380            set _click(theta) $_view(theta)
1381            set _click(phi) $_view(phi)
1382        }
1383        drag {
1384            if {[array size _click] == 0} {
1385                Rotate click $x $y
1386            } else {
1387                set w [winfo width $itk_component(3dview)]
1388                set h [winfo height $itk_component(3dview)]
1389                if {$w <= 0 || $h <= 0} {
1390                    return
1391                }
1392
1393                if {[catch {
1394                    # this fails sometimes for no apparent reason
1395                    set dx [expr {double($x-$_click(x))/$w}]
1396                    set dy [expr {double($y-$_click(y))/$h}]
1397                }]} {
1398                    return
1399                }
1400
1401                #
1402                # Rotate the camera in 3D
1403                #
1404                if {$_view(psi) > 90 || $_view(psi) < -90} {
1405                    # when psi is flipped around, theta moves backwards
1406                    set dy [expr {-$dy}]
1407                }
1408                set theta [expr {$_view(theta) - $dy*180}]
1409                while {$theta < 0} { set theta [expr {$theta+180}] }
1410                while {$theta > 180} { set theta [expr {$theta-180}] }
1411
1412                if {abs($theta) >= 30 && abs($theta) <= 160} {
1413                    set phi [expr {$_view(phi) - $dx*360}]
1414                    while {$phi < 0} { set phi [expr {$phi+360}] }
1415                    while {$phi > 360} { set phi [expr {$phi-360}] }
1416                    set psi $_view(psi)
1417                } else {
1418                    set phi $_view(phi)
1419                    set psi [expr {$_view(psi) - $dx*360}]
1420                    while {$psi < -180} { set psi [expr {$psi+360}] }
1421                    while {$psi > 180} { set psi [expr {$psi-360}] }
1422                }
1423
1424                set _view(theta)        $theta
1425                set _view(phi)          $phi
1426                set _view(psi)          $psi
1427                set xyz [Euler2XYZ $theta $phi $psi]
1428                set _settings($this-theta) $_view(theta)
1429                set _settings($this-phi)   $_view(phi)
1430                set _settings($this-psi)   $_view(psi)
1431                SendCmd "camera angle $xyz"
1432                set _click(x) $x
1433                set _click(y) $y
1434            }
1435        }
1436        release {
1437            Rotate drag $x $y
1438            $itk_component(3dview) configure -cursor ""
1439            catch {unset _click}
1440        }
1441        default {
1442            error "bad option \"$option\": should be click, drag, release"
1443        }
1444    }
1445}
1446
1447# ----------------------------------------------------------------------
1448# USAGE: $this Pan click x y
1449#        $this Pan drag x y
1450#        $this Pan release x y
1451#
1452# Called automatically when the user clicks on one of the zoom
1453# controls for this widget.  Changes the zoom for the current view.
1454# ----------------------------------------------------------------------
1455itcl::body Rappture::FlowvisViewer::Pan {option x y} {
1456    # Experimental stuff
1457    set w [winfo width $itk_component(3dview)]
1458    set h [winfo height $itk_component(3dview)]
1459    if { $option == "set" } {
1460        set x [expr $x / double($w)]
1461        set y [expr $y / double($h)]
1462        set _view(pan-x) [expr $_view(pan-x) + $x]
1463        set _view(pan-y) [expr $_view(pan-y) + $y]
1464        PanCamera
1465        set _settings($this-pan-x) $_view(pan-x)
1466        set _settings($this-pan-y) $_view(pan-y)
1467        return
1468    }
1469    if { $option == "click" } {
1470        set _click(x) $x
1471        set _click(y) $y
1472        $itk_component(3dview) configure -cursor hand1
1473    }
1474    if { $option == "drag" || $option == "release" } {
1475        set dx [expr ($_click(x) - $x)/double($w)]
1476        set dy [expr ($_click(y) - $y)/double($h)]
1477        set _click(x) $x
1478        set _click(y) $y
1479        set _view(pan-x) [expr $_view(pan-x) - $dx]
1480        set _view(pan-y) [expr $_view(pan-y) - $dy]
1481        PanCamera
1482        set _settings($this-pan-x) $_view(pan-x)
1483        set _settings($this-pan-y) $_view(pan-y)
1484    }
1485    if { $option == "release" } {
1486        $itk_component(3dview) configure -cursor ""
1487    }
1488}
1489
1490
1491# ----------------------------------------------------------------------
1492# USAGE: Flow movie record|stop|play ?on|off|toggle?
1493#
1494# Called when the user clicks on the record, stop or play buttons
1495# for flow visualization.
1496# ----------------------------------------------------------------------
1497itcl::body Rappture::FlowvisViewer::Flow {option args} {
1498    switch -- $option {
1499        movie {
1500            if {[llength $args] < 1 || [llength $args] > 2} {
1501                error "wrong # args: should be \"Flow movie record|stop|play ?on|off|toggle?\""
1502            }
1503            set action [lindex $args 0]
1504            set op [lindex $args 1]
1505            if {$op == ""} { set op "on" }
1506
1507            set current [State $action]
1508            if {$op == "toggle"} {
1509                if {$current == "on"} {
1510                    set op "off"
1511                } else {
1512                    set op "on"
1513                }
1514            }
1515            set cmds ""
1516            switch -- $action {
1517                record {
1518                    if { [$itk_component(rewind) cget -relief] != "sunken" } {
1519                        $itk_component(rewind) configure -relief sunken
1520                        $itk_component(stop) configure -relief raised
1521                        $itk_component(play) configure -relief raised
1522                        set inner $itk_component(settingsFrame)
1523                        set frames [$inner.framecnt value]
1524                        set _settings(nsteps) $frames
1525                        set cmds "flow capture $frames"
1526                        SendCmd $cmds
1527                    }
1528                }
1529                stop {
1530                    if { [$itk_component(stop) cget -relief] != "sunken" } {
1531                        $itk_component(rewind) configure -relief raised
1532                        $itk_component(stop) configure -relief sunken
1533                        $itk_component(play) configure -relief raised
1534                        _pause
1535                        set cmds "flow reset"
1536                        SendCmd $cmds
1537                    }
1538                }
1539                play {
1540                    if { [$itk_component(play) cget -relief] != "sunken" } {
1541                        $itk_component(rewind) configure -relief raised
1542                        $itk_component(stop) configure -relief raised
1543                        $itk_component(play) configure \
1544                            -image [Rappture::icon flow-pause] \
1545                            -relief sunken
1546                        bind $itk_component(play) <ButtonPress> \
1547                            [itcl::code $this _pause]
1548                        flow next
1549                    }
1550                }
1551                default {
1552                    error "bad option \"$option\": should be one of record|stop|play"
1553                }
1554
1555            }
1556        }
1557        default {
1558            error "bad option \"$option\": should be movie"
1559        }
1560    }
1561}
1562
1563# ----------------------------------------------------------------------
1564# USAGE: Play
1565#
1566# ----------------------------------------------------------------------
1567itcl::body Rappture::FlowvisViewer::Play {} {
1568    SendCmd "flow next"
1569    set delay [expr {int(ceil(pow($_settings(speed)/10.0+2,2.0)*15))}]
1570    $_dispatcher event -after $delay !play
1571}
1572
1573# ----------------------------------------------------------------------
1574# USAGE: Pause
1575#
1576# Invoked when the user hits the "pause" button to stop playing the
1577# current sequence of frames as a movie.
1578# ----------------------------------------------------------------------
1579itcl::body Rappture::FlowvisViewer::Pause {} {
1580    $_dispatcher cancel !play
1581
1582    # Toggle the button to "play" mode
1583    $itk_component(play) configure \
1584        -image [Rappture::icon flow-start] \
1585        -relief raised
1586    bind $itk_component(play) <ButtonPress> \
1587        [itcl::code $this Flow movie play toggle]
1588}
1589
1590# ----------------------------------------------------------------------
1591# USAGE: FixSettings <what> ?<value>?
1592#
1593# Used internally to update rendering settings whenever parameters
1594# change in the popup settings panel.  Sends the new settings off
1595# to the back end.
1596# ----------------------------------------------------------------------
1597itcl::body Rappture::FlowvisViewer::FixSettings {what {value ""}} {
1598    switch -- $what {
1599        light {
1600            if { $_first != "" } {
1601                set comp [lindex [$_first components] 0]
1602                set tag $_first-$comp
1603                set diffuse [expr {0.1*$_settings($this-light)}]
1604                set specular [expr {sqrt($_settings($this-light)+1.0)}]
1605                SendCmd "$tag configure -diffuse $diffuse -specular $specular"
1606            }
1607        }
1608        transp {
1609            if { $_first != "" } {
1610                set comp [lindex [$_first components] 0]
1611                set tag $_first-$comp
1612                set opacity [expr {0.2*$_settings($this-transp)+1}]
1613                SendCmd "$tag configure -opacity $opacity"
1614            }
1615        }
1616        opacity {
1617            if { $_first != "" && $_activeTf != "" } {
1618                set opacity [expr { 0.01 * double($_settings($this-opacity)) }]
1619                set tf $_activeTf
1620                set _settings($this-$tf-opacity) $opacity
1621                updatetransferfuncs
1622            }
1623        }
1624
1625        thickness {
1626            if { $_first != "" && $_activeTf != "" } {
1627                set val $_settings($this-thickness)
1628                # Scale values between 0.00001 and 0.01000
1629                set sval [expr {0.0001*double($val)}]
1630                set tf $_activeTf
1631                set _settings($this-$tf-thickness) $sval
1632                updatetransferfuncs
1633            }
1634        }
1635        "outline" {
1636            if { $_first != "" } {
1637                set comp [lindex [$_first components] 0]
1638                set tag $_first-$comp
1639                SendCmd "$tag configure -outline $_settings($this-outline)"
1640            }
1641        }
1642        "isosurface" {
1643            if { [isconnected] } {
1644                SendCmd "volume shading isosurface $_settings($this-isosurface)"
1645            }
1646        }
1647        "grid" {
1648            if { [isconnected] } {
1649                SendCmd "grid visible $_settings($this-grid)"
1650            }
1651        }
1652        "axes" {
1653            if { [isconnected] } {
1654                SendCmd "axis visible $_settings($this-axes)"
1655            }
1656        }
1657        "legend" {
1658            if { $_settings($this-legend) } {
1659                blt::table $itk_component(plotarea) \
1660                    0,0 $itk_component(3dview) -fill both \
1661                    1,0 $itk_component(legend) -fill x
1662                blt::table configure $itk_component(plotarea) r1 -resize none
1663            } else {
1664                blt::table forget $itk_component(legend)
1665            }
1666        }
1667        "volume" {
1668            if { $_first != "" } {
1669                set comp [lindex [$_first components] 0]
1670                set tag $_first-$comp
1671                SendCmd "$tag configure -volume $_settings($this-volume)"
1672            }
1673        }
1674        "xcutplane" - "ycutplane" - "zcutplane" {
1675            set axis [string range $what 0 0]
1676            set bool $_settings($this-$what)
1677            if { [isconnected] } {
1678                set vols [CurrentVolumeIds -cutplanes]
1679                SendCmd "cutplane state $bool $axis $vols"
1680            }
1681            if { $bool } {
1682                $itk_component(${axis}CutScale) configure -state normal \
1683                    -troughcolor white
1684            } else {
1685                $itk_component(${axis}CutScale) configure -state disabled \
1686                    -troughcolor grey82
1687            }
1688        }
1689        default {
1690            error "don't know how to fix $what"
1691        }
1692    }
1693}
1694
1695# ----------------------------------------------------------------------
1696# USAGE: ResizeLegend
1697#
1698# Used internally to update the legend area whenever it changes size
1699# or when the field changes.  Asks the server to send a new legend
1700# for the current field.
1701# ----------------------------------------------------------------------
1702itcl::body Rappture::FlowvisViewer::ResizeLegend {} {
1703    set _resizeLegendPending 0
1704    set lineht [font metrics $itk_option(-font) -linespace]
1705    set w [expr {$_width-20}]
1706    set h [expr {[winfo height $itk_component(legend)]-20-$lineht}]
1707
1708    if { $_first == "" } {
1709        return
1710    }
1711    set comp [lindex [$_first components] 0]
1712    set tag $_first-$comp
1713    #set _activeTf [lindex $_obj2style($tag) 0]
1714    if {$w > 0 && $h > 0 && "" != $_activeTf} {
1715        #SendCmd "legend $_activeTf $w $h"
1716        SendCmd "$tag legend $w $h"
1717    } else {
1718    # Can't do this as this will remove the items associated with the
1719    # isomarkers.
1720
1721    #$itk_component(legend) delete all
1722    }
1723}
1724
1725#
1726# NameTransferFunc --
1727#
1728#       Creates a transfer function name based on the <style> settings in the
1729#       library run.xml file. This placeholder will be used later to create
1730#       and send the actual transfer function once the data info has been sent
1731#       to us by the render server. [We won't know the volume limits until the
1732#       server parses the 3D data and sends back the limits via ReceiveData.]
1733#
1734#       FIXME: The current way we generate transfer-function names completely
1735#              ignores the -markers option.  The problem is that we are forced
1736#              to compute the name from an increasing complex set of values:
1737#              color, levels, marker, opacity.  I think we're stuck doing it
1738#              now.
1739#
1740itcl::body Rappture::FlowvisViewer::NameTransferFunc { dataobj comp } {
1741    array set style {
1742        -color rainbow
1743        -levels 6
1744        -opacity 1.0
1745        -light 40
1746        -transp 50
1747    }
1748    array set style [lindex [$dataobj components -style $comp] 0]
1749    set _settings($this-light) $style(-light)
1750    set _settings($this-transp) $style(-transp)
1751    set _settings($this-opacity) [expr $style(-opacity) * 100]
1752    set tf "$style(-color):$style(-levels):$style(-opacity)"
1753    set _obj2style($dataobj-$comp) $tf
1754    lappend _style2objs($tf) $dataobj $comp
1755    return $tf
1756}
1757
1758#
1759# ComputeTransferFunc --
1760#
1761#   Computes and sends the transfer function to the render server.  It's
1762#   assumed that the volume data limits are known and that the global
1763#   transfer-functions slider values have be setup.  Both parts are
1764#   needed to compute the relative value (location) of the marker, and
1765#   the alpha map of the transfer function.
1766#
1767itcl::body Rappture::FlowvisViewer::ComputeTransferFunc { tf } {
1768    array set style {
1769        -color rainbow
1770        -levels 6
1771        -opacity 1.0
1772        -light 40
1773        -transp 50
1774    }
1775    set dataobj ""; set comp ""
1776    foreach {dataobj comp} $_style2objs($tf) break
1777    if { $dataobj == "" } {
1778        return 0
1779    }
1780    array set style [lindex [$dataobj components -style $comp] 0]
1781
1782
1783    # We have to parse the style attributes for a volume using this
1784    # transfer-function *once*.  This sets up the initial isomarkers for the
1785    # transfer function.  The user may add/delete markers, so we have to
1786    # maintain a list of markers for each transfer-function.  We use the one
1787    # of the volumes (the first in the list) using the transfer-function as a
1788    # reference.
1789    #
1790    # FIXME: The current way we generate transfer-function names completely
1791    #        ignores the -markers option.  The problem is that we are forced
1792    #        to compute the name from an increasing complex set of values:
1793    #        color, levels, marker, opacity.  I think the cow's out of the
1794    #        barn on this one.
1795
1796    if { ![info exists _isomarkers($tf)] } {
1797        # Have to defer creation of isomarkers until we have data limits
1798        if { [info exists style(-markers)] } {
1799            ParseMarkersOption $tf $style(-markers)
1800        } else {
1801            ParseLevelsOption $tf $style(-levels)
1802        }
1803    }
1804    if {$style(-color) == "rainbow"} {
1805        set style(-color) "white:yellow:green:cyan:blue:magenta"
1806    }
1807    if { [info exists style(-nonuniformcolors)] } {
1808        foreach { value color } $style(-nonuniformcolors) {
1809            append cmap "$value [Color2RGB $color] "
1810        }
1811    } else {
1812        set clist [split $style(-color) :]
1813        set cmap "0.0 [Color2RGB white] "
1814        for {set i 0} {$i < [llength $clist]} {incr i} {
1815            set x [expr {double($i+1)/([llength $clist]+1)}]
1816            set color [lindex $clist $i]
1817            append cmap "$x [Color2RGB $color] "
1818        }
1819        append cmap "1.0 [Color2RGB $color]"
1820    }
1821    set tag $this-$tf
1822    if { ![info exists _settings($tag-opacity)] } {
1823        set _settings($tag-opacity) $style(-opacity)
1824    }
1825    set max $_settings($tag-opacity)
1826   
1827    set isovalues {}
1828    foreach m $_isomarkers($tf) {
1829        lappend isovalues [$m relval]
1830    }
1831    # Sort the isovalues
1832    set isovalues [lsort -real $isovalues]
1833
1834    if { ![info exists _settings($tag-thickness)]} {
1835        set _settings($tag-thickness) 0.05
1836    }
1837    set delta $_settings($tag-thickness)
1838
1839    set first [lindex $isovalues 0]
1840    set last [lindex $isovalues end]
1841    set wmap ""
1842    if { $first == "" || $first != 0.0 } {
1843        lappend wmap 0.0 0.0
1844    }
1845    foreach x $isovalues {
1846        set x1 [expr {$x-$delta-0.00001}]
1847        set x2 [expr {$x-$delta}]
1848        set x3 [expr {$x+$delta}]
1849        set x4 [expr {$x+$delta+0.00001}]
1850        if { $x1 < 0.0 } {
1851            set x1 0.0
1852        } elseif { $x1 > 1.0 } {
1853            set x1 1.0
1854        }
1855        if { $x2 < 0.0 } {
1856            set x2 0.0
1857        } elseif { $x2 > 1.0 } {
1858            set x2 1.0
1859        }
1860        if { $x3 < 0.0 } {
1861            set x3 0.0
1862        } elseif { $x3 > 1.0 } {
1863            set x3 1.0
1864        }
1865        if { $x4 < 0.0 } {
1866            set x4 0.0
1867        } elseif { $x4 > 1.0 } {
1868            set x4 1.0
1869        }
1870        # add spikes in the middle
1871        lappend wmap $x1 0.0
1872        lappend wmap $x2 $max
1873        lappend wmap $x3 $max
1874        lappend wmap $x4 0.0
1875    }
1876    if { $last == "" || $last != 1.0 } {
1877        lappend wmap 1.0 0.0
1878    }
1879    SendCmd "transfunc define $tf { $cmap } { $wmap }\n"
1880    return [SendCmd "$dataobj-$comp configure -transferfunction $tf\n"]
1881}
1882
1883# ----------------------------------------------------------------------
1884# CONFIGURATION OPTION: -plotbackground
1885# ----------------------------------------------------------------------
1886itcl::configbody Rappture::FlowvisViewer::plotbackground {
1887    if { [isconnected] } {
1888        foreach {r g b} [Color2RGB $itk_option(-plotbackground)] break
1889        #fix this!
1890        #SendCmd "color background $r $g $b"
1891    }
1892}
1893
1894# ----------------------------------------------------------------------
1895# CONFIGURATION OPTION: -plotforeground
1896# ----------------------------------------------------------------------
1897itcl::configbody Rappture::FlowvisViewer::plotforeground {
1898    if { [isconnected] } {
1899        foreach {r g b} [Color2RGB $itk_option(-plotforeground)] break
1900        #fix this!
1901        #SendCmd "color background $r $g $b"
1902    }
1903}
1904
1905# ----------------------------------------------------------------------
1906# CONFIGURATION OPTION: -plotoutline
1907# ----------------------------------------------------------------------
1908itcl::configbody Rappture::FlowvisViewer::plotoutline {
1909    # Must check if we are connected because this routine is called from the
1910    # class body when the -plotoutline itk_option is defined.  At that point
1911    # the FlowvisViewer class constructor hasn't been called, so we can't
1912    # start sending commands to visualization server.
1913    if { [isconnected] } {
1914        if {"" == $itk_option(-plotoutline)} {
1915            SendCmd "volume outline state off"
1916        } else {
1917            SendCmd "volume outline state on"
1918            SendCmd "volume outline color [Color2RGB $itk_option(-plotoutline)]"
1919        }
1920    }
1921}
1922
1923#
1924# The -levels option takes a single value that represents the number
1925# of evenly distributed markers based on the current data range. Each
1926# marker is a relative value from 0.0 to 1.0.
1927#
1928itcl::body Rappture::FlowvisViewer::ParseLevelsOption { tf levels } {
1929    set c $itk_component(legend)
1930    regsub -all "," $levels " " levels
1931    if {[string is int $levels]} {
1932        for {set i 1} { $i <= $levels } {incr i} {
1933            set x [expr {double($i)/($levels+1)}]
1934            set m [Rappture::IsoMarker \#auto $c $this $tf]
1935            $m relval $x
1936            lappend _isomarkers($tf) $m
1937        }
1938    } else {
1939        foreach x $levels {
1940            set m [Rappture::IsoMarker \#auto $c $this $tf]
1941            $m relval $x
1942            lappend _isomarkers($tf) $m
1943        }
1944    }
1945}
1946
1947#
1948# The -markers option takes a list of zero or more values (the values
1949# may be separated either by spaces or commas) that have the following
1950# format:
1951#
1952#   N%  Percent of current total data range.  Converted to
1953#       to a relative value between 0.0 and 1.0.
1954#   N   Absolute value of marker.  If the marker is outside of
1955#       the current range, it will be displayed on the outer
1956#       edge of the legends, but it range it represents will
1957#       not be seen.
1958#
1959itcl::body Rappture::FlowvisViewer::ParseMarkersOption { tf markers } {
1960    set c $itk_component(legend)
1961    regsub -all "," $markers " " markers
1962    foreach marker $markers {
1963        set n [scan $marker "%g%s" value suffix]
1964        if { $n == 2 && $suffix == "%" } {
1965            # ${n}% : Set relative value.
1966            set value [expr {$value * 0.01}]
1967            set m [Rappture::IsoMarker \#auto $c $this $tf]
1968            $m relval $value
1969            lappend _isomarkers($tf) $m
1970        } else {
1971            # ${n} : Set absolute value.
1972            set m [Rappture::IsoMarker \#auto $c $this $tf]
1973            $m absval $value
1974            lappend _isomarkers($tf) $m
1975        }
1976    }
1977}
1978
1979# ----------------------------------------------------------------------
1980# USAGE: UndateTransferFuncs
1981# ----------------------------------------------------------------------
1982itcl::body Rappture::FlowvisViewer::updatetransferfuncs {} {
1983    $_dispatcher event -after 100 !send_transfunc
1984}
1985
1986itcl::body Rappture::FlowvisViewer::AddIsoMarker { x y } {
1987    if { $_activeTf == "" } {
1988        error "active transfer function isn't set"
1989    }
1990    set tf $_activeTf
1991    set c $itk_component(legend)
1992    set m [Rappture::IsoMarker \#auto $c $this $tf]
1993    set w [winfo width $c]
1994    $m relval [expr {double($x-10)/($w-20)}]
1995    lappend _isomarkers($tf) $m
1996    updatetransferfuncs
1997    return 1
1998}
1999
2000itcl::body Rappture::FlowvisViewer::rmdupmarker { marker x } {
2001    set tf [$marker transferfunc]
2002    set bool 0
2003    if { [info exists _isomarkers($tf)] } {
2004        set list {}
2005        set marker [namespace tail $marker]
2006        foreach m $_isomarkers($tf) {
2007            set sx [$m screenpos]
2008            if { $m != $marker } {
2009                if { $x >= ($sx-3) && $x <= ($sx+3) } {
2010                    $marker relval [$m relval]
2011                    itcl::delete object $m
2012                    bell
2013                    set bool 1
2014                    continue
2015                }
2016            }
2017            lappend list $m
2018        }
2019        set _isomarkers($tf) $list
2020        updatetransferfuncs
2021    }
2022    return $bool
2023}
2024
2025itcl::body Rappture::FlowvisViewer::overmarker { marker x } {
2026    set tf [$marker transferfunc]
2027    if { [info exists _isomarkers($tf)] } {
2028        set marker [namespace tail $marker]
2029        foreach m $_isomarkers($tf) {
2030            set sx [$m screenpos]
2031            if { $m != $marker } {
2032                set bool [expr { $x >= ($sx-3) && $x <= ($sx+3) }]
2033                $m activate $bool
2034            }
2035        }
2036    }
2037    return ""
2038}
2039
2040itcl::body Rappture::FlowvisViewer::limits { tf } {
2041    set _limits(vmin) 0.0
2042    set _limits(vmax) 1.0
2043    if { ![info exists _style2objs($tf)] } {
2044        puts stderr "no style2objs for $tf tf=($tf)"
2045        return [array get _limits]
2046    }
2047    set min ""; set max ""
2048    foreach {dataobj comp} $_style2objs($tf) {
2049        set tag $dataobj-$comp
2050        if { ![info exists _serverObjs($tag)] } {
2051            puts stderr "$tag not in serverObjs?"
2052            continue
2053        }
2054        if { ![info exists _limits($tag-min)] } {
2055            puts stderr "$tag no min?"
2056            continue
2057        }
2058        if { $min == "" || $min > $_limits($tag-min) } {
2059            set min $_limits($tag-min)
2060        }
2061        if { $max == "" || $max < $_limits($tag-max) } {
2062            set max $_limits($tag-max)
2063        }
2064    }
2065    if { $min != "" } {
2066        set _limits(vmin) $min
2067    }
2068    if { $max != "" } {
2069        set _limits(vmax) $max
2070    }
2071    return [array get _limits]
2072}
2073
2074
2075
2076itcl::body Rappture::FlowvisViewer::BuildViewTab {} {
2077    foreach { key value } {
2078        grid            0
2079        axes            0
2080        outline         1
2081        volume          1
2082        legend          1
2083        particles       1
2084        lic             1
2085    } {
2086        set _settings($this-$key) $value
2087    }
2088
2089    set fg [option get $itk_component(hull) font Font]
2090    #set bfg [option get $itk_component(hull) boldFont Font]
2091
2092    set inner [$itk_component(main) insert end \
2093        -title "View Settings" \
2094        -icon [Rappture::icon wrench]]
2095    $inner configure -borderwidth 4
2096
2097    set ::Rappture::FlowvisViewer::_settings($this-isosurface) 0
2098    checkbutton $inner.isosurface \
2099        -text "Isosurface shading" \
2100        -variable [itcl::scope _settings($this-isosurface)] \
2101        -command [itcl::code $this FixSettings isosurface] \
2102        -font "Arial 9"
2103
2104    checkbutton $inner.axes \
2105        -text "Axes" \
2106        -variable [itcl::scope _settings($this-axes)] \
2107        -command [itcl::code $this FixSettings axes] \
2108        -font "Arial 9"
2109
2110    checkbutton $inner.grid \
2111        -text "Grid" \
2112        -variable [itcl::scope _settings($this-grid)] \
2113        -command [itcl::code $this FixSettings grid] \
2114        -font "Arial 9"
2115
2116    checkbutton $inner.outline \
2117        -text "Outline" \
2118        -variable [itcl::scope _settings($this-outline)] \
2119        -command [itcl::code $this FixSettings outline] \
2120        -font "Arial 9"
2121
2122    checkbutton $inner.legend \
2123        -text "Legend" \
2124        -variable [itcl::scope _settings($this-legend)] \
2125        -command [itcl::code $this FixSettings legend] \
2126        -font "Arial 9"
2127
2128    checkbutton $inner.volume \
2129        -text "Volume" \
2130        -variable [itcl::scope _settings($this-volume)] \
2131        -command [itcl::code $this FixSettings volume] \
2132        -font "Arial 9"
2133
2134    checkbutton $inner.particles \
2135        -text "Particles" \
2136        -variable [itcl::scope _settings($this-particles)] \
2137        -command [itcl::code $this FixSettings particles] \
2138        -font "Arial 9"
2139
2140    checkbutton $inner.lic \
2141        -text "Lic" \
2142        -variable [itcl::scope _settings($this-lic)] \
2143        -command [itcl::code $this FixSettings lic] \
2144        -font "Arial 9"
2145
2146    frame $inner.frame
2147
2148    blt::table $inner \
2149        0,0 $inner.axes  -columnspan 2 -anchor w \
2150        1,0 $inner.grid  -columnspan 2 -anchor w \
2151        2,0 $inner.outline  -columnspan 2 -anchor w \
2152        3,0 $inner.volume  -columnspan 2 -anchor w \
2153        4,0 $inner.legend  -columnspan 2 -anchor w
2154
2155    bind $inner <Map> [itcl::code $this GetFlowInfo $inner]
2156
2157    blt::table configure $inner r* -resize none
2158    blt::table configure $inner r5 -resize expand
2159}
2160
2161itcl::body Rappture::FlowvisViewer::BuildVolumeTab {} {
2162    foreach { key value } {
2163        light           40
2164        transp          50
2165        opacity         100
2166        thickness       350
2167    } {
2168        set _settings($this-$key) $value
2169    }
2170
2171    set inner [$itk_component(main) insert end \
2172        -title "Volume Settings" \
2173        -icon [Rappture::icon volume-on]]
2174    $inner configure -borderwidth 4
2175
2176    set fg [option get $itk_component(hull) font Font]
2177    #set bfg [option get $itk_component(hull) boldFont Font]
2178
2179    checkbutton $inner.vol -text "Show volume" -font $fg \
2180        -text "Volume" \
2181        -variable [itcl::scope _settings($this-volume)] \
2182        -command [itcl::code $this FixSettings volume] \
2183        -font "Arial 9"
2184
2185    label $inner.shading -text "Shading:" -font $fg
2186
2187    label $inner.dim -text "Dim" -font $fg
2188    ::scale $inner.light -from 0 -to 100 -orient horizontal \
2189        -variable [itcl::scope _settings($this-light)] \
2190        -width 10 \
2191        -showvalue off -command [itcl::code $this FixSettings light]
2192    label $inner.bright -text "Bright" -font $fg
2193
2194    label $inner.fog -text "Fog" -font $fg
2195    ::scale $inner.transp -from 0 -to 100 -orient horizontal \
2196        -variable [itcl::scope _settings($this-transp)] \
2197        -width 10 \
2198        -showvalue off -command [itcl::code $this FixSettings transp]
2199    label $inner.plastic -text "Plastic" -font $fg
2200
2201    label $inner.clear -text "Clear" -font $fg
2202    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
2203        -variable [itcl::scope _settings($this-opacity)] \
2204        -width 10 \
2205        -showvalue off -command [itcl::code $this FixSettings opacity]
2206    label $inner.opaque -text "Opaque" -font $fg
2207
2208    label $inner.thin -text "Thin" -font $fg
2209    ::scale $inner.thickness -from 0 -to 1000 -orient horizontal \
2210        -variable [itcl::scope _settings($this-thickness)] \
2211        -width 10 \
2212        -showvalue off -command [itcl::code $this FixSettings thickness]
2213    label $inner.thick -text "Thick" -font $fg
2214
2215    blt::table $inner \
2216        0,0 $inner.vol -columnspan 4 -anchor w -pady 2 \
2217        1,0 $inner.shading -columnspan 4 -anchor w -pady {10 2} \
2218        2,0 $inner.dim -anchor e -pady 2 \
2219        2,1 $inner.light -columnspan 2 -pady 2 -fill x \
2220        2,3 $inner.bright -anchor w -pady 2 \
2221        3,0 $inner.fog -anchor e -pady 2 \
2222        3,1 $inner.transp -columnspan 2 -pady 2 -fill x \
2223        3,3 $inner.plastic -anchor w -pady 2 \
2224        4,0 $inner.clear -anchor e -pady 2 \
2225        4,1 $inner.opacity -columnspan 2 -pady 2 -fill x\
2226        4,3 $inner.opaque -anchor w -pady 2 \
2227        5,0 $inner.thin -anchor e -pady 2 \
2228        5,1 $inner.thickness -columnspan 2 -pady 2 -fill x\
2229        5,3 $inner.thick -anchor w -pady 2
2230
2231    if 0 {
2232        0,0 $inner.dim  -anchor e -pady 2 \
2233        0,1 $inner.light -columnspan 2 -pady 2 \
2234        0,3 $inner.bright -anchor w -pady 2 \
2235        1,0 $inner.fog -anchor e -pady 2 \
2236        1,1 $inner.transp -columnspan 2 -pady 2 \
2237        1,3 $inner.plastic -anchor w -pady 2 \
2238        2,0 $inner.clear -anchor e -pady 2 \
2239        2,1 $inner.opacity -columnspan 2 -pady 2 \
2240        2,3 $inner.opaque -anchor w -pady 2 \
2241        3,0 $inner.thin -anchor e -pady 2 \
2242        3,1 $inner.thickness -columnspan 2 -pady 2 \
2243        3,3 $inner.thick -anchor w -pady 2
2244    }
2245    blt::table configure $inner c0 c1 c3 r* -resize none
2246    blt::table configure $inner r6 -resize expand
2247}
2248
2249itcl::body Rappture::FlowvisViewer::BuildCutplanesTab {} {
2250    set inner [$itk_component(main) insert end \
2251        -title "Cutplane Settings" \
2252        -icon [Rappture::icon cutbutton]]
2253    $inner configure -borderwidth 4
2254
2255    # X-value slicer...
2256    itk_component add xCutButton {
2257        Rappture::PushButton $inner.xbutton \
2258            -onimage [Rappture::icon x-cutplane] \
2259            -offimage [Rappture::icon x-cutplane] \
2260            -command [itcl::code $this FixSettings xcutplane] \
2261            -variable [itcl::scope _settings($this-xcutplane)]
2262    }
2263    Rappture::Tooltip::for $itk_component(xCutButton) \
2264        "Toggle the X cut plane on/off"
2265
2266    itk_component add xCutScale {
2267        ::scale $inner.xval -from 100 -to 0 \
2268            -width 10 -orient vertical -showvalue off \
2269            -borderwidth 1 -highlightthickness 0 \
2270            -command [itcl::code $this Slice move x] \
2271            -variable [itcl::scope _settings($this-xcutposition)]
2272    } {
2273        usual
2274        ignore -borderwidth -highlightthickness
2275    }
2276    # Set the default cutplane value before disabling the scale.
2277    $itk_component(xCutScale) set 50
2278    $itk_component(xCutScale) configure -state disabled
2279    Rappture::Tooltip::for $itk_component(xCutScale) \
2280        "@[itcl::code $this SlicerTip x]"
2281
2282    # Y-value slicer...
2283    itk_component add yCutButton {
2284        Rappture::PushButton $inner.ybutton \
2285            -onimage [Rappture::icon y-cutplane] \
2286            -offimage [Rappture::icon y-cutplane] \
2287            -command [itcl::code $this FixSettings ycutplane] \
2288            -variable [itcl::scope _settings($this-ycutplane)]
2289    }
2290    Rappture::Tooltip::for $itk_component(yCutButton) \
2291        "Toggle the Y cut plane on/off"
2292
2293    itk_component add yCutScale {
2294        ::scale $inner.yval -from 100 -to 0 \
2295            -width 10 -orient vertical -showvalue off \
2296            -borderwidth 1 -highlightthickness 0 \
2297            -command [itcl::code $this Slice move y] \
2298            -variable [itcl::scope _settings($this-ycutposition)]
2299    } {
2300        usual
2301        ignore -borderwidth -highlightthickness
2302    }
2303    Rappture::Tooltip::for $itk_component(yCutScale) \
2304        "@[itcl::code $this SlicerTip y]"
2305    # Set the default cutplane value before disabling the scale.
2306    $itk_component(yCutScale) set 50
2307    $itk_component(yCutScale) configure -state disabled
2308
2309    # Z-value slicer...
2310    itk_component add zCutButton {
2311        Rappture::PushButton $inner.zbutton \
2312            -onimage [Rappture::icon z-cutplane] \
2313            -offimage [Rappture::icon z-cutplane] \
2314            -command [itcl::code $this FixSettings zcutplane] \
2315            -variable [itcl::scope _settings($this-zcutplane)]
2316    }
2317    Rappture::Tooltip::for $itk_component(zCutButton) \
2318        "Toggle the Z cut plane on/off"
2319
2320    itk_component add zCutScale {
2321        ::scale $inner.zval -from 100 -to 0 \
2322            -width 10 -orient vertical -showvalue off \
2323            -borderwidth 1 -highlightthickness 0 \
2324            -command [itcl::code $this Slice move z] \
2325            -variable [itcl::scope _settings($this-zcutposition)]
2326    } {
2327        usual
2328        ignore -borderwidth -highlightthickness
2329    }
2330    $itk_component(zCutScale) set 50
2331    $itk_component(zCutScale) configure -state disabled
2332    #$itk_component(zCutScale) configure -state disabled
2333    Rappture::Tooltip::for $itk_component(zCutScale) \
2334        "@[itcl::code $this SlicerTip z]"
2335
2336    blt::table $inner \
2337        1,1 $itk_component(xCutButton) \
2338        1,2 $itk_component(yCutButton) \
2339        1,3 $itk_component(zCutButton) \
2340        0,1 $itk_component(xCutScale) \
2341        0,2 $itk_component(yCutScale) \
2342        0,3 $itk_component(zCutScale) \
2343
2344    blt::table configure $inner r0 r1 c* -resize none
2345    blt::table configure $inner r2 c4 -resize expand
2346    blt::table configure $inner c0 -width 2
2347    blt::table configure $inner c1 c2 c3 -padx 2
2348}
2349
2350itcl::body Rappture::FlowvisViewer::BuildCameraTab {} {
2351    set inner [$itk_component(main) insert end \
2352        -title "Camera Settings" \
2353        -icon [Rappture::icon camera]]
2354    $inner configure -borderwidth 4
2355
2356    set labels { phi theta psi pan-x pan-y zoom }
2357    set row 0
2358    foreach tag $labels {
2359        label $inner.${tag}label -text $tag -font "Arial 9"
2360        entry $inner.${tag} -font "Arial 9"  -bg white \
2361            -textvariable [itcl::scope _settings($this-$tag)]
2362        bind $inner.${tag} <KeyPress-Return> \
2363            [itcl::code $this camera set ${tag}]
2364        blt::table $inner \
2365            $row,0 $inner.${tag}label -anchor e -pady 2 \
2366            $row,1 $inner.${tag} -anchor w -pady 2
2367        blt::table configure $inner r$row -resize none
2368        incr row
2369    }
2370    blt::table configure $inner c0 c1 -resize none
2371    blt::table configure $inner c2 -resize expand
2372    blt::table configure $inner r$row -resize expand
2373}
2374
2375itcl::body Rappture::FlowvisViewer::GetFlowInfo { w } {
2376    set flowobj ""
2377    foreach key [array names _obj2flow] {
2378        set flowobj $_obj2flow($key)
2379        break
2380    }
2381    if { $flowobj == "" } {
2382        return
2383    }
2384    if { [winfo exists $w.frame] } {
2385        destroy $w.frame
2386    }
2387    set inner [frame $w.frame]
2388    blt::table $w \
2389        5,0 $inner -fill both -columnspan 2 -anchor nw
2390    array set hints [$flowobj hints]
2391    checkbutton $inner.showstreams -text "Streams Plane" \
2392        -variable [itcl::scope _settings($this-streams)] \
2393        -command  [itcl::code $this streams $key $hints(name)]  \
2394        -font "Arial 9"
2395    Rappture::Tooltip::for $inner.showstreams $hints(description)
2396
2397    checkbutton $inner.showarrows -text "Arrows" \
2398        -variable [itcl::scope _settings($this-arrows)] \
2399        -command  [itcl::code $this arrows $key $hints(name)]  \
2400        -font "Arial 9"
2401
2402    label $inner.particles -text "Particles"         -font "Arial 9 bold"
2403    label $inner.boxes -text "Boxes"         -font "Arial 9 bold"
2404
2405    blt::table $inner \
2406        1,0 $inner.showstreams  -anchor w \
2407        2,0 $inner.showarrows  -anchor w
2408    blt::table configure $inner c0 c1 -resize none
2409    blt::table configure $inner c2 -resize expand
2410
2411    set row 3
2412    set particles [$flowobj particles]
2413    if { [llength $particles] > 0 } {
2414        blt::table $inner $row,0 $inner.particles  -anchor w
2415        incr row
2416    }
2417    foreach part $particles {
2418        array unset info
2419        array set info $part
2420        set name $info(name)
2421        if { ![info exists _settings($this-particles-$name)] } {
2422            set _settings($this-particles-$name) $info(hide)
2423        }
2424        checkbutton $inner.part$row -text $info(label) \
2425            -variable [itcl::scope _settings($this-particles-$name)] \
2426            -onvalue 0 -offvalue 1 \
2427            -command [itcl::code $this particles $key $name] \
2428            -font "Arial 9"
2429        Rappture::Tooltip::for $inner.part$row $info(description)
2430        blt::table $inner $row,0 $inner.part$row -anchor w
2431        if { !$_settings($this-particles-$name) } {
2432            $inner.part$row select
2433        }
2434        incr row
2435    }
2436    set boxes [$flowobj boxes]
2437    if { [llength $boxes] > 0 } {
2438        blt::table $inner $row,0 $inner.boxes  -anchor w
2439        incr row
2440    }
2441    foreach box $boxes {
2442        array unset info
2443        array set info $box
2444        set name $info(name)
2445        if { ![info exists _settings($this-box-$name)] } {
2446            set _settings($this-box-$name) $info(hide)
2447        }
2448        checkbutton $inner.box$row -text $info(label) \
2449            -variable [itcl::scope _settings($this-box-$name)] \
2450            -onvalue 0 -offvalue 1 \
2451            -command [itcl::code $this box $key $name] \
2452            -font "Arial 9"
2453        Rappture::Tooltip::for $inner.box$row $info(description)
2454        blt::table $inner $row,0 $inner.box$row -anchor w
2455        if { !$_settings($this-box-$name) } {
2456            $inner.box$row select
2457        }
2458        incr row
2459    }
2460    blt::table configure $inner r* -resize none
2461    blt::table configure $inner r$row -resize expand
2462    blt::table configure $inner c3 -resize expand
2463    event generate [winfo parent [winfo parent $w]] <Configure>
2464}
2465
2466itcl::body Rappture::FlowvisViewer::particles { tag name } {
2467    set bool $_settings($this-particles-$name)
2468    SendCmd "$tag particles configure {$name} -hide $bool"
2469}
2470
2471itcl::body Rappture::FlowvisViewer::box { tag name } {
2472    set bool $_settings($this-box-$name)
2473    SendCmd "$tag box configure {$name} -hide $bool"
2474}
2475
2476itcl::body Rappture::FlowvisViewer::streams { tag name } {
2477    set bool $_settings($this-streams)
2478    SendCmd "$tag configure -slice $bool"
2479}
2480
2481itcl::body Rappture::FlowvisViewer::arrows { tag name } {
2482    set bool $_settings($this-arrows)
2483    SendCmd "$tag configure -arrows no"
2484}
2485
2486# ----------------------------------------------------------------------
2487# USAGE: Slice move x|y|z <newval>
2488#
2489# Called automatically when the user drags the slider to move the
2490# cut plane that slices 3D data.  Gets the current value from the
2491# slider and moves the cut plane to the appropriate point in the
2492# data set.
2493# ----------------------------------------------------------------------
2494itcl::body Rappture::FlowvisViewer::Slice {option args} {
2495    switch -- $option {
2496        move {
2497            if {[llength $args] != 2} {
2498                error "wrong # args: should be \"Slice move x|y|z newval\""
2499            }
2500            set axis [lindex $args 0]
2501            set newval [lindex $args 1]
2502            set newpos [expr {0.01*$newval}]
2503
2504            # show the current value in the readout
2505
2506            set ids [CurrentVolumeIds -cutplanes]
2507            SendCmd "cutplane position $newpos $axis $ids"
2508        }
2509        default {
2510            error "bad option \"$option\": should be axis, move, or volume"
2511        }
2512    }
2513}
2514
2515# ----------------------------------------------------------------------
2516# USAGE: SlicerTip <axis>
2517#
2518# Used internally to generate a tooltip for the x/y/z slicer controls.
2519# Returns a message that includes the current slicer value.
2520# ----------------------------------------------------------------------
2521itcl::body Rappture::FlowvisViewer::SlicerTip {axis} {
2522    set val [$itk_component(${axis}CutScale) get]
2523#    set val [expr {0.01*($val-50)
2524#        *($_limits(${axis}max)-$_limits(${axis}min))
2525#          + 0.5*($_limits(${axis}max)+$_limits(${axis}min))}]
2526    return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
2527}
2528
2529
2530itcl::body Rappture::FlowvisViewer::Resize {} {
2531    SendCmd "screen $_width $_height"
2532    set _resizePending 0
2533}
2534
2535itcl::body Rappture::FlowvisViewer::EventuallyResize { w h } {
2536    set _width $w
2537    set _height $h
2538    if { !$_resizePending } {
2539        $_dispatcher event -after 200 !resize
2540        set _resizePending 1
2541    }
2542}
2543
2544itcl::body Rappture::FlowvisViewer::EventuallyResizeLegend {} {
2545    if { !$_resizeLegendPending } {
2546        $_dispatcher event -after 100 !legend
2547        set _resizeLegendPending 1
2548    }
2549}
2550
2551itcl::body Rappture::FlowvisViewer::EventuallyGoto { nSteps } {
2552    set _flow(goto) $nSteps
2553    if { !$_gotoPending } {
2554        $_dispatcher event -after 1000 !goto
2555        set _gotoPending 1
2556    }
2557}
2558
2559#  camera --
2560itcl::body Rappture::FlowvisViewer::camera {option args} {
2561    switch -- $option {
2562        "show" {
2563            puts [array get _view]
2564        }
2565        "set" {
2566            set who [lindex $args 0]
2567            set x $_settings($this-$who)
2568            set code [catch { string is double $x } result]
2569            if { $code != 0 || !$result } {
2570                set _settings($this-$who) $_view($who)
2571                return
2572            }
2573            switch -- $who {
2574                "pan-x" - "pan-y" {
2575                    set _view($who) $_settings($this-$who)
2576                    PanCamera
2577                }
2578                "phi" - "theta" - "psi" {
2579                    set _view($who) $_settings($this-$who)
2580                    set xyz [Euler2XYZ $_view(theta) $_view(phi) $_view(psi)]
2581                    SendCmd "camera angle $xyz"
2582                }
2583                "zoom" {
2584                    set _view($who) $_settings($this-$who)
2585                    SendCmd "camera zoom $_view(zoom)"
2586                }
2587            }
2588        }
2589    }
2590}
2591
2592itcl::body Rappture::FlowvisViewer::FlowCmd { dataobj comp nbytes extents } {
2593    set tag "$dataobj-$comp"
2594    if { ![info exists _obj2flow($tag)] } {
2595        append cmd "flow add $tag\n"
2596        append cmd "$tag data follows $nbytes $extents\n"
2597        return $cmd
2598    }
2599    set flowobj $_obj2flow($tag)
2600    if { $flowobj == "" } {
2601        puts stderr "no flowobj"
2602        return ""
2603    }
2604    set cmd {}
2605    append cmd "if {\[flow exists $tag\]} {flow delete $tag}\n"
2606    array set info  [$flowobj hints]
2607    set _settings($this-volume) $info(volume)
2608    set _settings($this-outline) $info(outline)
2609    set _settings($this-arrows) $info(arrows)
2610    set _settings($this-duration) $info(duration)
2611    $itk_component(speed) value $info(speed)
2612    append cmd "flow add $tag"
2613    append cmd " -position $info(position)"
2614    append cmd " -axis $info(axis)"
2615    append cmd " -volume $info(volume)"
2616    append cmd " -outline $info(outline)"
2617    append cmd " -slice $info(streams)"
2618    append cmd " -arrows $info(arrows)\n"
2619    foreach part [$flowobj particles] {
2620        array unset info
2621        array set info $part
2622        set color [Color2RGB $info(color)]
2623        append cmd "$tag particles add $info(name)"
2624        append cmd " -position $info(position)"
2625        append cmd " -hide $info(hide)"
2626        append cmd " -axis $info(axis)"
2627        append cmd " -color {$color}"
2628        append cmd " -size $info(size)\n"
2629    }
2630    foreach box [$flowobj boxes] {
2631        array unset info
2632        set info(corner1) ""
2633        set info(corner2) ""
2634        array set info $box
2635        if { $info(corner1) == "" || $info(corner2) == "" } {
2636            continue
2637        }
2638        set color [Color2RGB $info(color)]
2639        append cmd "$tag box add $info(name)"
2640        append cmd " -color {$color}"
2641        append cmd " -hide $info(hide)"
2642        append cmd " -linewidth $info(linewidth) "
2643        append cmd " -corner1 {$info(corner1)} "
2644        append cmd " -corner2 {$info(corner2)}\n"
2645    }   
2646    append cmd "$tag data follows $nbytes $extents\n"
2647    return $cmd
2648}
2649
2650
2651#
2652# flow --
2653#
2654# Called when the user clicks on the stop or play buttons
2655# for flow visualization.
2656#
2657#        $this flow play
2658#        $this flow stop
2659#        $this flow toggle
2660#        $this flow reset
2661#        $this flow pause
2662#        $this flow next
2663#
2664itcl::body Rappture::FlowvisViewer::flow { args } {
2665    set option [lindex $args 0]
2666    switch -- $option {
2667        "goto2" {
2668            puts stderr "actually sending \"flow goto $_flow(goto)\""
2669            SendCmd "flow goto $_flow(goto)"
2670            set _gotoPending 0
2671        }
2672        "goto" {
2673            puts stderr "flow goto to $_settings($this-currenttime)"
2674            # Figure out how many steps to the current time based upon
2675            # the speed and duration.
2676            set current $_settings($this-currenttime)
2677            set speed [$itk_component(speed) value]
2678            set time [str2millisecs $_settings($this-duration)]
2679            $itk_component(dial) configure -max $time
2680            set delay [expr int(round(500.0/$speed))]
2681            set timePerStep [expr {double($time) / $delay}]
2682            set nSteps [expr {int(ceil($current/$timePerStep))}]
2683            EventuallyGoto $nSteps
2684        }
2685        "speed" {
2686            set speed [$itk_component(speed) value]
2687            set _flow(delay) [expr int(round(500.0/$speed))]
2688        }
2689        "duration" {
2690            set max [str2millisecs $_settings($this-duration)]
2691            if { $max < 0 } {
2692                bell
2693                return
2694            }
2695            set _flow(duration) $max
2696            set _settings($this-duration) [millisecs2str $max]
2697            $itk_component(dial) configure -max $max
2698        }
2699        "off" {
2700            set _flow(state) 0
2701            $_dispatcher cancel !play
2702            $itk_component(play) deselect
2703        }
2704        "on" {
2705            flow speed
2706            flow duration
2707            set _flow(state) 1
2708            set _settings($this-currenttime) 0
2709            $itk_component(play) select
2710        }
2711        "stop" {
2712            if { $_flow(state) } {
2713                flow off
2714                flow reset
2715            }
2716        }
2717        "pause" {
2718            if { $_flow(state) } {
2719                flow off
2720            }
2721        }
2722        "play" {
2723            # If the flow is currently off, then restart it.
2724            if { !$_flow(state) } {
2725                flow on
2726                # If we're at the end of the flow, reset the flow.
2727                set _settings($this-currenttime) \
2728                    [expr {$_settings($this-currenttime) + $_flow(delay)}]
2729                if { $_settings($this-currenttime) >= $_flow(duration) } {
2730                    set _settings($this-step) 1
2731                    SendCmd "flow reset"
2732                }
2733                flow next
2734            }
2735        }
2736        "toggle" {
2737            if { $_settings($this-play) } {
2738                flow play
2739            } else {
2740                flow pause
2741            }
2742        }
2743        "reset" {
2744            set _settings($this-currenttime) 0
2745            SendCmd "flow reset"
2746            if { !$_flow(state) } {
2747                SendCmd "flow next"
2748            }
2749        }
2750        "next" {
2751            if { ![winfo viewable $itk_component(3dview)] } {
2752                flow stop
2753                return
2754            }
2755            set _settings($this-currenttime) \
2756                [expr {$_settings($this-currenttime) + $_flow(delay)}]
2757            if { $_settings($this-currenttime) >= $_flow(duration) } {
2758                if { !$_settings($this-loop) } {
2759                    flow off
2760                    return
2761                }
2762                flow reset
2763            } else {
2764                SendCmd "flow next"
2765            }
2766            $_dispatcher event -after $_flow(delay) !play
2767        }
2768        default {
2769            error "bad option \"$option\": should be play, stop, toggle, or reset."
2770        }
2771    }
2772}
2773
2774itcl::body Rappture::FlowvisViewer::WaitIcon  { option widget } {
2775    switch -- $option {
2776        "start" {
2777            $_dispatcher dispatch $this !waiticon \
2778                "[itcl::code $this WaitIcon "next" $widget] ; list"
2779            set _icon 0
2780            $widget configure -image [Rappture::icon bigroller${_icon}]
2781            $_dispatcher event -after 100 !waiticon
2782        }
2783        "next" {
2784            incr _icon
2785            if { $_icon >= 8 } {
2786                set _icon 0
2787            }
2788            $widget configure -image [Rappture::icon bigroller${_icon}]
2789            $_dispatcher event -after 100 !waiticon
2790        }
2791        "stop" {
2792            $_dispatcher cancel !waiticon
2793        }
2794    }
2795}
2796
2797itcl::body Rappture::FlowvisViewer::GetPngImage  { widget width height } {
2798    set token "print[incr _nextToken]"
2799    set var ::Rappture::FlowvisViewer::_hardcopy($this-$token)
2800    set $var ""
2801
2802    # Setup an automatic timeout procedure.
2803    $_dispatcher dispatch $this !pngtimeout "set $var {} ; list"
2804
2805    set popup .flowvisviewerprint
2806    if {![winfo exists $popup]} {
2807        Rappture::Balloon $popup -title "Generating file..."
2808        set inner [$popup component inner]
2809        label $inner.title -text "Generating hardcopy." -font "Arial 10 bold"
2810        label $inner.please -text "This may take a minute." -font "Arial 10"
2811        label $inner.icon -image [Rappture::icon bigroller0]
2812        button $inner.cancel -text "Cancel" -font "Arial 10 bold" \
2813            -command [list set $var ""]
2814        blt::table $inner \
2815            0,0 $inner.title -columnspan 2 \
2816            1,0 $inner.please -anchor w \
2817            1,1 $inner.icon -anchor e  \
2818            2,0 $inner.cancel -columnspan 2
2819        blt::table configure $inner r0 -pady 4
2820        blt::table configure $inner r2 -pady 4
2821        bind $inner.cancel <KeyPress-Return> [list $inner.cancel invoke]
2822    } else {
2823        set inner [$popup component inner]
2824    }
2825
2826    $_dispatcher event -after 60000 !pngtimeout
2827    WaitIcon start $inner.icon
2828    grab set $inner
2829    focus $inner.cancel
2830
2831    SendCmd "print $token $width $height"
2832
2833    $popup activate $widget below
2834    update
2835    # We wait here for either
2836    #  1) the png to be delivered or
2837    #  2) timeout or 
2838    #  3) user cancels the operation.
2839    tkwait variable $var
2840
2841    # Clean up.
2842    $_dispatcher cancel !pngtimeout
2843    WaitIcon stop $inner.icon
2844    grab release $inner
2845    $popup deactivate
2846    update
2847
2848    if { $_hardcopy($this-$token) != "" } {
2849        return [list .png $_hardcopy($this-$token)]
2850    }
2851    return ""
2852}
2853
2854itcl::body Rappture::FlowvisViewer::GetMovie { widget w h } {
2855    set token "movie[incr _nextToken]"
2856    set var ::Rappture::FlowvisViewer::_hardcopy($this-$token)
2857    set $var ""
2858
2859    # Setup an automatic timeout procedure.
2860    $_dispatcher dispatch $this !movietimeout "set $var {} ; list"
2861    set popup .flowvisviewermovie
2862    if {![winfo exists $popup]} {
2863        Rappture::Balloon $popup -title "Generating movie..."
2864        set inner [$popup component inner]
2865        label $inner.title -text "Generating movie for download" \
2866                -font "Arial 10 bold"
2867        label $inner.please -text "This may take a few minutes." \
2868                -font "Arial 10"
2869        label $inner.icon -image [Rappture::icon bigroller0]
2870        button $inner.cancel -text "Cancel" -font "Arial 10 bold" \
2871            -command [list set $var ""]
2872        blt::table $inner \
2873            0,0 $inner.title -columnspan 2 \
2874            1,0 $inner.please -anchor w \
2875            1,1 $inner.icon -anchor e  \
2876            2,0 $inner.cancel -columnspan 2
2877        blt::table configure $inner r0 -pady 4
2878        blt::table configure $inner r2 -pady 4
2879        bind $inner.cancel <KeyPress-Return> [list $inner.cancel invoke]
2880    } else {
2881        set inner [$popup component inner]
2882    }
2883    # Timeout is set to 10 minutes.
2884    $_dispatcher event -after 600000 !movietimeout
2885    WaitIcon start $inner.icon
2886    grab set $inner
2887    focus $inner.cancel
2888   
2889    flow duration
2890    flow speed
2891    set nframes [expr round($_flow(duration) / $_flow(delay))]
2892    set framerate [expr 1000.0 / $_flow(delay)]
2893
2894    # These are specific to MPEG1 video generation
2895    set framerate 25.0
2896    set bitrate 6.0e+6
2897
2898    set start [clock seconds]
2899    SendCmd "flow video $token -width $w -height $h -numframes $nframes "
2900   
2901    $popup activate $widget below
2902    update
2903    # We wait here until
2904    #  1. the movie is delivered or
2905    #  2. we've timed out or 
2906    #  3. the user has canceled the operation.b
2907    tkwait variable $var
2908
2909    puts stderr "Video generated in [expr [clock seconds] - $start] seconds."
2910
2911    # Clean up.
2912    $_dispatcher cancel !movietimeout
2913    WaitIcon stop $inner.icon
2914    grab release $inner
2915    $popup deactivate
2916    destroy $popup
2917    update
2918
2919    # This will both cancel the movie generation (if it hasn't already
2920    # completed) and reset the flow.
2921    SendCmd "flow reset"
2922    if { $_hardcopy($this-$token) != "" } {
2923        return [list .mpg $_hardcopy($this-$token)]
2924    }
2925    return ""
2926}
2927
2928itcl::body Rappture::FlowvisViewer::str2millisecs { value } {
2929    set parts [split $value :]
2930    set secs 0
2931    set mins 0
2932    if { [llength $parts] == 1 } {
2933        scan [lindex $parts 0] "%d" secs
2934    } else {
2935        scan [lindex $parts 1] "%d" secs
2936        scan [lindex $parts 0] "%d" mins
2937    }
2938    set ms [expr {(($mins * 60) + $secs) * 1000.0}]
2939    if { $ms > 600000.0 } {
2940        set ms 600000.0
2941    }
2942    if { $ms == 0.0 } {
2943        set ms 60000.0
2944    }
2945    return $ms
2946}
2947
2948itcl::body Rappture::FlowvisViewer::millisecs2str { value } {
2949    set min [expr floor($value / 60000.0)]
2950    set sec [expr ($value - ($min*60000.0)) / 1000.0]
2951    return [format %02d:%02d [expr round($min)] [expr round($sec)]]
2952}
2953
Note: See TracBrowser for help on using the repository browser.