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

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

Merge nanovis2 branch to trunk

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