source: branches/1.3/gui/scripts/flowvisviewer.tcl @ 5255

Last change on this file since 5255 was 5255, checked in by ldelgass, 6 years ago

bring flowvisviewer closer in line with trunk/1.4 branch

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