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

Last change on this file since 5256 was 5256, checked in by ldelgass, 9 years ago

Sync view settings names 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        -xpan    0
225        -ypan    0
226        -zoom    1.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                -xpan    0
1368                -ypan    0
1369                -zoom    1.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 $_view(-xpan)
1394    set y $_view(-ypan)
1395    SendCmd "camera pan $x $y"
1396}
1397
1398# ----------------------------------------------------------------------
1399# USAGE: Rotate click <x> <y>
1400# USAGE: Rotate drag <x> <y>
1401# USAGE: Rotate release <x> <y>
1402#
1403# Called automatically when the user clicks/drags/releases in the
1404# plot area.  Moves the plot according to the user's actions.
1405# ----------------------------------------------------------------------
1406itcl::body Rappture::FlowvisViewer::Rotate {option x y} {
1407    switch -- $option {
1408        click {
1409            $itk_component(3dview) configure -cursor fleur
1410            set _click(x) $x
1411            set _click(y) $y
1412        }
1413        drag {
1414            if {[array size _click] == 0} {
1415                Rotate click $x $y
1416            } else {
1417                set w [winfo width $itk_component(3dview)]
1418                set h [winfo height $itk_component(3dview)]
1419                if {$w <= 0 || $h <= 0} {
1420                    return
1421                }
1422
1423                if {[catch {
1424                    # this fails sometimes for no apparent reason
1425                    set dx [expr {double($x-$_click(x))/$w}]
1426                    set dy [expr {double($y-$_click(y))/$h}]
1427                }]} {
1428                    return
1429                }
1430
1431                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1432                QuaternionToView $q
1433                set _settings($this-qw) $_view(-qw)
1434                set _settings($this-qx) $_view(-qx)
1435                set _settings($this-qy) $_view(-qy)
1436                set _settings($this-qz) $_view(-qz)
1437                SendCmd "camera orient $q"
1438
1439                set _click(x) $x
1440                set _click(y) $y
1441            }
1442        }
1443        release {
1444            Rotate drag $x $y
1445            $itk_component(3dview) configure -cursor ""
1446            catch {unset _click}
1447        }
1448        default {
1449            error "bad option \"$option\": should be click, drag, release"
1450        }
1451    }
1452}
1453
1454# ----------------------------------------------------------------------
1455# USAGE: $this Pan click x y
1456#        $this Pan drag x y
1457#        $this Pan release x y
1458#
1459# Called automatically when the user clicks on one of the zoom
1460# controls for this widget.  Changes the zoom for the current view.
1461# ----------------------------------------------------------------------
1462itcl::body Rappture::FlowvisViewer::Pan {option x y} {
1463    # Experimental stuff
1464    set w [winfo width $itk_component(3dview)]
1465    set h [winfo height $itk_component(3dview)]
1466    if { $option == "set" } {
1467        set x [expr $x / double($w)]
1468        set y [expr $y / double($h)]
1469        set _view(-xpan) [expr $_view(-xpan) + $x]
1470        set _view(-ypan) [expr $_view(-ypan) + $y]
1471        PanCamera
1472        set _settings($this-xpan) $_view(-xpan)
1473        set _settings($this-ypan) $_view(-ypan)
1474        return
1475    }
1476    if { $option == "click" } {
1477        set _click(x) $x
1478        set _click(y) $y
1479        $itk_component(3dview) configure -cursor hand1
1480    }
1481    if { $option == "drag" || $option == "release" } {
1482        set dx [expr ($_click(x) - $x)/double($w)]
1483        set dy [expr ($_click(y) - $y)/double($h)]
1484        set _click(x) $x
1485        set _click(y) $y
1486        set _view(-xpan) [expr $_view(-xpan) - $dx]
1487        set _view(-ypan) [expr $_view(-ypan) - $dy]
1488        PanCamera
1489        set _settings($this-xpan) $_view(-xpan)
1490        set _settings($this-ypan) $_view(-ypan)
1491    }
1492    if { $option == "release" } {
1493        $itk_component(3dview) configure -cursor ""
1494    }
1495}
1496
1497
1498# ----------------------------------------------------------------------
1499# USAGE: Flow movie record|stop|play ?on|off|toggle?
1500#
1501# Called when the user clicks on the record, stop or play buttons
1502# for flow visualization.
1503# ----------------------------------------------------------------------
1504itcl::body Rappture::FlowvisViewer::Flow {option args} {
1505    switch -- $option {
1506        movie {
1507            if {[llength $args] < 1 || [llength $args] > 2} {
1508                error "wrong # args: should be \"Flow movie record|stop|play ?on|off|toggle?\""
1509            }
1510            set action [lindex $args 0]
1511            set op [lindex $args 1]
1512            if {$op == ""} { set op "on" }
1513
1514            set current [State $action]
1515            if {$op == "toggle"} {
1516                if {$current == "on"} {
1517                    set op "off"
1518                } else {
1519                    set op "on"
1520                }
1521            }
1522            set cmds ""
1523            switch -- $action {
1524                record {
1525                    if { [$itk_component(rewind) cget -relief] != "sunken" } {
1526                        $itk_component(rewind) configure -relief sunken
1527                        $itk_component(stop) configure -relief raised
1528                        $itk_component(play) configure -relief raised
1529                        set inner $itk_component(settingsFrame)
1530                        set frames [$inner.framecnt value]
1531                        set _settings(nsteps) $frames
1532                        set cmds "flow capture $frames"
1533                        SendCmd $cmds
1534                    }
1535                }
1536                stop {
1537                    if { [$itk_component(stop) cget -relief] != "sunken" } {
1538                        $itk_component(rewind) configure -relief raised
1539                        $itk_component(stop) configure -relief sunken
1540                        $itk_component(play) configure -relief raised
1541                        _pause
1542                        set cmds "flow reset"
1543                        SendCmd $cmds
1544                    }
1545                }
1546                play {
1547                    if { [$itk_component(play) cget -relief] != "sunken" } {
1548                        $itk_component(rewind) configure -relief raised
1549                        $itk_component(stop) configure -relief raised
1550                        $itk_component(play) configure \
1551                            -image [Rappture::icon flow-pause] \
1552                            -relief sunken
1553                        bind $itk_component(play) <ButtonPress> \
1554                            [itcl::code $this _pause]
1555                        flow next
1556                    }
1557                }
1558                default {
1559                    error "bad option \"$option\": should be one of record|stop|play"
1560                }
1561
1562            }
1563        }
1564        default {
1565            error "bad option \"$option\": should be movie"
1566        }
1567    }
1568}
1569
1570# ----------------------------------------------------------------------
1571# USAGE: Play
1572#
1573# ----------------------------------------------------------------------
1574itcl::body Rappture::FlowvisViewer::Play {} {
1575    SendCmd "flow next"
1576    set delay [expr {int(ceil(pow($_settings(speed)/10.0+2,2.0)*15))}]
1577    $_dispatcher event -after $delay !play
1578}
1579
1580# ----------------------------------------------------------------------
1581# USAGE: Pause
1582#
1583# Invoked when the user hits the "pause" button to stop playing the
1584# current sequence of frames as a movie.
1585# ----------------------------------------------------------------------
1586itcl::body Rappture::FlowvisViewer::Pause {} {
1587    $_dispatcher cancel !play
1588
1589    # Toggle the button to "play" mode
1590    $itk_component(play) configure \
1591        -image [Rappture::icon flow-start] \
1592        -relief raised
1593    bind $itk_component(play) <ButtonPress> \
1594        [itcl::code $this Flow movie play toggle]
1595}
1596
1597# ----------------------------------------------------------------------
1598# USAGE: InitSettings <what> ?<value>?
1599#
1600# Used internally to update rendering settings whenever parameters
1601# change in the popup settings panel.  Sends the new settings off
1602# to the back end.
1603# ----------------------------------------------------------------------
1604itcl::body Rappture::FlowvisViewer::InitSettings { args } {
1605    foreach arg $args {
1606        AdjustSetting $arg
1607    }
1608}
1609
1610# ----------------------------------------------------------------------
1611# USAGE: AdjustSetting <what> ?<value>?
1612#
1613# Used internally to update rendering settings whenever parameters
1614# change in the popup settings panel.  Sends the new settings off
1615# to the back end.
1616# ----------------------------------------------------------------------
1617itcl::body Rappture::FlowvisViewer::AdjustSetting {what {value ""}} {
1618    switch -- $what {
1619        colormap {
1620            set color [$itk_component(colormap) value]
1621            set _settings(colormap) $color
1622            #ResetColormap $color
1623        }
1624        light {
1625            if { $_first != "" } {
1626                set comp [lindex [$_first components] 0]
1627                set tag $_first-$comp
1628                set diffuse [expr {0.01*$_settings($this-light)}]
1629                set ambient [expr {1.0 - $diffuse}]
1630                set specularLevel 0.3
1631                set specularExp 90.0
1632                SendCmd "$tag configure -ambient $ambient -diffuse $diffuse -specularLevel $specularLevel -specularExp $specularExp"
1633            }
1634        }
1635        light2side {
1636            if { $_first != "" } {
1637                set comp [lindex [$_first components] 0]
1638                set tag $_first-$comp
1639                set val $_settings($this-light2side)
1640                SendCmd "$tag configure -light2side $val"
1641            }
1642        }
1643        transp {
1644            if { $_first != "" } {
1645                set comp [lindex [$_first components] 0]
1646                set tag $_first-$comp
1647                set opacity [expr { 0.01 * double($_settings($this-transp)) }]
1648                SendCmd "$tag configure -opacity $opacity"
1649            }
1650        }
1651        opacity {
1652            if { $_first != "" && $_activeTf != "" } {
1653                set opacity [expr { 0.01 * double($_settings($this-opacity)) }]
1654                set tf $_activeTf
1655                set _settings($this-$tf-opacity) $opacity
1656                updateTransferFunctions
1657            }
1658        }
1659
1660        thickness {
1661            if { $_first != "" && $_activeTf != "" } {
1662                set val $_settings($this-thickness)
1663                # Scale values between 0.00001 and 0.01000
1664                set sval [expr {0.0001*double($val)}]
1665                set tf $_activeTf
1666                set _settings($this-$tf-thickness) $sval
1667                updateTransferFunctions
1668            }
1669        }
1670        "outline" {
1671            if { $_first != "" } {
1672                set comp [lindex [$_first components] 0]
1673                set tag $_first-$comp
1674                SendCmd "$tag configure -outline $_settings($this-outline)"
1675            }
1676        }
1677        "isosurface" {
1678            if { [isconnected] } {
1679                SendCmd "volume shading isosurface $_settings($this-isosurface)"
1680            }
1681        }
1682        "grid" {
1683            if { [isconnected] } {
1684                SendCmd "grid visible $_settings($this-grid)"
1685            }
1686        }
1687        "axes" {
1688            if { [isconnected] } {
1689                SendCmd "axis visible $_settings($this-axes)"
1690            }
1691        }
1692        "legend" {
1693            if { $_settings($this-legend) } {
1694                blt::table $itk_component(plotarea) \
1695                    0,0 $itk_component(3dview) -fill both \
1696                    1,0 $itk_component(legend) -fill x
1697                blt::table configure $itk_component(plotarea) r1 -resize none
1698            } else {
1699                blt::table forget $itk_component(legend)
1700            }
1701        }
1702        "volume" {
1703            if { $_first != "" } {
1704                set comp [lindex [$_first components] 0]
1705                set tag $_first-$comp
1706                SendCmd "$tag configure -volume $_settings($this-volume)"
1707            }
1708        }
1709        "xcutplane" - "ycutplane" - "zcutplane" {
1710            set axis [string range $what 0 0]
1711            set bool $_settings($this-$what)
1712            if { [isconnected] } {
1713                set vols [CurrentVolumeIds -cutplanes]
1714                SendCmd "cutplane state $bool $axis $vols"
1715            }
1716            if { $bool } {
1717                $itk_component(${axis}CutScale) configure -state normal \
1718                    -troughcolor white
1719            } else {
1720                $itk_component(${axis}CutScale) configure -state disabled \
1721                    -troughcolor grey82
1722            }
1723        }
1724        default {
1725            error "don't know how to fix $what"
1726        }
1727    }
1728}
1729
1730# ----------------------------------------------------------------------
1731# USAGE: ResizeLegend
1732#
1733# Used internally to update the legend area whenever it changes size
1734# or when the field changes.  Asks the server to send a new legend
1735# for the current field.
1736# ----------------------------------------------------------------------
1737itcl::body Rappture::FlowvisViewer::ResizeLegend {} {
1738    set _resizeLegendPending 0
1739    set lineht [font metrics $itk_option(-font) -linespace]
1740    set w [expr {$_width-20}]
1741    set h [expr {[winfo height $itk_component(legend)]-20-$lineht}]
1742
1743    if { $_first == "" } {
1744        return
1745    }
1746    set comp [lindex [$_first components] 0]
1747    set tag $_first-$comp
1748    #set _activeTf [lindex $_obj2style($tag) 0]
1749    if {$w > 0 && $h > 0 && "" != $_activeTf} {
1750        #SendCmd "legend $_activeTf $w $h"
1751        SendCmd "$tag legend $w $h"
1752    } else {
1753    # Can't do this as this will remove the items associated with the
1754    # isomarkers.
1755
1756    #$itk_component(legend) delete all
1757    }
1758}
1759
1760#
1761# NameTransferFunc --
1762#
1763#       Creates a transfer function name based on the <style> settings in the
1764#       library run.xml file. This placeholder will be used later to create
1765#       and send the actual transfer function once the data info has been sent
1766#       to us by the render server. [We won't know the volume limits until the
1767#       server parses the 3D data and sends back the limits via ReceiveData.]
1768#
1769#       FIXME: The current way we generate transfer-function names completely
1770#              ignores the -markers option.  The problem is that we are forced
1771#              to compute the name from an increasing complex set of values:
1772#              color, levels, marker, opacity.  I think we're stuck doing it
1773#              now.
1774#
1775itcl::body Rappture::FlowvisViewer::NameTransferFunc { dataobj comp } {
1776    array set style {
1777        -color BCGYR
1778        -levels 6
1779        -opacity 1.0
1780        -light 40
1781        -transp 50
1782    }
1783    array set style [lindex [$dataobj components -style $comp] 0]
1784    set _settings($this-light) $style(-light)
1785    set _settings($this-transp) $style(-transp)
1786    set _settings($this-opacity) [expr $style(-opacity) * 100]
1787    set tf "$style(-color):$style(-levels):$style(-opacity)"
1788    set _obj2style($dataobj-$comp) $tf
1789    lappend _style2objs($tf) $dataobj $comp
1790    return $tf
1791}
1792
1793#
1794# ComputeTransferFunc --
1795#
1796#   Computes and sends the transfer function to the render server.  It's
1797#   assumed that the volume data limits are known and that the global
1798#   transfer-functions slider values have be setup.  Both parts are
1799#   needed to compute the relative value (location) of the marker, and
1800#   the alpha map of the transfer function.
1801#
1802itcl::body Rappture::FlowvisViewer::ComputeTransferFunc { tf } {
1803    array set style {
1804        -color BCGYR
1805        -levels 6
1806        -opacity 1.0
1807        -light 40
1808        -transp 50
1809    }
1810    set dataobj ""; set comp ""
1811    foreach {dataobj comp} $_style2objs($tf) break
1812    if { $dataobj == "" } {
1813        return 0
1814    }
1815    array set style [lindex [$dataobj components -style $comp] 0]
1816
1817
1818    # We have to parse the style attributes for a volume using this
1819    # transfer-function *once*.  This sets up the initial isomarkers for the
1820    # transfer function.  The user may add/delete markers, so we have to
1821    # maintain a list of markers for each transfer-function.  We use the one
1822    # of the volumes (the first in the list) using the transfer-function as a
1823    # reference.
1824    #
1825    # FIXME: The current way we generate transfer-function names completely
1826    #        ignores the -markers option.  The problem is that we are forced
1827    #        to compute the name from an increasing complex set of values:
1828    #        color, levels, marker, opacity.  I think the cow's out of the
1829    #        barn on this one.
1830
1831    if { ![info exists _isomarkers($tf)] } {
1832        # Have to defer creation of isomarkers until we have data limits
1833        if { [info exists style(-markers)] &&
1834             [llength $style(-markers)] > 0  } {
1835            ParseMarkersOption $tf $style(-markers)
1836        } else {
1837            ParseLevelsOption $tf $style(-levels)
1838        }
1839    }
1840    if { [info exists style(-nonuniformcolors)] } {
1841        foreach { value color } $style(-nonuniformcolors) {
1842            append cmap "$value [Color2RGB $color] "
1843        }
1844    } else {
1845        set cmap [ColorsToColormap $style(-color)]
1846    }
1847    set tag $this-$tf
1848    if { ![info exists _settings($tag-opacity)] } {
1849        set _settings($tag-opacity) $style(-opacity)
1850    }
1851    set max 1.0 ;#$_settings($tag-opacity)
1852
1853    set isovalues {}
1854    foreach m $_isomarkers($tf) {
1855        lappend isovalues [$m relval]
1856    }
1857    # Sort the isovalues
1858    set isovalues [lsort -real $isovalues]
1859
1860    if { ![info exists _settings($tag-thickness)]} {
1861        set _settings($tag-thickness) 0.005
1862    }
1863    set delta $_settings($tag-thickness)
1864
1865    set first [lindex $isovalues 0]
1866    set last [lindex $isovalues end]
1867    set amap ""
1868    if { $first == "" || $first != 0.0 } {
1869        lappend amap 0.0 0.0
1870    }
1871    foreach x $isovalues {
1872        set x1 [expr {$x-$delta-0.00001}]
1873        set x2 [expr {$x-$delta}]
1874        set x3 [expr {$x+$delta}]
1875        set x4 [expr {$x+$delta+0.00001}]
1876        if { $x1 < 0.0 } {
1877            set x1 0.0
1878        } elseif { $x1 > 1.0 } {
1879            set x1 1.0
1880        }
1881        if { $x2 < 0.0 } {
1882            set x2 0.0
1883        } elseif { $x2 > 1.0 } {
1884            set x2 1.0
1885        }
1886        if { $x3 < 0.0 } {
1887            set x3 0.0
1888        } elseif { $x3 > 1.0 } {
1889            set x3 1.0
1890        }
1891        if { $x4 < 0.0 } {
1892            set x4 0.0
1893        } elseif { $x4 > 1.0 } {
1894            set x4 1.0
1895        }
1896        # add spikes in the middle
1897        lappend amap $x1 0.0
1898        lappend amap $x2 $max
1899        lappend amap $x3 $max
1900        lappend amap $x4 0.0
1901    }
1902    if { $last == "" || $last != 1.0 } {
1903        lappend amap 1.0 0.0
1904    }
1905    SendCmd "transfunc define $tf { $cmap } { $amap }"
1906    return [SendCmd "$dataobj-$comp configure -transferfunction $tf"]
1907}
1908
1909# ----------------------------------------------------------------------
1910# CONFIGURATION OPTION: -plotbackground
1911# ----------------------------------------------------------------------
1912itcl::configbody Rappture::FlowvisViewer::plotbackground {
1913    if { [isconnected] } {
1914        foreach {r g b} [Color2RGB $itk_option(-plotbackground)] break
1915        #fix this!
1916        #SendCmd "color background $r $g $b"
1917    }
1918}
1919
1920# ----------------------------------------------------------------------
1921# CONFIGURATION OPTION: -plotforeground
1922# ----------------------------------------------------------------------
1923itcl::configbody Rappture::FlowvisViewer::plotforeground {
1924    if { [isconnected] } {
1925        foreach {r g b} [Color2RGB $itk_option(-plotforeground)] break
1926        #fix this!
1927        #SendCmd "color background $r $g $b"
1928    }
1929}
1930
1931# ----------------------------------------------------------------------
1932# CONFIGURATION OPTION: -plotoutline
1933# ----------------------------------------------------------------------
1934itcl::configbody Rappture::FlowvisViewer::plotoutline {
1935    # Must check if we are connected because this routine is called from the
1936    # class body when the -plotoutline itk_option is defined.  At that point
1937    # the FlowvisViewer class constructor hasn't been called, so we can't
1938    # start sending commands to visualization server.
1939    if { [isconnected] } {
1940        if {"" == $itk_option(-plotoutline)} {
1941            SendCmd "volume outline state off"
1942        } else {
1943            SendCmd "volume outline state on"
1944            SendCmd "volume outline color [Color2RGB $itk_option(-plotoutline)]"
1945        }
1946    }
1947}
1948
1949#
1950# The -levels option takes a single value that represents the number
1951# of evenly distributed markers based on the current data range. Each
1952# marker is a relative value from 0.0 to 1.0.
1953#
1954itcl::body Rappture::FlowvisViewer::ParseLevelsOption { tf levels } {
1955    set c $itk_component(legend)
1956    regsub -all "," $levels " " levels
1957    if {[string is int $levels]} {
1958        for {set i 1} { $i <= $levels } {incr i} {
1959            set x [expr {double($i)/($levels+1)}]
1960            set m [Rappture::IsoMarker \#auto $c $this $tf]
1961            $m relval $x
1962            lappend _isomarkers($tf) $m
1963        }
1964    } else {
1965        foreach x $levels {
1966            set m [Rappture::IsoMarker \#auto $c $this $tf]
1967            $m relval $x
1968            lappend _isomarkers($tf) $m
1969        }
1970    }
1971}
1972
1973#
1974# The -markers option takes a list of zero or more values (the values
1975# may be separated either by spaces or commas) that have the following
1976# format:
1977#
1978#   N%  Percent of current total data range.  Converted to
1979#       to a relative value between 0.0 and 1.0.
1980#   N   Absolute value of marker.  If the marker is outside of
1981#       the current range, it will be displayed on the outer
1982#       edge of the legends, but it range it represents will
1983#       not be seen.
1984#
1985itcl::body Rappture::FlowvisViewer::ParseMarkersOption { tf markers } {
1986    set c $itk_component(legend)
1987    regsub -all "," $markers " " markers
1988    foreach marker $markers {
1989        set n [scan $marker "%g%s" value suffix]
1990        if { $n == 2 && $suffix == "%" } {
1991            # ${n}% : Set relative value.
1992            set value [expr {$value * 0.01}]
1993            set m [Rappture::IsoMarker \#auto $c $this $tf]
1994            $m relval $value
1995            lappend _isomarkers($tf) $m
1996        } else {
1997            # ${n} : Set absolute value.
1998            set m [Rappture::IsoMarker \#auto $c $this $tf]
1999            $m absval $value
2000            lappend _isomarkers($tf) $m
2001        }
2002    }
2003}
2004
2005# ----------------------------------------------------------------------
2006# USAGE: UndateTransferFuncs
2007# ----------------------------------------------------------------------
2008itcl::body Rappture::FlowvisViewer::updateTransferFunctions {} {
2009    $_dispatcher event -after 100 !send_transfunc
2010}
2011
2012itcl::body Rappture::FlowvisViewer::AddIsoMarker { x y } {
2013    if { $_activeTf == "" } {
2014        error "active transfer function isn't set"
2015    }
2016    set tf $_activeTf
2017    set c $itk_component(legend)
2018    set m [Rappture::IsoMarker \#auto $c $this $tf]
2019    set w [winfo width $c]
2020    $m relval [expr {double($x-10)/($w-20)}]
2021    lappend _isomarkers($tf) $m
2022    updateTransferFunctions
2023    return 1
2024}
2025
2026itcl::body Rappture::FlowvisViewer::removeDuplicateMarker { marker x } {
2027    set tf [$marker transferfunc]
2028    set bool 0
2029    if { [info exists _isomarkers($tf)] } {
2030        set list {}
2031        set marker [namespace tail $marker]
2032        foreach m $_isomarkers($tf) {
2033            set sx [$m screenpos]
2034            if { $m != $marker } {
2035                if { $x >= ($sx-3) && $x <= ($sx+3) } {
2036                    $marker relval [$m relval]
2037                    itcl::delete object $m
2038                    bell
2039                    set bool 1
2040                    continue
2041                }
2042            }
2043            lappend list $m
2044        }
2045        set _isomarkers($tf) $list
2046        updateTransferFunctions
2047    }
2048    return $bool
2049}
2050
2051itcl::body Rappture::FlowvisViewer::overMarker { marker x } {
2052    set tf [$marker transferfunc]
2053    if { [info exists _isomarkers($tf)] } {
2054        set marker [namespace tail $marker]
2055        foreach m $_isomarkers($tf) {
2056            set sx [$m screenpos]
2057            if { $m != $marker } {
2058                set bool [expr { $x >= ($sx-3) && $x <= ($sx+3) }]
2059                $m activate $bool
2060            }
2061        }
2062    }
2063    return ""
2064}
2065
2066itcl::body Rappture::FlowvisViewer::limits { tf } {
2067    set _limits(vmin) 0.0
2068    set _limits(vmax) 1.0
2069    if { ![info exists _style2objs($tf)] } {
2070        puts stderr "no style2objs for $tf tf=($tf)"
2071        return [array get _limits]
2072    }
2073    set min ""; set max ""
2074    foreach {dataobj comp} $_style2objs($tf) {
2075        set tag $dataobj-$comp
2076        if { ![info exists _serverObjs($tag)] } {
2077            puts stderr "$tag not in serverObjs?"
2078            continue
2079        }
2080        if { ![info exists _limits($tag-min)] } {
2081            puts stderr "$tag no min?"
2082            continue
2083        }
2084        if { $min == "" || $min > $_limits($tag-min) } {
2085            set min $_limits($tag-min)
2086        }
2087        if { $max == "" || $max < $_limits($tag-max) } {
2088            set max $_limits($tag-max)
2089        }
2090    }
2091    if { $min != "" } {
2092        set _limits(vmin) $min
2093    }
2094    if { $max != "" } {
2095        set _limits(vmax) $max
2096    }
2097    return [array get _limits]
2098}
2099
2100itcl::body Rappture::FlowvisViewer::BuildViewTab {} {
2101    foreach { key value } {
2102        grid            0
2103        axes            0
2104        outline         1
2105        volume          1
2106        legend          1
2107        particles       1
2108        lic             1
2109    } {
2110        set _settings($this-$key) $value
2111    }
2112
2113    set fg [option get $itk_component(hull) font Font]
2114    #set bfg [option get $itk_component(hull) boldFont Font]
2115
2116    set inner [$itk_component(main) insert end \
2117        -title "View Settings" \
2118        -icon [Rappture::icon wrench]]
2119    $inner configure -borderwidth 4
2120
2121    set ::Rappture::FlowvisViewer::_settings($this-isosurface) 0
2122    checkbutton $inner.isosurface \
2123        -text "Isosurface shading" \
2124        -variable [itcl::scope _settings($this-isosurface)] \
2125        -command [itcl::code $this AdjustSetting isosurface] \
2126        -font "Arial 9"
2127
2128    checkbutton $inner.axes \
2129        -text "Axes" \
2130        -variable [itcl::scope _settings($this-axes)] \
2131        -command [itcl::code $this AdjustSetting axes] \
2132        -font "Arial 9"
2133
2134    checkbutton $inner.grid \
2135        -text "Grid" \
2136        -variable [itcl::scope _settings($this-grid)] \
2137        -command [itcl::code $this AdjustSetting grid] \
2138        -font "Arial 9"
2139
2140    checkbutton $inner.outline \
2141        -text "Outline" \
2142        -variable [itcl::scope _settings($this-outline)] \
2143        -command [itcl::code $this AdjustSetting outline] \
2144        -font "Arial 9"
2145
2146    checkbutton $inner.legend \
2147        -text "Legend" \
2148        -variable [itcl::scope _settings($this-legend)] \
2149        -command [itcl::code $this AdjustSetting legend] \
2150        -font "Arial 9"
2151
2152    checkbutton $inner.volume \
2153        -text "Volume" \
2154        -variable [itcl::scope _settings($this-volume)] \
2155        -command [itcl::code $this AdjustSetting volume] \
2156        -font "Arial 9"
2157
2158    checkbutton $inner.particles \
2159        -text "Particles" \
2160        -variable [itcl::scope _settings($this-particles)] \
2161        -command [itcl::code $this AdjustSetting particles] \
2162        -font "Arial 9"
2163
2164    checkbutton $inner.lic \
2165        -text "Lic" \
2166        -variable [itcl::scope _settings($this-lic)] \
2167        -command [itcl::code $this AdjustSetting lic] \
2168        -font "Arial 9"
2169
2170    frame $inner.frame
2171
2172    blt::table $inner \
2173        0,0 $inner.axes  -cspan 2 -anchor w \
2174        1,0 $inner.grid  -cspan 2 -anchor w \
2175        2,0 $inner.outline  -cspan 2 -anchor w \
2176        3,0 $inner.volume  -cspan 2 -anchor w \
2177        4,0 $inner.legend  -cspan 2 -anchor w
2178
2179    bind $inner <Map> [itcl::code $this GetFlowInfo $inner]
2180
2181    blt::table configure $inner r* -resize none
2182    blt::table configure $inner r5 -resize expand
2183}
2184
2185itcl::body Rappture::FlowvisViewer::BuildVolumeTab {} {
2186    foreach { key value } {
2187        light2side      1
2188        light           40
2189        transp          50
2190        opacity         100
2191        thickness       350
2192    } {
2193        set _settings($this-$key) $value
2194    }
2195
2196    set inner [$itk_component(main) insert end \
2197        -title "Volume Settings" \
2198        -icon [Rappture::icon volume-on]]
2199    $inner configure -borderwidth 4
2200
2201    set fg [option get $itk_component(hull) font Font]
2202    #set bfg [option get $itk_component(hull) boldFont Font]
2203
2204    checkbutton $inner.vol -text "Show volume" -font $fg \
2205        -text "Volume" \
2206        -variable [itcl::scope _settings($this-volume)] \
2207        -command [itcl::code $this AdjustSetting volume] \
2208        -font "Arial 9"
2209
2210    label $inner.shading -text "Shading:" -font $fg
2211
2212    checkbutton $inner.light2side -text "Two-sided lighting" -font $fg \
2213        -variable [itcl::scope _settings($this-light2side)] \
2214        -command [itcl::code $this AdjustSetting light2side]
2215
2216    label $inner.dim -text "Glow" -font $fg
2217    ::scale $inner.light -from 0 -to 100 -orient horizontal \
2218        -variable [itcl::scope _settings($this-light)] \
2219        -width 10 \
2220        -showvalue off -command [itcl::code $this AdjustSetting light]
2221    label $inner.bright -text "Surface" -font $fg
2222
2223    label $inner.fog -text "Clear" -font $fg
2224    ::scale $inner.transp -from 0 -to 100 -orient horizontal \
2225        -variable [itcl::scope _settings($this-transp)] \
2226        -width 10 \
2227        -showvalue off -command [itcl::code $this AdjustSetting transp]
2228    label $inner.plastic -text "Opaque" -font $fg
2229
2230    label $inner.clear -text "Clear" -font $fg
2231    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
2232        -variable [itcl::scope _settings($this-opacity)] \
2233        -width 10 \
2234        -showvalue off -command [itcl::code $this AdjustSetting opacity]
2235    label $inner.opaque -text "Opaque" -font $fg
2236
2237    label $inner.thin -text "Thin" -font $fg
2238    ::scale $inner.thickness -from 0 -to 1000 -orient horizontal \
2239        -variable [itcl::scope _settings($this-thickness)] \
2240        -width 10 \
2241        -showvalue off -command [itcl::code $this AdjustSetting thickness]
2242    label $inner.thick -text "Thick" -font $fg
2243
2244    label $inner.colormap_l -text "Colormap" -font "Arial 9"
2245    itk_component add colormap {
2246        Rappture::Combobox $inner.colormap -width 10 -editable no
2247    }
2248
2249    $inner.colormap choices insert end [GetColormapList -includeNone]
2250    $itk_component(colormap) value "BCGYR"
2251    bind $inner.colormap <<Value>> \
2252        [itcl::code $this AdjustSetting colormap]
2253
2254    blt::table $inner \
2255        0,0 $inner.vol -cspan 4 -anchor w -pady 2 \
2256        1,0 $inner.shading -cspan 4 -anchor w -pady {10 2} \
2257        2,0 $inner.light2side -cspan 4 -anchor w -pady 2 \
2258        3,0 $inner.dim -anchor e -pady 2 \
2259        3,1 $inner.light -cspan 2 -pady 2 -fill x \
2260        3,3 $inner.bright -anchor w -pady 2 \
2261        4,0 $inner.fog -anchor e -pady 2 \
2262        4,1 $inner.transp -cspan 2 -pady 2 -fill x \
2263        4,3 $inner.plastic -anchor w -pady 2 \
2264        5,0 $inner.thin -anchor e -pady 2 \
2265        5,1 $inner.thickness -cspan 2 -pady 2 -fill x\
2266        5,3 $inner.thick -anchor w -pady 2
2267
2268    blt::table configure $inner c0 c1 c3 r* -resize none
2269    blt::table configure $inner r6 -resize expand
2270}
2271
2272itcl::body Rappture::FlowvisViewer::BuildCutplanesTab {} {
2273    set inner [$itk_component(main) insert end \
2274        -title "Cutplane Settings" \
2275        -icon [Rappture::icon cutbutton]]
2276    $inner configure -borderwidth 4
2277
2278    # X-value slicer...
2279    itk_component add xCutButton {
2280        Rappture::PushButton $inner.xbutton \
2281            -onimage [Rappture::icon x-cutplane] \
2282            -offimage [Rappture::icon x-cutplane] \
2283            -command [itcl::code $this AdjustSetting xcutplane] \
2284            -variable [itcl::scope _settings($this-xcutplane)]
2285    }
2286    Rappture::Tooltip::for $itk_component(xCutButton) \
2287        "Toggle the X cut plane on/off"
2288
2289    itk_component add xCutScale {
2290        ::scale $inner.xval -from 100 -to 0 \
2291            -width 10 -orient vertical -showvalue off \
2292            -borderwidth 1 -highlightthickness 0 \
2293            -command [itcl::code $this Slice move x] \
2294            -variable [itcl::scope _settings($this-xcutposition)]
2295    } {
2296        usual
2297        ignore -borderwidth -highlightthickness
2298    }
2299    # Set the default cutplane value before disabling the scale.
2300    $itk_component(xCutScale) set 50
2301    $itk_component(xCutScale) configure -state disabled
2302    Rappture::Tooltip::for $itk_component(xCutScale) \
2303        "@[itcl::code $this SlicerTip x]"
2304
2305    # Y-value slicer...
2306    itk_component add yCutButton {
2307        Rappture::PushButton $inner.ybutton \
2308            -onimage [Rappture::icon y-cutplane] \
2309            -offimage [Rappture::icon y-cutplane] \
2310            -command [itcl::code $this AdjustSetting ycutplane] \
2311            -variable [itcl::scope _settings($this-ycutplane)]
2312    }
2313    Rappture::Tooltip::for $itk_component(yCutButton) \
2314        "Toggle the Y cut plane on/off"
2315
2316    itk_component add yCutScale {
2317        ::scale $inner.yval -from 100 -to 0 \
2318            -width 10 -orient vertical -showvalue off \
2319            -borderwidth 1 -highlightthickness 0 \
2320            -command [itcl::code $this Slice move y] \
2321            -variable [itcl::scope _settings($this-ycutposition)]
2322    } {
2323        usual
2324        ignore -borderwidth -highlightthickness
2325    }
2326    Rappture::Tooltip::for $itk_component(yCutScale) \
2327        "@[itcl::code $this SlicerTip y]"
2328    # Set the default cutplane value before disabling the scale.
2329    $itk_component(yCutScale) set 50
2330    $itk_component(yCutScale) configure -state disabled
2331
2332    # Z-value slicer...
2333    itk_component add zCutButton {
2334        Rappture::PushButton $inner.zbutton \
2335            -onimage [Rappture::icon z-cutplane] \
2336            -offimage [Rappture::icon z-cutplane] \
2337            -command [itcl::code $this AdjustSetting zcutplane] \
2338            -variable [itcl::scope _settings($this-zcutplane)]
2339    }
2340    Rappture::Tooltip::for $itk_component(zCutButton) \
2341        "Toggle the Z cut plane on/off"
2342
2343    itk_component add zCutScale {
2344        ::scale $inner.zval -from 100 -to 0 \
2345            -width 10 -orient vertical -showvalue off \
2346            -borderwidth 1 -highlightthickness 0 \
2347            -command [itcl::code $this Slice move z] \
2348            -variable [itcl::scope _settings($this-zcutposition)]
2349    } {
2350        usual
2351        ignore -borderwidth -highlightthickness
2352    }
2353    $itk_component(zCutScale) set 50
2354    $itk_component(zCutScale) configure -state disabled
2355    #$itk_component(zCutScale) configure -state disabled
2356    Rappture::Tooltip::for $itk_component(zCutScale) \
2357        "@[itcl::code $this SlicerTip z]"
2358
2359    blt::table $inner \
2360        1,1 $itk_component(xCutButton) \
2361        1,2 $itk_component(yCutButton) \
2362        1,3 $itk_component(zCutButton) \
2363        0,1 $itk_component(xCutScale) \
2364        0,2 $itk_component(yCutScale) \
2365        0,3 $itk_component(zCutScale) \
2366
2367    blt::table configure $inner r0 r1 c* -resize none
2368    blt::table configure $inner r2 c4 -resize expand
2369    blt::table configure $inner c0 -width 2
2370    blt::table configure $inner c1 c2 c3 -padx 2
2371}
2372
2373itcl::body Rappture::FlowvisViewer::BuildCameraTab {} {
2374    set inner [$itk_component(main) insert end \
2375        -title "Camera Settings" \
2376        -icon [Rappture::icon camera]]
2377    $inner configure -borderwidth 4
2378
2379    label $inner.view_l -text "view" -font "Arial 9"
2380    set f [frame $inner.view]
2381    foreach side { front back left right top bottom } {
2382        button $f.$side  -image [Rappture::icon view$side] \
2383            -command [itcl::code $this SetOrientation $side]
2384        Rappture::Tooltip::for $f.$side "Change the view to $side"
2385        pack $f.$side -side left
2386    }
2387
2388    blt::table $inner \
2389        0,0 $inner.view_l -anchor e -pady 2 \
2390        0,1 $inner.view -anchor w -pady 2
2391    blt::table configure $inner r0 -resize none
2392
2393    set row 1
2394    set labels { qw qx qy qz xpan ypan zoom }
2395    foreach tag $labels {
2396        label $inner.${tag}label -text $tag -font "Arial 9"
2397        entry $inner.${tag} -font "Arial 9"  -bg white \
2398            -textvariable [itcl::scope _settings($this-$tag)]
2399        bind $inner.${tag} <Return> \
2400            [itcl::code $this camera set -${tag}]
2401        bind $inner.${tag} <KP_Enter> \
2402            [itcl::code $this camera set -${tag}]
2403        blt::table $inner \
2404            $row,0 $inner.${tag}label -anchor e -pady 2 \
2405            $row,1 $inner.${tag} -anchor w -pady 2
2406        blt::table configure $inner r$row -resize none
2407        incr row
2408    }
2409
2410    blt::table configure $inner c* -resize none
2411    blt::table configure $inner c2 -resize expand
2412    blt::table configure $inner r$row -resize expand
2413}
2414
2415itcl::body Rappture::FlowvisViewer::GetFlowInfo { w } {
2416    set flowobj ""
2417    foreach key [array names _obj2flow] {
2418        set flowobj $_obj2flow($key)
2419        break
2420    }
2421    if { $flowobj == "" } {
2422        return
2423    }
2424    if { [winfo exists $w.frame] } {
2425        destroy $w.frame
2426    }
2427    set inner [frame $w.frame]
2428    blt::table $w \
2429        5,0 $inner -fill both -cspan 2 -anchor nw
2430    array set hints [$flowobj hints]
2431    checkbutton $inner.showstreams -text "Streams Plane" \
2432        -variable [itcl::scope _settings($this-streams)] \
2433        -command  [itcl::code $this streams $key $hints(name)]  \
2434        -font "Arial 9"
2435    Rappture::Tooltip::for $inner.showstreams $hints(description)
2436
2437    checkbutton $inner.showarrows -text "Arrows" \
2438        -variable [itcl::scope _settings($this-arrows)] \
2439        -command  [itcl::code $this arrows $key $hints(name)]  \
2440        -font "Arial 9"
2441
2442    label $inner.particles -text "Particles"         -font "Arial 9 bold"
2443    label $inner.boxes -text "Boxes"         -font "Arial 9 bold"
2444
2445    blt::table $inner \
2446        1,0 $inner.showstreams  -anchor w \
2447        2,0 $inner.showarrows  -anchor w
2448    blt::table configure $inner c0 c1 -resize none
2449    blt::table configure $inner c2 -resize expand
2450
2451    set row 3
2452    set particles [$flowobj particles]
2453    if { [llength $particles] > 0 } {
2454        blt::table $inner $row,0 $inner.particles  -anchor w
2455        incr row
2456    }
2457    foreach part $particles {
2458        array unset info
2459        array set info $part
2460        set name $info(name)
2461        if { ![info exists _settings($this-particles-$name)] } {
2462            set _settings($this-particles-$name) $info(hide)
2463        }
2464        checkbutton $inner.part$row -text $info(label) \
2465            -variable [itcl::scope _settings($this-particles-$name)] \
2466            -onvalue 0 -offvalue 1 \
2467            -command [itcl::code $this particles $key $name] \
2468            -font "Arial 9"
2469        Rappture::Tooltip::for $inner.part$row $info(description)
2470        blt::table $inner $row,0 $inner.part$row -anchor w
2471        if { !$_settings($this-particles-$name) } {
2472            $inner.part$row select
2473        }
2474        incr row
2475    }
2476    set boxes [$flowobj boxes]
2477    if { [llength $boxes] > 0 } {
2478        blt::table $inner $row,0 $inner.boxes  -anchor w
2479        incr row
2480    }
2481    foreach box $boxes {
2482        array unset info
2483        array set info $box
2484        set name $info(name)
2485        if { ![info exists _settings($this-box-$name)] } {
2486            set _settings($this-box-$name) $info(hide)
2487        }
2488        checkbutton $inner.box$row -text $info(label) \
2489            -variable [itcl::scope _settings($this-box-$name)] \
2490            -onvalue 0 -offvalue 1 \
2491            -command [itcl::code $this box $key $name] \
2492            -font "Arial 9"
2493        Rappture::Tooltip::for $inner.box$row $info(description)
2494        blt::table $inner $row,0 $inner.box$row -anchor w
2495        if { !$_settings($this-box-$name) } {
2496            $inner.box$row select
2497        }
2498        incr row
2499    }
2500    blt::table configure $inner r* -resize none
2501    blt::table configure $inner r$row -resize expand
2502    blt::table configure $inner c3 -resize expand
2503    event generate [winfo parent [winfo parent $w]] <Configure>
2504}
2505
2506itcl::body Rappture::FlowvisViewer::particles { tag name } {
2507    set bool $_settings($this-particles-$name)
2508    SendCmd "$tag particles configure {$name} -hide $bool"
2509}
2510
2511itcl::body Rappture::FlowvisViewer::box { tag name } {
2512    set bool $_settings($this-box-$name)
2513    SendCmd "$tag box configure {$name} -hide $bool"
2514}
2515
2516itcl::body Rappture::FlowvisViewer::streams { tag name } {
2517    set bool $_settings($this-streams)
2518    SendCmd "$tag configure -slice $bool"
2519}
2520
2521itcl::body Rappture::FlowvisViewer::arrows { tag name } {
2522    set bool $_settings($this-arrows)
2523    SendCmd "$tag configure -arrows $bool"
2524}
2525
2526# ----------------------------------------------------------------------
2527# USAGE: Slice move x|y|z <newval>
2528#
2529# Called automatically when the user drags the slider to move the
2530# cut plane that slices 3D data.  Gets the current value from the
2531# slider and moves the cut plane to the appropriate point in the
2532# data set.
2533# ----------------------------------------------------------------------
2534itcl::body Rappture::FlowvisViewer::Slice {option args} {
2535    switch -- $option {
2536        move {
2537            if {[llength $args] != 2} {
2538                error "wrong # args: should be \"Slice move x|y|z newval\""
2539            }
2540            set axis [lindex $args 0]
2541            set newval [lindex $args 1]
2542            set newpos [expr {0.01*$newval}]
2543
2544            # show the current value in the readout
2545
2546            set ids [CurrentVolumeIds -cutplanes]
2547            SendCmd "cutplane position $newpos $axis $ids"
2548        }
2549        default {
2550            error "bad option \"$option\": should be axis, move, or volume"
2551        }
2552    }
2553}
2554
2555# ----------------------------------------------------------------------
2556# USAGE: SlicerTip <axis>
2557#
2558# Used internally to generate a tooltip for the x/y/z slicer controls.
2559# Returns a message that includes the current slicer value.
2560# ----------------------------------------------------------------------
2561itcl::body Rappture::FlowvisViewer::SlicerTip {axis} {
2562    set val [$itk_component(${axis}CutScale) get]
2563    return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
2564}
2565
2566itcl::body Rappture::FlowvisViewer::Resize {} {
2567    $_arcball resize $_width $_height
2568    SendCmd "screen size $_width $_height"
2569    set _resizePending 0
2570}
2571
2572itcl::body Rappture::FlowvisViewer::EventuallyResize { w h } {
2573    set _width $w
2574    set _height $h
2575    $_arcball resize $w $h
2576    if { !$_resizePending } {
2577        $_dispatcher event -after 200 !resize
2578        set _resizePending 1
2579    }
2580}
2581
2582itcl::body Rappture::FlowvisViewer::EventuallyResizeLegend {} {
2583    if { !$_resizeLegendPending } {
2584        $_dispatcher event -after 100 !legend
2585        set _resizeLegendPending 1
2586    }
2587}
2588
2589itcl::body Rappture::FlowvisViewer::EventuallyGoto { nSteps } {
2590    set _flow(goto) $nSteps
2591    if { !$_gotoPending } {
2592        $_dispatcher event -after 1000 !goto
2593        set _gotoPending 1
2594    }
2595}
2596
2597#  camera --
2598itcl::body Rappture::FlowvisViewer::camera {option args} {
2599    switch -- $option {
2600        "show" {
2601            puts [array get _view]
2602        }
2603        "set" {
2604            set what [lindex $args 0]
2605            set x $_settings($this-$what)
2606            set code [catch { string is double $x } result]
2607            if { $code != 0 || !$result } {
2608                set _settings($this-$what) $_view($what)
2609                return
2610            }
2611            switch -- $what {
2612                "-xpan" - "-ypan" {
2613                    set _view($what) $_settings(${this}${what})
2614                    PanCamera
2615                }
2616                "-qx" - "-qy" - "-qz" - "-qw" {
2617                    set _view($what) $_settings(${this}${what})
2618                    set q [ViewToQuaternion]
2619                    $_arcball quaternion $q
2620                    SendCmd "camera orient $q"
2621                }
2622                "-zoom" {
2623                    set _view($what) $_settings(${this}${what})
2624                    SendCmd "camera zoom $_view($what)"
2625                }
2626            }
2627        }
2628    }
2629}
2630
2631itcl::body Rappture::FlowvisViewer::SendFlowCmd { dataobj comp nbytes extents } {
2632    set tag "$dataobj-$comp"
2633    if { ![info exists _obj2flow($tag)] } {
2634        SendCmd "flow add $tag"
2635        SendCmd "$tag data follows $nbytes $extents"
2636        return 0
2637    }
2638    set flowobj $_obj2flow($tag)
2639    if { $flowobj == "" } {
2640        puts stderr "no flowobj"
2641        return -1
2642    }
2643    SendCmd "if {\[flow exists $tag\]} {flow delete $tag}"
2644    array set info  [$flowobj hints]
2645    set _settings($this-volume) $info(volume)
2646    set _settings($this-outline) $info(outline)
2647    set _settings($this-arrows) $info(arrows)
2648    set _settings($this-duration) $info(duration)
2649    $itk_component(speed) value $info(speed)
2650    set cmd {}
2651    append cmd "flow add $tag"
2652    append cmd " -position $info(position)"
2653    append cmd " -axis $info(axis)"
2654    append cmd " -volume $info(volume)"
2655    append cmd " -outline $info(outline)"
2656    append cmd " -slice $info(streams)"
2657    append cmd " -arrows $info(arrows)"
2658    SendCmd $cmd
2659    foreach part [$flowobj particles] {
2660        set cmd {}
2661        array unset info
2662        array set info $part
2663        set color [Color2RGB $info(color)]
2664        append cmd "$tag particles add $info(name)"
2665        append cmd " -position $info(position)"
2666        append cmd " -hide $info(hide)"
2667        append cmd " -axis $info(axis)"
2668        append cmd " -color {$color}"
2669        append cmd " -size $info(size)"
2670        SendCmd $cmd
2671    }
2672    foreach box [$flowobj boxes] {
2673        set cmd {}
2674        array unset info
2675        set info(corner1) ""
2676        set info(corner2) ""
2677        array set info $box
2678        if { $info(corner1) == "" || $info(corner2) == "" } {
2679            continue
2680        }
2681        set color [Color2RGB $info(color)]
2682        append cmd "$tag box add $info(name)"
2683        append cmd " -color {$color}"
2684        append cmd " -hide $info(hide)"
2685        append cmd " -linewidth $info(linewidth) "
2686        append cmd " -corner1 {$info(corner1)} "
2687        append cmd " -corner2 {$info(corner2)}"
2688        SendCmd $cmd
2689    }
2690    SendCmd "$tag data follows $nbytes $extents"
2691    return 0
2692}
2693
2694
2695#
2696# flow --
2697#
2698# Called when the user clicks on the stop or play buttons
2699# for flow visualization.
2700#
2701#        $this flow play
2702#        $this flow stop
2703#        $this flow toggle
2704#        $this flow reset
2705#        $this flow pause
2706#        $this flow next
2707#
2708itcl::body Rappture::FlowvisViewer::flow { args } {
2709    set option [lindex $args 0]
2710    switch -- $option {
2711        "goto2" {
2712            puts stderr "actually sending \"flow goto $_flow(goto)\""
2713            SendCmd "flow goto $_flow(goto)"
2714            set _gotoPending 0
2715        }
2716        "goto" {
2717            puts stderr "flow goto to $_settings($this-currenttime)"
2718            # Figure out how many steps to the current time based upon
2719            # the speed and duration.
2720            set current $_settings($this-currenttime)
2721            set speed [$itk_component(speed) value]
2722            set time [str2millisecs $_settings($this-duration)]
2723            $itk_component(dial) configure -max $time
2724            set delay [expr int(round(500.0/$speed))]
2725            set timePerStep [expr {double($time) / $delay}]
2726            set nSteps [expr {int(ceil($current/$timePerStep))}]
2727            EventuallyGoto $nSteps
2728        }
2729        "speed" {
2730            set speed [$itk_component(speed) value]
2731            set _flow(delay) [expr int(round(500.0/$speed))]
2732        }
2733        "duration" {
2734            set max [str2millisecs $_settings($this-duration)]
2735            if { $max < 0 } {
2736                bell
2737                return
2738            }
2739            set _flow(duration) $max
2740            set _settings($this-duration) [millisecs2str $max]
2741            $itk_component(dial) configure -max $max
2742        }
2743        "off" {
2744            set _flow(state) 0
2745            $_dispatcher cancel !play
2746            $itk_component(play) deselect
2747        }
2748        "on" {
2749            flow speed
2750            flow duration
2751            set _flow(state) 1
2752            set _settings($this-currenttime) 0
2753            $itk_component(play) select
2754        }
2755        "stop" {
2756            if { $_flow(state) } {
2757                flow off
2758                flow reset
2759            }
2760        }
2761        "pause" {
2762            if { $_flow(state) } {
2763                flow off
2764            }
2765        }
2766        "play" {
2767            # If the flow is currently off, then restart it.
2768            if { !$_flow(state) } {
2769                flow on
2770                # If we're at the end of the flow, reset the flow.
2771                set _settings($this-currenttime) \
2772                    [expr {$_settings($this-currenttime) + $_flow(delay)}]
2773                if { $_settings($this-currenttime) >= $_flow(duration) } {
2774                    set _settings($this-step) 1
2775                    SendCmd "flow reset"
2776                }
2777                flow next
2778            }
2779        }
2780        "toggle" {
2781            if { $_settings($this-play) } {
2782                flow play
2783            } else {
2784                flow pause
2785            }
2786        }
2787        "reset" {
2788            set _settings($this-currenttime) 0
2789            SendCmd "flow reset"
2790        }
2791        "next" {
2792            if { ![winfo viewable $itk_component(3dview)] } {
2793                flow stop
2794                return
2795            }
2796            set _settings($this-currenttime) \
2797                [expr {$_settings($this-currenttime) + $_flow(delay)}]
2798            if { $_settings($this-currenttime) >= $_flow(duration) } {
2799                if { !$_settings($this-loop) } {
2800                    flow off
2801                    return
2802                }
2803                flow reset
2804            } else {
2805                SendCmd "flow next"
2806            }
2807            $_dispatcher event -after $_flow(delay) !play
2808        }
2809        default {
2810            error "bad option \"$option\": should be play, stop, toggle, or reset."
2811        }
2812    }
2813}
2814
2815itcl::body Rappture::FlowvisViewer::WaitIcon  { option widget } {
2816    switch -- $option {
2817        "start" {
2818            $_dispatcher dispatch $this !waiticon \
2819                "[itcl::code $this WaitIcon "next" $widget] ; list"
2820            set _icon 0
2821            $widget configure -image [Rappture::icon bigroller${_icon}]
2822            $_dispatcher event -after 100 !waiticon
2823        }
2824        "next" {
2825            incr _icon
2826            if { $_icon >= 8 } {
2827                set _icon 0
2828            }
2829            $widget configure -image [Rappture::icon bigroller${_icon}]
2830            $_dispatcher event -after 100 !waiticon
2831        }
2832        "stop" {
2833            $_dispatcher cancel !waiticon
2834        }
2835    }
2836}
2837
2838itcl::body Rappture::FlowvisViewer::GetPngImage  { widget width height } {
2839    set token "print[incr _nextToken]"
2840    set var ::Rappture::FlowvisViewer::_hardcopy($this-$token)
2841    set $var ""
2842
2843    # Setup an automatic timeout procedure.
2844    $_dispatcher dispatch $this !pngtimeout "set $var {} ; list"
2845
2846    set popup .flowvisviewerprint
2847    if {![winfo exists $popup]} {
2848        Rappture::Balloon $popup -title "Generating file..."
2849        set inner [$popup component inner]
2850        label $inner.title -text "Generating hardcopy." -font "Arial 10 bold"
2851        label $inner.please -text "This may take a minute." -font "Arial 10"
2852        label $inner.icon -image [Rappture::icon bigroller0]
2853        button $inner.cancel -text "Cancel" -font "Arial 10 bold" \
2854            -command [list set $var ""]
2855        blt::table $inner \
2856            0,0 $inner.title -cspan 2 \
2857            1,0 $inner.please -anchor w \
2858            1,1 $inner.icon -anchor e  \
2859            2,0 $inner.cancel -cspan 2
2860        blt::table configure $inner r0 -pady 4
2861        blt::table configure $inner r2 -pady 4
2862        bind $inner.cancel <KeyPress-Return> [list $inner.cancel invoke]
2863    } else {
2864        set inner [$popup component inner]
2865    }
2866
2867    $_dispatcher event -after 60000 !pngtimeout
2868    WaitIcon start $inner.icon
2869    grab set $inner
2870    focus $inner.cancel
2871
2872    SendCmd "print $token $width $height"
2873
2874    $popup activate $widget below
2875    update idletasks
2876    update
2877    # We wait here for either
2878    #  1) the png to be delivered or
2879    #  2) timeout or
2880    #  3) user cancels the operation.
2881    tkwait variable $var
2882
2883    # Clean up.
2884    $_dispatcher cancel !pngtimeout
2885    WaitIcon stop $inner.icon
2886    grab release $inner
2887    $popup deactivate
2888    update
2889
2890    if { $_hardcopy($this-$token) != "" } {
2891        return [list .png $_hardcopy($this-$token)]
2892    }
2893    return ""
2894}
2895
2896itcl::body Rappture::FlowvisViewer::GetMovie { widget w h } {
2897    set token "movie[incr _nextToken]"
2898    set var ::Rappture::FlowvisViewer::_hardcopy($this-$token)
2899    set $var ""
2900
2901    # Setup an automatic timeout procedure.
2902    $_dispatcher dispatch $this !movietimeout "set $var {} ; list"
2903    set popup .flowvisviewermovie
2904    if {![winfo exists $popup]} {
2905        Rappture::Balloon $popup -title "Generating movie..."
2906        set inner [$popup component inner]
2907        label $inner.title -text "Generating movie for download" \
2908                -font "Arial 10 bold"
2909        label $inner.please -text "This may take a few minutes." \
2910                -font "Arial 10"
2911        label $inner.icon -image [Rappture::icon bigroller0]
2912        button $inner.cancel -text "Cancel" -font "Arial 10 bold" \
2913            -command [list set $var ""]
2914        blt::table $inner \
2915            0,0 $inner.title -cspan 2 \
2916            1,0 $inner.please -anchor w \
2917            1,1 $inner.icon -anchor e  \
2918            2,0 $inner.cancel -cspan 2
2919        blt::table configure $inner r0 -pady 4
2920        blt::table configure $inner r2 -pady 4
2921        bind $inner.cancel <KeyPress-Return> [list $inner.cancel invoke]
2922    } else {
2923        set inner [$popup component inner]
2924    }
2925    update
2926    # Timeout is set to 10 minutes.
2927    $_dispatcher event -after 600000 !movietimeout
2928    WaitIcon start $inner.icon
2929    grab set $inner
2930    focus $inner.cancel
2931
2932    flow duration
2933    flow speed
2934    set nframes [expr round($_flow(duration) / $_flow(delay))]
2935    set framerate [expr 1000.0 / $_flow(delay)]
2936
2937    # These are specific to MPEG1 video generation
2938    set framerate 25.0
2939    set bitrate 6.0e+6
2940
2941    set start [clock seconds]
2942    SendCmd "flow video $token -width $w -height $h -numframes $nframes "
2943
2944    $popup activate $widget below
2945    update idletasks
2946    update
2947    # We wait here until
2948    #  1. the movie is delivered or
2949    #  2. we've timed out or
2950    #  3. the user has canceled the operation.b
2951    tkwait variable $var
2952
2953    puts stderr "Video generated in [expr [clock seconds] - $start] seconds."
2954
2955    # Clean up.
2956    $_dispatcher cancel !movietimeout
2957    WaitIcon stop $inner.icon
2958    grab release $inner
2959    $popup deactivate
2960    destroy $popup
2961    update
2962
2963    # This will both cancel the movie generation (if it hasn't already
2964    # completed) and reset the flow.
2965    SendCmd "flow reset"
2966    if { $_hardcopy($this-$token) != "" } {
2967        return [list .mpg $_hardcopy($this-$token)]
2968    }
2969    return ""
2970}
2971
2972itcl::body Rappture::FlowvisViewer::str2millisecs { value } {
2973    set parts [split $value :]
2974    set secs 0
2975    set mins 0
2976    if { [llength $parts] == 1 } {
2977        scan [lindex $parts 0] "%d" secs
2978    } else {
2979        scan [lindex $parts 1] "%d" secs
2980        scan [lindex $parts 0] "%d" mins
2981    }
2982    set ms [expr {(($mins * 60) + $secs) * 1000.0}]
2983    if { $ms > 600000.0 } {
2984        set ms 600000.0
2985    }
2986    if { $ms == 0.0 } {
2987        set ms 60000.0
2988    }
2989    return $ms
2990}
2991
2992itcl::body Rappture::FlowvisViewer::millisecs2str { value } {
2993    set min [expr floor($value / 60000.0)]
2994    set sec [expr ($value - ($min*60000.0)) / 1000.0]
2995    return [format %02d:%02d [expr round($min)] [expr round($sec)]]
2996}
2997
2998itcl::body Rappture::FlowvisViewer::SetOrientation { side } {
2999    array set positions {
3000        front "1 0 0 0"
3001        back  "0 0 1 0"
3002        left  "0.707107 0 -0.707107 0"
3003        right "0.707107 0 0.707107 0"
3004        top   "0.707107 -0.707107 0 0"
3005        bottom "0.707107 0.707107 0 0"
3006    }
3007    foreach name { -qw -qx -qy -qz } value $positions($side) {
3008        set _view($name) $value
3009    }
3010    set q [ViewToQuaternion]
3011    $_arcball quaternion $q
3012    SendCmd "camera orient $q"
3013    SendCmd "camera reset"
3014    set _view(-xpan) 0.0
3015    set _view(-ypan) 0.0
3016    set _view(-zoom) 1.0
3017    set _settings($this-xpan) $_view(-xpan)
3018    set _settings($this-ypan) $_view(-ypan)
3019    set _settings($this-zoom) $_view(-zoom)
3020}
Note: See TracBrowser for help on using the repository browser.