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

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