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

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

Fix camera reset in nanovisviewer (leftover reference to orientation dropdown),
was causing a Tcl error. Bring flowvisviewer in line with nanovisviewer
changes.

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