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

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

sync with 1.3 branch

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