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

Last change on this file since 5366 was 5366, checked in by ldelgass, 10 years ago

init colormap setting

File size: 100.0 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#  AUTHOR:  Michael McLennan, Purdue University
10#  Copyright (c) 2004-2012  HUBzero Foundation, LLC
11#
12# See the file "license.terms" for information on usage and redistribution of
13# this file, and for a DISCLAIMER OF ALL WARRANTIES.
14# ======================================================================
15package require Itk
16package require BLT
17package require Img
18
19option add *FlowvisViewer.width 5i widgetDefault
20option add *FlowvisViewer*cursor crosshair widgetDefault
21option add *FlowvisViewer.height 4i widgetDefault
22option add *FlowvisViewer.foreground black widgetDefault
23option add *FlowvisViewer.controlBackground gray widgetDefault
24option add *FlowvisViewer.controlDarkBackground #999999 widgetDefault
25option add *FlowvisViewer.plotBackground black widgetDefault
26option add *FlowvisViewer.plotForeground white widgetDefault
27option add *FlowvisViewer.plotOutline gray widgetDefault
28option add *FlowvisViewer.font \
29    -*-helvetica-medium-r-normal-*-12-* widgetDefault
30
31# must use this name -- plugs into Rappture::resources::load
32proc FlowvisViewer_init_resources {} {
33    Rappture::resources::register \
34        nanovis_server Rappture::FlowvisViewer::SetServerList
35}
36
37itcl::class Rappture::FlowvisViewer {
38    inherit Rappture::VisViewer
39
40    itk_option define -plotforeground plotForeground Foreground ""
41    itk_option define -plotbackground plotBackground Background ""
42    itk_option define -plotoutline plotOutline PlotOutline ""
43
44    constructor { hostlist args } {
45        Rappture::VisViewer::constructor $hostlist
46    } {
47        # defined below
48    }
49    destructor {
50        # defined below
51    }
52    public proc SetServerList { namelist } {
53        Rappture::VisViewer::SetServerList "nanovis" $namelist
54    }
55    public method add {dataobj {settings ""}}
56    public method camera {option args}
57    public method delete {args}
58    public method disconnect {}
59    public method download {option args}
60    public method flow {option}
61    public method get {args}
62    public method isconnected {}
63    public method limits { cname }
64    public method overMarker { m x }
65    public method parameters {title args} {
66        # do nothing
67    }
68    public method removeDuplicateMarker { m x }
69    public method scale {args}
70    public method updateTransferFunctions {}
71
72    # The following methods are only used by this class.
73    private method AddIsoMarker { x y }
74    private method AdjustSetting {what {value ""}}
75    private method BuildCameraTab {}
76    private method BuildCutplanesTab {}
77    private method BuildViewTab {}
78    private method BuildVolumeComponents {}
79    private method BuildVolumeTab {}
80    private method ComputeTransferFunction { tf }
81    private method Connect {}
82    private method CurrentVolumeIds {{what -all}}
83    private method Disconnect {}
84    private method DrawLegend { tf }
85    private method EventuallyResize { w h }
86    private method EventuallyGoto { nSteps }
87    private method EventuallyResizeLegend { }
88    private method GetDatasetsWithComponent { cname }
89    private method GetFlowInfo { widget }
90    private method GetMovie { widget width height }
91    private method GetPngImage { widget width height }
92    private method InitSettings { args }
93    private method NameTransferFunction { dataobj comp }
94    private method Pan {option x y}
95    private method PanCamera {}
96    private method ParseLevelsOption { tf levels }
97    private method ParseMarkersOption { tf markers }
98    private method QuaternionToView { q } {
99        foreach { _view(-qw) _view(-qx) _view(-qy) _view(-qz) } $q break
100    }
101    private method Rebuild {}
102    private method ReceiveData { args }
103    private method ReceiveImage { args }
104    private method ReceiveLegend { tf vmin vmax size }
105    private method Resize {}
106    private method ResizeLegend {}
107    private method Rotate {option x y}
108    private method SendFlowCmd { dataobj comp nbytes extents }
109    private method SendTransferFunctions {}
110    private method SetOrientation { side }
111    private method Slice {option args}
112    private method SlicerTip {axis}
113    private method ViewToQuaternion {} {
114        return [list $_view(-qw) $_view(-qx) $_view(-qy) $_view(-qz)]
115    }
116    private method WaitIcon { option widget }
117    private method Zoom {option}
118    private method arrows { tag name }
119    private method box { tag name }
120    private method millisecs2str { value }
121    private method particles { tag name }
122    private method str2millisecs { value }
123    private method streams { tag name }
124
125    private variable _arcball ""
126    private variable _dlist ""         ;# list of data objects
127    private variable _obj2ovride       ;# maps dataobj => style override
128    private variable _serverDatasets   ;# maps dataobj-component to volume ID
129                                        # in the server
130    private variable _recvdDatasets    ;# list of data objs to send to server
131    private variable _dataset2style    ;# maps dataobj-component to transfunc
132    private variable _style2datasets   ;# maps tf back to list of
133                                        # dataobj-components using the tf.
134    private variable _dataset2flow     ;# Maps dataobj-component to a flow.
135
136    private variable _reset 1          ;# Connection to server has been reset
137    private variable _click            ;# info used for rotate operations
138    private variable _limits           ;# Autoscale min/max for all axes
139    private variable _view             ;# View params for 3D view
140    private variable _isomarkers       ;# array of isosurface level values 0..1
141    private variable _settings
142    private variable _activeTf ""      ;# The currently active transfer function
143    private variable _first ""         ;# This is the topmost volume.
144    private variable _volcomponents    ;# Array of components found
145    private variable _componentsList   ;# Array of components found
146    private variable _nextToken 0
147    private variable _icon 0
148    private variable _flow
149    private variable _width 0
150    private variable _height 0
151    private variable _resizePending 0
152    private variable _resizeLegendPending 0
153    private variable _gotoPending 0
154
155    private common _downloadPopup      ;# download options from popup
156    private common _hardcopy
157}
158
159itk::usual FlowvisViewer {
160    keep -background -foreground -cursor -font
161    keep -plotbackground -plotforeground
162}
163
164# ----------------------------------------------------------------------
165# CONSTRUCTOR
166# ----------------------------------------------------------------------
167itcl::body Rappture::FlowvisViewer::constructor { hostlist args } {
168    set _serverType "nanovis"
169
170    # Draw legend event
171    $_dispatcher register !legend
172    $_dispatcher dispatch $this !legend "[itcl::code $this ResizeLegend]; list"
173
174    # Send transferfunctions event
175    $_dispatcher register !send_transfunc
176    $_dispatcher dispatch $this !send_transfunc \
177        "[itcl::code $this SendTransferFunctions]; list"
178
179    # Rebuild event.
180    $_dispatcher register !rebuild
181    $_dispatcher dispatch $this !rebuild "[itcl::code $this Rebuild]; list"
182
183    # Resize event.
184    $_dispatcher register !resize
185    $_dispatcher dispatch $this !resize "[itcl::code $this Resize]; list"
186
187    $_dispatcher register !play
188    $_dispatcher dispatch $this !play "[itcl::code $this flow next]; list"
189
190    $_dispatcher register !goto
191    $_dispatcher dispatch $this !goto "[itcl::code $this flow goto2]; list"
192
193    $_dispatcher register !movietimeout
194    $_dispatcher register !waiticon
195
196    set _flow(state) 0
197
198    array set _downloadPopup {
199        format draft
200    }
201    #
202    # Populate parser with commands handle incoming requests
203    #
204    $_parser alias image [itcl::code $this ReceiveImage]
205    $_parser alias legend [itcl::code $this ReceiveLegend]
206    $_parser alias data [itcl::code $this ReceiveData]
207
208    # Initialize the view to some default parameters.
209    array set _view {
210        -qw      0.853553
211        -qx      -0.353553
212        -qy      0.353553
213        -qz      0.146447
214        -xpan    0
215        -ypan    0
216        -zoom    1.0
217    }
218    set _arcball [blt::arcball create 100 100]
219    $_arcball quaternion [ViewToQuaternion]
220
221    set _limits(v) [list 0.0 1.0]
222    set _reset 1
223
224    array set _settings [subst {
225        -ambient                60
226        -arrows                 0
227        -axes                   0
228        -colormap               BCGYR
229        -currenttime            0
230        -cutplanesVisible       0
231        -diffuse                40
232        -duration               1:00
233        -grid                   0
234        -isosurface             0
235        -legend                 1
236        -lic                    1
237        -light2side             1
238        -loop                   0
239        -opacity                50
240        -outline                1
241        -particles              1
242        -play                   0
243        -qw                     $_view(-qw)
244        -qx                     $_view(-qx)
245        -qy                     $_view(-qy)
246        -qz                     $_view(-qz)
247        -specularLevel          30
248        -specularExponent       90
249        -speed                  500
250        -step                   0
251        -streams                0
252        -thickness              350
253        -volume                 1
254        -xcutplane              1
255        -xcutposition           0
256        -xpan                   $_view(-xpan)
257        -ycutplane              1
258        -ycutposition           0
259        -ypan                   $_view(-ypan)
260        -zcutplane              1
261        -zcutposition           0
262        -zoom                   $_view(-zoom)
263    }]
264
265    itk_component add 3dview {
266        label $itk_component(plotarea).view -image $_image(plot) \
267            -highlightthickness 0 -borderwidth 0
268    } {
269        usual
270        ignore -highlightthickness -borderwidth  -background
271    }
272    bind $itk_component(3dview) <Control-F1> [itcl::code $this ToggleConsole]
273
274    set f [$itk_component(main) component controls]
275    itk_component add reset {
276        button $f.reset -borderwidth 1 -padx 1 -pady 1 \
277            -highlightthickness 0 \
278            -image [Rappture::icon reset-view] \
279            -command [itcl::code $this Zoom reset]
280    } {
281        usual
282        ignore -highlightthickness
283    }
284    pack $itk_component(reset) -side top -padx 2 -pady 2
285    Rappture::Tooltip::for $itk_component(reset) "Reset the view to the default zoom level"
286
287    itk_component add zoomin {
288        button $f.zin -borderwidth 1 -padx 1 -pady 1 \
289            -highlightthickness 0 \
290            -image [Rappture::icon zoom-in] \
291            -command [itcl::code $this Zoom in]
292    } {
293        usual
294        ignore -highlightthickness
295    }
296    pack $itk_component(zoomin) -side top -padx 2 -pady 2
297    Rappture::Tooltip::for $itk_component(zoomin) "Zoom in"
298
299    itk_component add zoomout {
300        button $f.zout -borderwidth 1 -padx 1 -pady 1 \
301            -highlightthickness 0 \
302            -image [Rappture::icon zoom-out] \
303            -command [itcl::code $this Zoom out]
304    } {
305        usual
306        ignore -highlightthickness
307    }
308    pack $itk_component(zoomout) -side top -padx 2 -pady 2
309    Rappture::Tooltip::for $itk_component(zoomout) "Zoom out"
310
311    itk_component add volume {
312        Rappture::PushButton $f.volume \
313            -onimage [Rappture::icon volume-on] \
314            -offimage [Rappture::icon volume-off] \
315            -command [itcl::code $this AdjustSetting -volume] \
316            -variable [itcl::scope _settings(-volume)]
317    }
318    $itk_component(volume) select
319    Rappture::Tooltip::for $itk_component(volume) \
320        "Toggle the volume cloud on/off"
321    pack $itk_component(volume) -padx 2 -pady 2
322
323    itk_component add cutplane {
324        Rappture::PushButton $f.cutplane \
325            -onimage [Rappture::icon cutbutton] \
326            -offimage [Rappture::icon cutbutton] \
327            -variable [itcl::scope _settings(-cutplanesVisible)] \
328            -command [itcl::code $this AdjustSetting -cutplanesVisible]
329    }
330    Rappture::Tooltip::for $itk_component(cutplane) \
331        "Show/Hide cutplanes"
332    pack $itk_component(cutplane) -padx 2 -pady 2
333
334    if { [catch {
335        BuildViewTab
336        BuildVolumeTab
337        BuildCutplanesTab
338        BuildCameraTab
339    } errs] != 0 } {
340        global errorInfo
341        puts stderr "errs=$errs errorInfo=$errorInfo"
342    }
343
344    bind $itk_component(3dview) <Configure> \
345        [itcl::code $this EventuallyResize %w %h]
346
347    # Legend
348    set _image(legend) [image create photo]
349    itk_component add legend {
350        canvas $itk_component(plotarea).legend -height 50 -highlightthickness 0
351    } {
352        usual
353        ignore -highlightthickness
354        rename -background -plotbackground plotBackground Background
355    }
356    bind $itk_component(legend) <Configure> \
357        [itcl::code $this EventuallyResizeLegend]
358
359    # Hack around the Tk panewindow.  The problem is that the requested
360    # size of the 3d view isn't set until an image is retrieved from
361    # the server.  So the panewindow uses the tiny size.
362    set w 10000
363    pack forget $itk_component(3dview)
364    blt::table $itk_component(plotarea) \
365        0,0 $itk_component(3dview) -fill both -reqwidth $w \
366        1,0 $itk_component(legend) -fill x
367    blt::table configure $itk_component(plotarea) r1 -resize none
368    # Create flow controls...
369
370    itk_component add flowcontrols {
371        frame $itk_interior.flowcontrols
372    } {
373        usual
374        rename -background -controlbackground controlBackground Background
375    }
376    pack forget $itk_component(main)
377    blt::table $itk_interior \
378        0,0 $itk_component(main) -fill both  \
379        1,0 $itk_component(flowcontrols) -fill x
380    blt::table configure $itk_interior r1 -resize none
381
382    # Rewind
383    itk_component add rewind {
384        button $itk_component(flowcontrols).reset \
385            -borderwidth 1 -padx 1 -pady 1 \
386            -image [Rappture::icon flow-rewind] \
387            -command [itcl::code $this flow reset]
388    } {
389        usual
390        ignore -borderwidth
391        rename -highlightbackground -controlbackground controlBackground \
392            Background
393    }
394    Rappture::Tooltip::for $itk_component(rewind) \
395        "Rewind flow"
396
397    # Stop
398    itk_component add stop {
399        button $itk_component(flowcontrols).stop \
400            -borderwidth 1 -padx 1 -pady 1 \
401            -image [Rappture::icon flow-stop] \
402            -command [itcl::code $this flow stop]
403    } {
404        usual
405        ignore -borderwidth
406        rename -highlightbackground -controlbackground controlBackground \
407            Background
408    }
409    Rappture::Tooltip::for $itk_component(stop) \
410        "Stop flow"
411
412    # Play
413    itk_component add play {
414        Rappture::PushButton $itk_component(flowcontrols).play \
415            -onimage [Rappture::icon flow-pause] \
416            -offimage [Rappture::icon flow-play] \
417            -variable [itcl::scope _settings(-play)] \
418            -command [itcl::code $this flow toggle]
419    }
420    set fg [option get $itk_component(hull) font Font]
421    Rappture::Tooltip::for $itk_component(play) \
422        "Play/Pause flow"
423
424    # Loop
425    itk_component add loop {
426        Rappture::PushButton $itk_component(flowcontrols).loop \
427            -onimage [Rappture::icon flow-loop] \
428            -offimage [Rappture::icon flow-loop] \
429            -variable [itcl::scope _settings(-loop)]
430    }
431    Rappture::Tooltip::for $itk_component(loop) \
432        "Play continuously"
433
434    itk_component add dial {
435        Rappture::Flowdial $itk_component(flowcontrols).dial \
436            -length 10 -valuewidth 0 -valuepadding 0 -padding 6 \
437            -linecolor "" -activelinecolor "" \
438            -min 0.0 -max 1.0 \
439            -variable [itcl::scope _settings(-currenttime)] \
440            -knobimage [Rappture::icon knob2] -knobposition center@middle
441    } {
442        usual
443        ignore -dialprogresscolor
444        rename -background -controlbackground controlBackground Background
445    }
446    $itk_component(dial) current 0.0
447    bind $itk_component(dial) <<Value>> [itcl::code $this flow goto]
448    # Duration
449    itk_component add duration {
450        entry $itk_component(flowcontrols).duration \
451            -textvariable [itcl::scope _settings(-duration)] \
452            -bg white -width 6 -font "arial 9"
453    } {
454        usual
455        ignore -highlightthickness -background
456    }
457    bind $itk_component(duration) <Return> [itcl::code $this flow duration]
458    bind $itk_component(duration) <KP_Enter> [itcl::code $this flow duration]
459    bind $itk_component(duration) <Tab> [itcl::code $this flow duration]
460    Rappture::Tooltip::for $itk_component(duration) \
461        "Set duration of flow (format is min:sec)"
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
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(-thickness)
967    # Scale values between 0.00001 and 0.01000
968    set thickness [expr {double($value) * 0.0001}]
969    set _settings($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    # Turn off cutplanes for all volumes
1192    foreach axis {x y z} {
1193        SendCmd "cutplane state 0 $axis"
1194    }
1195
1196    # Reset the camera and other view parameters
1197    InitSettings -light2side \
1198        -ambient -diffuse -specularLevel -specularExponent \
1199        -opacity -isosurface -grid -axes -volume -outline \
1200        -cutplanesVisible -xcutplane -ycutplane -zcutplane
1201
1202    # nothing to send -- activate the proper volume
1203    if {"" != $_first} {
1204        set axis [$_first hints updir]
1205        if {"" != $axis} {
1206            SendCmd "up $axis"
1207        }
1208        set location [$_first hints camera]
1209        if { $location != "" } {
1210            array set _view $location
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    # sync the state of slicers
1250    set vols [CurrentVolumeIds -cutplanes]
1251    foreach axis {x y z} {
1252        set pos [expr {0.01*$_settings(-${axis}cutposition)}]
1253        SendCmd "cutplane position $pos $axis $vols"
1254    }
1255    SendCmd "volume data state $_settings(-volume)"
1256    EventuallyResizeLegend
1257
1258    # Actually write the commands to the server socket.  If it fails, we don't
1259    # care.  We're finished here.
1260    blt::busy hold $itk_component(hull)
1261    StopBufferingCommands
1262    blt::busy release $itk_component(hull)
1263    set _reset 0
1264}
1265
1266# ----------------------------------------------------------------------
1267# USAGE: CurrentVolumeIds ?-cutplanes?
1268#
1269# Returns a list of volume server IDs for the current volume being
1270# displayed.  This is normally a single ID, but it might be a list
1271# of IDs if the current data object has multiple components.
1272# ----------------------------------------------------------------------
1273itcl::body Rappture::FlowvisViewer::CurrentVolumeIds {{what -all}} {
1274    return ""
1275    if { $_first == "" } {
1276        return
1277    }
1278    foreach key [array names _serverDatasets *-*] {
1279        if {[string match $_first-* $key]} {
1280            array set style {
1281                -cutplanes 1
1282            }
1283            foreach {dataobj comp} [split $key -] break
1284            array set style [lindex [$dataobj components -style $comp] 0]
1285            if {$what != "-cutplanes" || $style(-cutplanes)} {
1286                lappend rlist $_serverDatasets($key)
1287            }
1288        }
1289    }
1290    return $rlist
1291}
1292
1293# ----------------------------------------------------------------------
1294# USAGE: Zoom in
1295# USAGE: Zoom out
1296# USAGE: Zoom reset
1297#
1298# Called automatically when the user clicks on one of the zoom
1299# controls for this widget.  Changes the zoom for the current view.
1300# ----------------------------------------------------------------------
1301itcl::body Rappture::FlowvisViewer::Zoom {option} {
1302    switch -- $option {
1303        "in" {
1304            set _view(-zoom) [expr {$_view(-zoom)*1.25}]
1305            set _settings(-zoom) $_view(-zoom)
1306            SendCmd "camera zoom $_view(-zoom)"
1307        }
1308        "out" {
1309            set _view(-zoom) [expr {$_view(-zoom)*0.8}]
1310            set _settings(-zoom) $_view(-zoom)
1311            SendCmd "camera zoom $_view(-zoom)"
1312        }
1313        "reset" {
1314            array set _view {
1315                -qw      0.853553
1316                -qx      -0.353553
1317                -qy      0.353553
1318                -qz      0.146447
1319                -xpan    0
1320                -ypan    0
1321                -zoom    1.0
1322            }
1323            if { $_first != "" } {
1324                set location [$_first hints camera]
1325                if { $location != "" } {
1326                    array set _view $location
1327                }
1328            }
1329            set q [ViewToQuaternion]
1330            $_arcball quaternion $q
1331            SendCmd "camera orient $q"
1332            SendCmd "camera reset"
1333            set _settings(-qw)    $_view(-qw)
1334            set _settings(-qx)    $_view(-qx)
1335            set _settings(-qy)    $_view(-qy)
1336            set _settings(-qz)    $_view(-qz)
1337            set _settings(-xpan)  $_view(-xpan)
1338            set _settings(-ypan)  $_view(-ypan)
1339            set _settings(-zoom)  $_view(-zoom)
1340        }
1341    }
1342}
1343
1344itcl::body Rappture::FlowvisViewer::PanCamera {} {
1345    set x $_view(-xpan)
1346    set y $_view(-ypan)
1347    SendCmd "camera pan $x $y"
1348}
1349
1350# ----------------------------------------------------------------------
1351# USAGE: Rotate click <x> <y>
1352# USAGE: Rotate drag <x> <y>
1353# USAGE: Rotate release <x> <y>
1354#
1355# Called automatically when the user clicks/drags/releases in the
1356# plot area.  Moves the plot according to the user's actions.
1357# ----------------------------------------------------------------------
1358itcl::body Rappture::FlowvisViewer::Rotate {option x y} {
1359    switch -- $option {
1360        click {
1361            $itk_component(3dview) configure -cursor fleur
1362            set _click(x) $x
1363            set _click(y) $y
1364        }
1365        drag {
1366            if {[array size _click] == 0} {
1367                Rotate click $x $y
1368            } else {
1369                set w [winfo width $itk_component(3dview)]
1370                set h [winfo height $itk_component(3dview)]
1371                if {$w <= 0 || $h <= 0} {
1372                    return
1373                }
1374
1375                if {[catch {
1376                    # this fails sometimes for no apparent reason
1377                    set dx [expr {double($x-$_click(x))/$w}]
1378                    set dy [expr {double($y-$_click(y))/$h}]
1379                }]} {
1380                    return
1381                }
1382
1383                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1384                QuaternionToView $q
1385                set _settings(-qw) $_view(-qw)
1386                set _settings(-qx) $_view(-qx)
1387                set _settings(-qy) $_view(-qy)
1388                set _settings(-qz) $_view(-qz)
1389                SendCmd "camera orient $q"
1390
1391                set _click(x) $x
1392                set _click(y) $y
1393            }
1394        }
1395        release {
1396            Rotate drag $x $y
1397            $itk_component(3dview) configure -cursor ""
1398            catch {unset _click}
1399        }
1400        default {
1401            error "bad option \"$option\": should be click, drag, release"
1402        }
1403    }
1404}
1405
1406# ----------------------------------------------------------------------
1407# USAGE: $this Pan click x y
1408#        $this Pan drag x y
1409#        $this Pan release x y
1410#
1411# Called automatically when the user clicks on one of the zoom
1412# controls for this widget.  Changes the zoom for the current view.
1413# ----------------------------------------------------------------------
1414itcl::body Rappture::FlowvisViewer::Pan {option x y} {
1415    # Experimental stuff
1416    set w [winfo width $itk_component(3dview)]
1417    set h [winfo height $itk_component(3dview)]
1418    if { $option == "set" } {
1419        set x [expr $x / double($w)]
1420        set y [expr $y / double($h)]
1421        set _view(-xpan) [expr $_view(-xpan) + $x]
1422        set _view(-ypan) [expr $_view(-ypan) + $y]
1423        PanCamera
1424        set _settings(-xpan) $_view(-xpan)
1425        set _settings(-ypan) $_view(-ypan)
1426        return
1427    }
1428    if { $option == "click" } {
1429        set _click(x) $x
1430        set _click(y) $y
1431        $itk_component(3dview) configure -cursor hand1
1432    }
1433    if { $option == "drag" || $option == "release" } {
1434        set dx [expr ($_click(x) - $x)/double($w)]
1435        set dy [expr ($_click(y) - $y)/double($h)]
1436        set _click(x) $x
1437        set _click(y) $y
1438        set _view(-xpan) [expr $_view(-xpan) - $dx]
1439        set _view(-ypan) [expr $_view(-ypan) - $dy]
1440        PanCamera
1441        set _settings(-xpan) $_view(-xpan)
1442        set _settings(-ypan) $_view(-ypan)
1443    }
1444    if { $option == "release" } {
1445        $itk_component(3dview) configure -cursor ""
1446    }
1447}
1448
1449# ----------------------------------------------------------------------
1450# USAGE: InitSettings <what> ?<value>?
1451#
1452# Used internally to update rendering settings whenever parameters
1453# change in the popup settings panel.  Sends the new settings off
1454# to the back end.
1455# ----------------------------------------------------------------------
1456itcl::body Rappture::FlowvisViewer::InitSettings { args } {
1457    foreach arg $args {
1458        AdjustSetting $arg
1459    }
1460}
1461
1462# ----------------------------------------------------------------------
1463# USAGE: AdjustSetting <what> ?<value>?
1464#
1465# Used internally to update rendering settings whenever parameters
1466# change in the popup settings panel.  Sends the new settings off
1467# to the back end.
1468# ----------------------------------------------------------------------
1469itcl::body Rappture::FlowvisViewer::AdjustSetting {what {value ""}} {
1470    switch -- $what {
1471        "-colormap" {
1472            set color [$itk_component(colormap) value]
1473            set _settings($what) $color
1474            #ResetColormap $color
1475        }
1476        "-ambient" {
1477            if { $_first != "" } {
1478                set comp [lindex [$_first components] 0]
1479                set tag $_first-$comp
1480                set val $_settings($what)
1481                set val [expr {0.01*$val}]
1482                SendCmd "$tag configure -ambient $val"
1483            }
1484        }
1485        "-diffuse" {
1486            if { $_first != "" } {
1487                set comp [lindex [$_first components] 0]
1488                set tag $_first-$comp
1489                set val $_settings($what)
1490                set val [expr {0.01*$val}]
1491                SendCmd "$tag configure -diffuse $val"
1492            }
1493        }
1494        "-specularLevel" {
1495            if { $_first != "" } {
1496                set comp [lindex [$_first components] 0]
1497                set tag $_first-$comp
1498                set val $_settings($what)
1499                set val [expr {0.01*$val}]
1500                SendCmd "$tag configure -specularLevel $val"
1501            }
1502        }
1503        "-specularExponent" {
1504            if { $_first != "" } {
1505                set comp [lindex [$_first components] 0]
1506                set tag $_first-$comp
1507                set val $_settings($what)
1508                SendCmd "$tag configure -specularExp $val"
1509            }
1510        }
1511        "-light2side" {
1512            if { $_first != "" } {
1513                set comp [lindex [$_first components] 0]
1514                set tag $_first-$comp
1515                set val $_settings($what)
1516                SendCmd "$tag configure -light2side $val"
1517            }
1518        }
1519        "-opacity" {
1520            if { $_first != "" } {
1521                set comp [lindex [$_first components] 0]
1522                set tag $_first-$comp
1523                set opacity [expr { 0.01 * double($_settings($what)) }]
1524                SendCmd "$tag configure -opacity $opacity"
1525            }
1526        }
1527        "-thickness" {
1528            if { $_first != "" && $_activeTf != "" } {
1529                set val $_settings($what)
1530                # Scale values between 0.00001 and 0.01000
1531                set sval [expr {0.0001*double($val)}]
1532                set tf $_activeTf
1533                set _settings($tf${what}) $sval
1534                updateTransferFunctions
1535            }
1536        }
1537        "-outline" {
1538            if { $_first != "" } {
1539                set comp [lindex [$_first components] 0]
1540                set tag $_first-$comp
1541                SendCmd "$tag configure -outline $_settings($what)"
1542            }
1543        }
1544        "-isosurface" {
1545            if { [isconnected] } {
1546                SendCmd "volume shading isosurface $_settings($what)"
1547            }
1548        }
1549        "-grid" {
1550            if { [isconnected] } {
1551                SendCmd "grid visible $_settings($what)"
1552            }
1553        }
1554        "-axes" {
1555            if { [isconnected] } {
1556                SendCmd "axis visible $_settings($what)"
1557            }
1558        }
1559        "-legend" {
1560            if { $_settings($what) } {
1561                blt::table $itk_component(plotarea) \
1562                    0,0 $itk_component(3dview) -fill both \
1563                    1,0 $itk_component(legend) -fill x
1564                blt::table configure $itk_component(plotarea) r1 -resize none
1565            } else {
1566                blt::table forget $itk_component(legend)
1567            }
1568        }
1569        "-volume" {
1570            if { $_first != "" } {
1571                set comp [lindex [$_first components] 0]
1572                set tag $_first-$comp
1573                SendCmd "$tag configure -volume $_settings($what)"
1574            }
1575        }
1576        "-cutplanesVisible" {
1577            set bool $_settings($what)
1578            set datasets [CurrentVolumeIds -cutplanes]
1579            set tag [lindex $datasets 0]
1580            SendCmd "cutplane visible $bool $tag"
1581        }
1582        "-xcutplane" - "-ycutplane" - "-zcutplane" {
1583            set axis [string range $what 1 1]
1584            set bool $_settings($what)
1585            if { [isconnected] } {
1586                set vols [CurrentVolumeIds -cutplanes]
1587                SendCmd "cutplane state $bool $axis $vols"
1588            }
1589            if { $bool } {
1590                $itk_component(${axis}CutScale) configure -state normal \
1591                    -troughcolor white
1592            } else {
1593                $itk_component(${axis}CutScale) configure -state disabled \
1594                    -troughcolor grey82
1595            }
1596        }
1597        default {
1598            error "don't know how to fix $what"
1599        }
1600    }
1601}
1602
1603# ----------------------------------------------------------------------
1604# USAGE: ResizeLegend
1605#
1606# Used internally to update the legend area whenever it changes size
1607# or when the field changes.  Asks the server to send a new legend
1608# for the current field.
1609# ----------------------------------------------------------------------
1610itcl::body Rappture::FlowvisViewer::ResizeLegend {} {
1611    set _resizeLegendPending 0
1612    set lineht [font metrics $itk_option(-font) -linespace]
1613    set w [expr {$_width-20}]
1614    set h [expr {[winfo height $itk_component(legend)]-20-$lineht}]
1615
1616    if { $_first == "" } {
1617        return
1618    }
1619    set comp [lindex [$_first components] 0]
1620    set tag $_first-$comp
1621    #set _activeTf [lindex $_dataset2style($tag) 0]
1622    if {$w > 0 && $h > 0 && "" != $_activeTf} {
1623        #SendCmd "legend $_activeTf $w $h"
1624        SendCmd "$tag legend $w $h"
1625    } else {
1626    # Can't do this as this will remove the items associated with the
1627    # isomarkers.
1628
1629    #$itk_component(legend) delete all
1630    }
1631}
1632
1633#
1634# NameTransferFunction --
1635#
1636#       Creates a transfer function name based on the <style> settings in the
1637#       library run.xml file. This placeholder will be used later to create
1638#       and send the actual transfer function once the data info has been sent
1639#       to us by the render server. [We won't know the volume limits until the
1640#       server parses the 3D data and sends back the limits via ReceiveData.]
1641#
1642#       FIXME: The current way we generate transfer-function names completely
1643#              ignores the -markers option.  The problem is that we are forced
1644#              to compute the name from an increasing complex set of values:
1645#              color, levels, marker, opacity.  I think we're stuck doing it
1646#              now.
1647#
1648itcl::body Rappture::FlowvisViewer::NameTransferFunction { dataobj cname } {
1649    array set style {
1650        -color BCGYR
1651        -levels 6
1652        -opacity 0.5
1653    }
1654    array set style [lindex [$dataobj components -style $cname] 0]
1655    set _settings(-opacity) [expr $style(-opacity) * 100]
1656    set _dataset2style($dataobj-$cname) $cname
1657    lappend _style2datasets($cname) $dataobj $cname
1658    return $cname
1659}
1660
1661#
1662# ComputeTransferFunction --
1663#
1664#   Computes and sends the transfer function to the render server.  It's
1665#   assumed that the volume data limits are known and that the global
1666#   transfer-functions slider values have be setup.  Both parts are
1667#   needed to compute the relative value (location) of the marker, and
1668#   the alpha map of the transfer function.
1669#
1670itcl::body Rappture::FlowvisViewer::ComputeTransferFunction { tf } {
1671    array set style {
1672        -color BCGYR
1673        -levels 6
1674        -opacity 0.5
1675    }
1676    set dataobj ""; set comp ""
1677    foreach {dataobj comp} $_style2datasets($tf) break
1678    if { $dataobj == "" } {
1679        return 0
1680    }
1681    array set style [lindex [$dataobj components -style $comp] 0]
1682
1683    # We have to parse the style attributes for a volume using this
1684    # transfer-function *once*.  This sets up the initial isomarkers for the
1685    # transfer function.  The user may add/delete markers, so we have to
1686    # maintain a list of markers for each transfer-function.  We use the one
1687    # of the volumes (the first in the list) using the transfer-function as a
1688    # reference.
1689    #
1690    # FIXME: The current way we generate transfer-function names completely
1691    #        ignores the -markers option.  The problem is that we are forced
1692    #        to compute the name from an increasing complex set of values:
1693    #        color, levels, marker, opacity.  I think the cow's out of the
1694    #        barn on this one.
1695
1696    if { ![info exists _isomarkers($tf)] } {
1697        # Have to defer creation of isomarkers until we have data limits
1698        if { [info exists style(-markers)] &&
1699             [llength $style(-markers)] > 0  } {
1700            ParseMarkersOption $tf $style(-markers)
1701        } else {
1702            ParseLevelsOption $tf $style(-levels)
1703        }
1704    }
1705    if { [info exists style(-nonuniformcolors)] } {
1706        foreach { value color } $style(-nonuniformcolors) {
1707            append cmap "$value [Color2RGB $color] "
1708        }
1709    } else {
1710        set cmap [ColorsToColormap $style(-color)]
1711    }
1712
1713    if { ![info exists _settings(-opacity)] } {
1714        set _settings(-opacity) [expr $style(-opacity) * 100]
1715    }
1716
1717    # Transfer function should be normalized with [0,1] range
1718    # The volume shading opacity setting is used to scale opacity
1719    # in the volume shader.
1720    set max 1.0
1721
1722    set isovalues {}
1723    foreach m $_isomarkers($tf) {
1724        lappend isovalues [$m relval]
1725    }
1726    # Sort the isovalues
1727    set isovalues [lsort -real $isovalues]
1728
1729    set tag $tf
1730    if { ![info exists _settings($tag-thickness)]} {
1731        set _settings($tag-thickness) 0.005
1732    }
1733    set delta $_settings($tag-thickness)
1734
1735    set first [lindex $isovalues 0]
1736    set last [lindex $isovalues end]
1737    set amap ""
1738    if { $first == "" || $first != 0.0 } {
1739        lappend amap 0.0 0.0
1740    }
1741    foreach x $isovalues {
1742        set x1 [expr {$x-$delta-0.00001}]
1743        set x2 [expr {$x-$delta}]
1744        set x3 [expr {$x+$delta}]
1745        set x4 [expr {$x+$delta+0.00001}]
1746        if { $x1 < 0.0 } {
1747            set x1 0.0
1748        } elseif { $x1 > 1.0 } {
1749            set x1 1.0
1750        }
1751        if { $x2 < 0.0 } {
1752            set x2 0.0
1753        } elseif { $x2 > 1.0 } {
1754            set x2 1.0
1755        }
1756        if { $x3 < 0.0 } {
1757            set x3 0.0
1758        } elseif { $x3 > 1.0 } {
1759            set x3 1.0
1760        }
1761        if { $x4 < 0.0 } {
1762            set x4 0.0
1763        } elseif { $x4 > 1.0 } {
1764            set x4 1.0
1765        }
1766        # add spikes in the middle
1767        lappend amap $x1 0.0
1768        lappend amap $x2 $max
1769        lappend amap $x3 $max
1770        lappend amap $x4 0.0
1771    }
1772    if { $last == "" || $last != 1.0 } {
1773        lappend amap 1.0 0.0
1774    }
1775    SendCmd "transfunc define $tf { $cmap } { $amap }"
1776    return [SendCmd "$dataobj-$comp configure -transferfunction $tf"]
1777}
1778
1779# ----------------------------------------------------------------------
1780# CONFIGURATION OPTION: -plotbackground
1781# ----------------------------------------------------------------------
1782itcl::configbody Rappture::FlowvisViewer::plotbackground {
1783    if { [isconnected] } {
1784        set color $itk_option(-plotbackground)
1785        set rgb [Color2RGB $color]
1786        SendCmd "screen bgcolor $rgb"
1787        $itk_component(legend) configure -background $color
1788    }
1789}
1790
1791# ----------------------------------------------------------------------
1792# CONFIGURATION OPTION: -plotforeground
1793# ----------------------------------------------------------------------
1794itcl::configbody Rappture::FlowvisViewer::plotforeground {
1795    if { [isconnected] } {
1796        set color $itk_option(-plotforeground)
1797        set rgb [Color2RGB $color]
1798        SendCmd "volume outline color $rgb"
1799        SendCmd "grid axiscolor $rgb"
1800        SendCmd "grid linecolor $rgb"
1801        $itk_component(legend) itemconfigure labels -fill $color
1802        $itk_component(legend) itemconfigure limits -fill $color
1803    }
1804}
1805
1806# ----------------------------------------------------------------------
1807# CONFIGURATION OPTION: -plotoutline
1808# ----------------------------------------------------------------------
1809itcl::configbody Rappture::FlowvisViewer::plotoutline {
1810    # Must check if we are connected because this routine is called from the
1811    # class body when the -plotoutline itk_option is defined.  At that point
1812    # the FlowvisViewer class constructor hasn't been called, so we can't
1813    # start sending commands to visualization server.
1814    if { [isconnected] } {
1815        if {"" == $itk_option(-plotoutline)} {
1816            SendCmd "volume outline state off"
1817        } else {
1818            SendCmd "volume outline state on"
1819            SendCmd "volume outline color [Color2RGB $itk_option(-plotoutline)]"
1820        }
1821    }
1822}
1823
1824#
1825# The -levels option takes a single value that represents the number
1826# of evenly distributed markers based on the current data range. Each
1827# marker is a relative value from 0.0 to 1.0.
1828#
1829itcl::body Rappture::FlowvisViewer::ParseLevelsOption { tf levels } {
1830    set c $itk_component(legend)
1831    regsub -all "," $levels " " levels
1832    if {[string is int $levels]} {
1833        for {set i 1} { $i <= $levels } {incr i} {
1834            set x [expr {double($i)/($levels+1)}]
1835            set m [Rappture::IsoMarker \#auto $c $this $tf]
1836            $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1837            $m relval $x
1838            lappend _isomarkers($tf) $m
1839        }
1840    } else {
1841        foreach x $levels {
1842            set m [Rappture::IsoMarker \#auto $c $this $tf]
1843            $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1844            $m relval $x
1845            lappend _isomarkers($tf) $m
1846        }
1847    }
1848}
1849
1850#
1851# The -markers option takes a list of zero or more values (the values
1852# may be separated either by spaces or commas) that have the following
1853# format:
1854#
1855#   N%  Percent of current total data range.  Converted to
1856#       to a relative value between 0.0 and 1.0.
1857#   N   Absolute value of marker.  If the marker is outside of
1858#       the current range, it will be displayed on the outer
1859#       edge of the legends, but it range it represents will
1860#       not be seen.
1861#
1862itcl::body Rappture::FlowvisViewer::ParseMarkersOption { tf markers } {
1863    set c $itk_component(legend)
1864    regsub -all "," $markers " " markers
1865    foreach marker $markers {
1866        set n [scan $marker "%g%s" value suffix]
1867        if { $n == 2 && $suffix == "%" } {
1868            # ${n}% : Set relative value.
1869            set value [expr {$value * 0.01}]
1870            set m [Rappture::IsoMarker \#auto $c $this $tf]
1871            $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1872            $m relval $value
1873            lappend _isomarkers($tf) $m
1874        } else {
1875            # ${n} : Set absolute value.
1876            set m [Rappture::IsoMarker \#auto $c $this $tf]
1877            $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1878            $m absval $value
1879            lappend _isomarkers($tf) $m
1880        }
1881    }
1882}
1883
1884# ----------------------------------------------------------------------
1885# USAGE: UpdateTransferFunctions
1886# ----------------------------------------------------------------------
1887itcl::body Rappture::FlowvisViewer::updateTransferFunctions {} {
1888    $_dispatcher event -after 100 !send_transfunc
1889}
1890
1891itcl::body Rappture::FlowvisViewer::AddIsoMarker { x y } {
1892    if { $_activeTf == "" } {
1893        error "active transfer function isn't set"
1894    }
1895    set tf $_activeTf
1896    set c $itk_component(legend)
1897    set m [Rappture::IsoMarker \#auto $c $this $tf]
1898    $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1899    set w [winfo width $c]
1900    $m relval [expr {double($x-10)/($w-20)}]
1901    lappend _isomarkers($tf) $m
1902    updateTransferFunctions
1903    return 1
1904}
1905
1906itcl::body Rappture::FlowvisViewer::removeDuplicateMarker { marker x } {
1907    set tf [$marker transferfunc]
1908    set bool 0
1909    if { [info exists _isomarkers($tf)] } {
1910        set list {}
1911        set marker [namespace tail $marker]
1912        foreach m $_isomarkers($tf) {
1913            set sx [$m screenpos]
1914            if { $m != $marker } {
1915                if { $x >= ($sx-3) && $x <= ($sx+3) } {
1916                    $marker relval [$m relval]
1917                    itcl::delete object $m
1918                    bell
1919                    set bool 1
1920                    continue
1921                }
1922            }
1923            lappend list $m
1924        }
1925        set _isomarkers($tf) $list
1926        updateTransferFunctions
1927    }
1928    return $bool
1929}
1930
1931itcl::body Rappture::FlowvisViewer::overMarker { marker x } {
1932    set tf [$marker transferfunc]
1933    if { [info exists _isomarkers($tf)] } {
1934        set marker [namespace tail $marker]
1935        foreach m $_isomarkers($tf) {
1936            set sx [$m screenpos]
1937            if { $m != $marker } {
1938                set bool [expr { $x >= ($sx-3) && $x <= ($sx+3) }]
1939                $m activate $bool
1940            }
1941        }
1942    }
1943    return ""
1944}
1945
1946itcl::body Rappture::FlowvisViewer::limits { cname } {
1947    set _limits(v) [list 0.0 1.0]
1948    if { ![info exists _style2datasets($cname)] } {
1949        puts stderr "no _style2datasets for cname=($cname)"
1950        return [array get _limits]
1951    }
1952    set min ""; set max ""
1953    foreach tag [GetDatasetsWithComponent $cname] {
1954        if { ![info exists _serverDatasets($tag)] } {
1955            puts stderr "$tag not in _serverDatasets?"
1956            continue
1957        }
1958        if { ![info exists _limits($tag)] } {
1959            puts stderr "$tag no min?"
1960            continue
1961        }
1962        foreach {vmin vmax} $_limits($tag) break
1963        if { $min == "" || $min > $vmin } {
1964            set min $vmin
1965        }
1966        if { $max == "" || $max < $vmax } {
1967            set max $vmax
1968        }
1969    }
1970    if { $min != "" && $max != "" } {
1971        set _limits(v) [list $min $max]
1972        set _limits($cname) [list $min $max]
1973    }
1974    return $_limits($cname)
1975}
1976
1977itcl::body Rappture::FlowvisViewer::BuildViewTab {} {
1978    set fg [option get $itk_component(hull) font Font]
1979    #set bfg [option get $itk_component(hull) boldFont Font]
1980
1981    set inner [$itk_component(main) insert end \
1982        -title "View Settings" \
1983        -icon [Rappture::icon wrench]]
1984    $inner configure -borderwidth 4
1985
1986    checkbutton $inner.isosurface \
1987        -text "Isosurface shading" \
1988        -variable [itcl::scope _settings(-isosurface)] \
1989        -command [itcl::code $this AdjustSetting -isosurface] \
1990        -font "Arial 9"
1991
1992    checkbutton $inner.axes \
1993        -text "Axes" \
1994        -variable [itcl::scope _settings(-axes)] \
1995        -command [itcl::code $this AdjustSetting -axes] \
1996        -font "Arial 9"
1997
1998    checkbutton $inner.grid \
1999        -text "Grid" \
2000        -variable [itcl::scope _settings(-grid)] \
2001        -command [itcl::code $this AdjustSetting -grid] \
2002        -font "Arial 9"
2003
2004    checkbutton $inner.outline \
2005        -text "Outline" \
2006        -variable [itcl::scope _settings(-outline)] \
2007        -command [itcl::code $this AdjustSetting -outline] \
2008        -font "Arial 9"
2009
2010    checkbutton $inner.legend \
2011        -text "Legend" \
2012        -variable [itcl::scope _settings(-legend)] \
2013        -command [itcl::code $this AdjustSetting -legend] \
2014        -font "Arial 9"
2015
2016    checkbutton $inner.volume \
2017        -text "Volume" \
2018        -variable [itcl::scope _settings(-volume)] \
2019        -command [itcl::code $this AdjustSetting -volume] \
2020        -font "Arial 9"
2021
2022    checkbutton $inner.particles \
2023        -text "Particles" \
2024        -variable [itcl::scope _settings(-particles)] \
2025        -command [itcl::code $this AdjustSetting -particles] \
2026        -font "Arial 9"
2027
2028    checkbutton $inner.lic \
2029        -text "Lic" \
2030        -variable [itcl::scope _settings(-lic)] \
2031        -command [itcl::code $this AdjustSetting -lic] \
2032        -font "Arial 9"
2033
2034    frame $inner.frame
2035
2036    blt::table $inner \
2037        0,0 $inner.axes  -cspan 2 -anchor w \
2038        1,0 $inner.grid  -cspan 2 -anchor w \
2039        2,0 $inner.outline  -cspan 2 -anchor w \
2040        3,0 $inner.volume  -cspan 2 -anchor w \
2041        4,0 $inner.legend  -cspan 2 -anchor w
2042
2043    bind $inner <Map> [itcl::code $this GetFlowInfo $inner]
2044
2045    blt::table configure $inner r* -resize none
2046    blt::table configure $inner r5 -resize expand
2047}
2048
2049itcl::body Rappture::FlowvisViewer::BuildVolumeTab {} {
2050    set inner [$itk_component(main) insert end \
2051        -title "Volume Settings" \
2052        -icon [Rappture::icon volume-on]]
2053    $inner configure -borderwidth 4
2054
2055    set fg [option get $itk_component(hull) font Font]
2056    #set bfg [option get $itk_component(hull) boldFont Font]
2057
2058    checkbutton $inner.vol -text "Show volume" -font $fg \
2059        -text "Volume" \
2060        -variable [itcl::scope _settings(-volume)] \
2061        -command [itcl::code $this AdjustSetting -volume] \
2062        -font "Arial 9"
2063
2064    label $inner.shading -text "Shading:" -font $fg
2065
2066    checkbutton $inner.light2side -text "Two-sided lighting" -font $fg \
2067        -variable [itcl::scope _settings(-light2side)] \
2068        -command [itcl::code $this AdjustSetting -light2side]
2069
2070    label $inner.ambient_l -text "Ambient" -font $fg
2071    ::scale $inner.ambient -from 0 -to 100 -orient horizontal \
2072        -variable [itcl::scope _settings(-ambient)] \
2073        -width 10 \
2074        -showvalue off -command [itcl::code $this AdjustSetting -ambient]
2075
2076    label $inner.diffuse_l -text "Diffuse" -font $fg
2077    ::scale $inner.diffuse -from 0 -to 100 -orient horizontal \
2078        -variable [itcl::scope _settings(-diffuse)] \
2079        -width 10 \
2080        -showvalue off -command [itcl::code $this AdjustSetting -diffuse]
2081
2082    label $inner.specularLevel_l -text "Specular" -font $fg
2083    ::scale $inner.specularLevel -from 0 -to 100 -orient horizontal \
2084        -variable [itcl::scope _settings(-specularLevel)] \
2085        -width 10 \
2086        -showvalue off -command [itcl::code $this AdjustSetting -specularLevel]
2087
2088    label $inner.specularExponent_l -text "Shininess" -font $fg
2089    ::scale $inner.specularExponent -from 10 -to 128 -orient horizontal \
2090        -variable [itcl::scope _settings(-specularExponent)] \
2091        -width 10 \
2092        -showvalue off -command [itcl::code $this AdjustSetting -specularExponent]
2093
2094    label $inner.clear -text "Clear" -font $fg
2095    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
2096        -variable [itcl::scope _settings(-opacity)] \
2097        -width 10 \
2098        -showvalue off -command [itcl::code $this AdjustSetting -opacity]
2099    label $inner.opaque -text "Opaque" -font $fg
2100
2101    label $inner.thin -text "Thin" -font $fg
2102    ::scale $inner.thickness -from 0 -to 1000 -orient horizontal \
2103        -variable [itcl::scope _settings(-thickness)] \
2104        -width 10 \
2105        -showvalue off -command [itcl::code $this AdjustSetting -thickness]
2106    label $inner.thick -text "Thick" -font $fg
2107
2108    label $inner.colormap_l -text "Colormap" -font "Arial 9"
2109    itk_component add colormap {
2110        Rappture::Combobox $inner.colormap -width 10 -editable no
2111    }
2112    $inner.colormap choices insert end [GetColormapList -includeNone]
2113    $itk_component(colormap) value "BCGYR"
2114    bind $inner.colormap <<Value>> \
2115        [itcl::code $this AdjustSetting -colormap]
2116
2117    blt::table $inner \
2118        0,0 $inner.vol -cspan 4 -anchor w -pady 2 \
2119        1,0 $inner.shading -cspan 4 -anchor w -pady {10 2} \
2120        2,0 $inner.light2side -cspan 4 -anchor w -pady 2 \
2121        3,0 $inner.ambient_l -anchor e -pady 2 \
2122        3,1 $inner.ambient -cspan 3 -pady 2 -fill x \
2123        4,0 $inner.diffuse_l -anchor e -pady 2 \
2124        4,1 $inner.diffuse -cspan 3 -pady 2 -fill x \
2125        5,0 $inner.specularLevel_l -anchor e -pady 2 \
2126        5,1 $inner.specularLevel -cspan 3 -pady 2 -fill x \
2127        6,0 $inner.specularExponent_l -anchor e -pady 2 \
2128        6,1 $inner.specularExponent -cspan 3 -pady 2 -fill x \
2129        7,0 $inner.clear -anchor e -pady 2 \
2130        7,1 $inner.opacity -cspan 2 -pady 2 -fill x \
2131        7,3 $inner.opaque -anchor w -pady 2 \
2132        8,0 $inner.thin -anchor e -pady 2 \
2133        8,1 $inner.thickness -cspan 2 -pady 2 -fill x \
2134        8,3 $inner.thick -anchor w -pady 2
2135
2136    blt::table configure $inner c0 c1 c3 r* -resize none
2137    blt::table configure $inner r9 -resize expand
2138}
2139
2140itcl::body Rappture::FlowvisViewer::BuildCutplanesTab {} {
2141    set inner [$itk_component(main) insert end \
2142        -title "Cutplane Settings" \
2143        -icon [Rappture::icon cutbutton]]
2144    $inner configure -borderwidth 4
2145
2146    # X-value slicer...
2147    itk_component add xCutButton {
2148        Rappture::PushButton $inner.xbutton \
2149            -onimage [Rappture::icon x-cutplane] \
2150            -offimage [Rappture::icon x-cutplane] \
2151            -command [itcl::code $this AdjustSetting -xcutplane] \
2152            -variable [itcl::scope _settings(-xcutplane)]
2153    }
2154    Rappture::Tooltip::for $itk_component(xCutButton) \
2155        "Toggle the X cut plane on/off"
2156    $itk_component(xCutButton) select
2157
2158    itk_component add xCutScale {
2159        ::scale $inner.xval -from 100 -to 0 \
2160            -width 10 -orient vertical -showvalue off \
2161            -borderwidth 1 -highlightthickness 0 \
2162            -command [itcl::code $this Slice move x] \
2163            -variable [itcl::scope _settings(-xcutposition)]
2164    } {
2165        usual
2166        ignore -borderwidth -highlightthickness
2167    }
2168    # Set the default cutplane value before disabling the scale.
2169    $itk_component(xCutScale) set 50
2170    $itk_component(xCutScale) configure -state disabled
2171    Rappture::Tooltip::for $itk_component(xCutScale) \
2172        "@[itcl::code $this SlicerTip x]"
2173
2174    # Y-value slicer...
2175    itk_component add yCutButton {
2176        Rappture::PushButton $inner.ybutton \
2177            -onimage [Rappture::icon y-cutplane] \
2178            -offimage [Rappture::icon y-cutplane] \
2179            -command [itcl::code $this AdjustSetting -ycutplane] \
2180            -variable [itcl::scope _settings(-ycutplane)]
2181    }
2182    Rappture::Tooltip::for $itk_component(yCutButton) \
2183        "Toggle the Y cut plane on/off"
2184    $itk_component(yCutButton) select
2185
2186    itk_component add yCutScale {
2187        ::scale $inner.yval -from 100 -to 0 \
2188            -width 10 -orient vertical -showvalue off \
2189            -borderwidth 1 -highlightthickness 0 \
2190            -command [itcl::code $this Slice move y] \
2191            -variable [itcl::scope _settings(-ycutposition)]
2192    } {
2193        usual
2194        ignore -borderwidth -highlightthickness
2195    }
2196    Rappture::Tooltip::for $itk_component(yCutScale) \
2197        "@[itcl::code $this SlicerTip y]"
2198    # Set the default cutplane value before disabling the scale.
2199    $itk_component(yCutScale) set 50
2200    $itk_component(yCutScale) configure -state disabled
2201
2202    # Z-value slicer...
2203    itk_component add zCutButton {
2204        Rappture::PushButton $inner.zbutton \
2205            -onimage [Rappture::icon z-cutplane] \
2206            -offimage [Rappture::icon z-cutplane] \
2207            -command [itcl::code $this AdjustSetting -zcutplane] \
2208            -variable [itcl::scope _settings(-zcutplane)]
2209    }
2210    Rappture::Tooltip::for $itk_component(zCutButton) \
2211        "Toggle the Z cut plane on/off"
2212    $itk_component(zCutButton) select
2213
2214    itk_component add zCutScale {
2215        ::scale $inner.zval -from 100 -to 0 \
2216            -width 10 -orient vertical -showvalue off \
2217            -borderwidth 1 -highlightthickness 0 \
2218            -command [itcl::code $this Slice move z] \
2219            -variable [itcl::scope _settings(-zcutposition)]
2220    } {
2221        usual
2222        ignore -borderwidth -highlightthickness
2223    }
2224    $itk_component(zCutScale) set 50
2225    $itk_component(zCutScale) configure -state disabled
2226    #$itk_component(zCutScale) configure -state disabled
2227    Rappture::Tooltip::for $itk_component(zCutScale) \
2228        "@[itcl::code $this SlicerTip z]"
2229
2230    blt::table $inner \
2231        1,1 $itk_component(xCutButton) \
2232        1,2 $itk_component(yCutButton) \
2233        1,3 $itk_component(zCutButton) \
2234        0,1 $itk_component(xCutScale) \
2235        0,2 $itk_component(yCutScale) \
2236        0,3 $itk_component(zCutScale) \
2237
2238    blt::table configure $inner r0 r1 c* -resize none
2239    blt::table configure $inner r2 c4 -resize expand
2240    blt::table configure $inner c0 -width 2
2241    blt::table configure $inner c1 c2 c3 -padx 2
2242}
2243
2244itcl::body Rappture::FlowvisViewer::BuildCameraTab {} {
2245    set inner [$itk_component(main) insert end \
2246        -title "Camera Settings" \
2247        -icon [Rappture::icon camera]]
2248    $inner configure -borderwidth 4
2249
2250    label $inner.view_l -text "view" -font "Arial 9"
2251    set f [frame $inner.view]
2252    foreach side { front back left right top bottom } {
2253        button $f.$side  -image [Rappture::icon view$side] \
2254            -command [itcl::code $this SetOrientation $side]
2255        Rappture::Tooltip::for $f.$side "Change the view to $side"
2256        pack $f.$side -side left
2257    }
2258
2259    blt::table $inner \
2260        0,0 $inner.view_l -anchor e -pady 2 \
2261        0,1 $inner.view -anchor w -pady 2
2262    blt::table configure $inner r0 -resize none
2263
2264    set row 1
2265    set labels { qw qx qy qz xpan ypan zoom }
2266    foreach tag $labels {
2267        label $inner.${tag}label -text $tag -font "Arial 9"
2268        entry $inner.${tag} -font "Arial 9"  -bg white \
2269            -textvariable [itcl::scope _settings(-$tag)]
2270        bind $inner.${tag} <Return> \
2271            [itcl::code $this camera set -${tag}]
2272        bind $inner.${tag} <KP_Enter> \
2273            [itcl::code $this camera set -${tag}]
2274        blt::table $inner \
2275            $row,0 $inner.${tag}label -anchor e -pady 2 \
2276            $row,1 $inner.${tag} -anchor w -pady 2
2277        blt::table configure $inner r$row -resize none
2278        incr row
2279    }
2280
2281    blt::table configure $inner c* -resize none
2282    blt::table configure $inner c2 -resize expand
2283    blt::table configure $inner r$row -resize expand
2284}
2285
2286itcl::body Rappture::FlowvisViewer::GetFlowInfo { w } {
2287    set flowobj ""
2288    foreach key [array names _dataset2flow] {
2289        set flowobj $_dataset2flow($key)
2290        break
2291    }
2292    if { $flowobj == "" } {
2293        return
2294    }
2295    if { [winfo exists $w.frame] } {
2296        destroy $w.frame
2297    }
2298    set inner [frame $w.frame]
2299    blt::table $w \
2300        5,0 $inner -fill both -cspan 2 -anchor nw
2301    array set hints [$flowobj hints]
2302    checkbutton $inner.showstreams -text "Streams Plane" \
2303        -variable [itcl::scope _settings(-streams)] \
2304        -command  [itcl::code $this streams $key $hints(name)]  \
2305        -font "Arial 9"
2306    Rappture::Tooltip::for $inner.showstreams $hints(description)
2307
2308    checkbutton $inner.showarrows -text "Arrows" \
2309        -variable [itcl::scope _settings(-arrows)] \
2310        -command  [itcl::code $this arrows $key $hints(name)]  \
2311        -font "Arial 9"
2312
2313    label $inner.particles -text "Particles" -font "Arial 9 bold"
2314    label $inner.boxes -text "Boxes" -font "Arial 9 bold"
2315
2316    blt::table $inner \
2317        1,0 $inner.showstreams  -anchor w \
2318        2,0 $inner.showarrows  -anchor w
2319    blt::table configure $inner c0 c1 -resize none
2320    blt::table configure $inner c2 -resize expand
2321
2322    set row 3
2323    set particles [$flowobj particles]
2324    if { [llength $particles] > 0 } {
2325        blt::table $inner $row,0 $inner.particles  -anchor w
2326        incr row
2327    }
2328    foreach part $particles {
2329        array unset info
2330        array set info $part
2331        set name $info(name)
2332        if { ![info exists _settings(-particles-$name)] } {
2333            set _settings(-particles-$name) $info(hide)
2334        }
2335        checkbutton $inner.part$row -text $info(label) \
2336            -variable [itcl::scope _settings(-particles-$name)] \
2337            -onvalue 0 -offvalue 1 \
2338            -command [itcl::code $this particles $key $name] \
2339            -font "Arial 9"
2340        Rappture::Tooltip::for $inner.part$row $info(description)
2341        blt::table $inner $row,0 $inner.part$row -anchor w
2342        if { !$_settings(-particles-$name) } {
2343            $inner.part$row select
2344        }
2345        incr row
2346    }
2347    set boxes [$flowobj boxes]
2348    if { [llength $boxes] > 0 } {
2349        blt::table $inner $row,0 $inner.boxes  -anchor w
2350        incr row
2351    }
2352    foreach box $boxes {
2353        array unset info
2354        array set info $box
2355        set name $info(name)
2356        if { ![info exists _settings(-box-$name)] } {
2357            set _settings(-box-$name) $info(hide)
2358        }
2359        checkbutton $inner.box$row -text $info(label) \
2360            -variable [itcl::scope _settings(-box-$name)] \
2361            -onvalue 0 -offvalue 1 \
2362            -command [itcl::code $this box $key $name] \
2363            -font "Arial 9"
2364        Rappture::Tooltip::for $inner.box$row $info(description)
2365        blt::table $inner $row,0 $inner.box$row -anchor w
2366        if { !$_settings(-box-$name) } {
2367            $inner.box$row select
2368        }
2369        incr row
2370    }
2371    blt::table configure $inner r* -resize none
2372    blt::table configure $inner r$row -resize expand
2373    blt::table configure $inner c3 -resize expand
2374    event generate [winfo parent [winfo parent $w]] <Configure>
2375}
2376
2377itcl::body Rappture::FlowvisViewer::particles { tag name } {
2378    set bool $_settings(-particles-$name)
2379    SendCmd "$tag particles configure {$name} -hide $bool"
2380}
2381
2382itcl::body Rappture::FlowvisViewer::box { tag name } {
2383    set bool $_settings(-box-$name)
2384    SendCmd "$tag box configure {$name} -hide $bool"
2385}
2386
2387itcl::body Rappture::FlowvisViewer::streams { tag name } {
2388    set bool $_settings(-streams)
2389    SendCmd "$tag configure -slice $bool"
2390}
2391
2392itcl::body Rappture::FlowvisViewer::arrows { tag name } {
2393    set bool $_settings(-arrows)
2394    SendCmd "$tag configure -arrows $bool"
2395}
2396
2397# ----------------------------------------------------------------------
2398# USAGE: Slice move x|y|z <newval>
2399#
2400# Called automatically when the user drags the slider to move the
2401# cut plane that slices 3D data.  Gets the current value from the
2402# slider and moves the cut plane to the appropriate point in the
2403# data set.
2404# ----------------------------------------------------------------------
2405itcl::body Rappture::FlowvisViewer::Slice {option args} {
2406    switch -- $option {
2407        move {
2408            if {[llength $args] != 2} {
2409                error "wrong # args: should be \"Slice move x|y|z newval\""
2410            }
2411            set axis [lindex $args 0]
2412            set newval [lindex $args 1]
2413            set newpos [expr {0.01*$newval}]
2414
2415            # show the current value in the readout
2416
2417            set ids [CurrentVolumeIds -cutplanes]
2418            SendCmd "cutplane position $newpos $axis $ids"
2419        }
2420        default {
2421            error "bad option \"$option\": should be axis, move, or volume"
2422        }
2423    }
2424}
2425
2426# ----------------------------------------------------------------------
2427# USAGE: SlicerTip <axis>
2428#
2429# Used internally to generate a tooltip for the x/y/z slicer controls.
2430# Returns a message that includes the current slicer value.
2431# ----------------------------------------------------------------------
2432itcl::body Rappture::FlowvisViewer::SlicerTip {axis} {
2433    set val [$itk_component(${axis}CutScale) get]
2434    return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
2435}
2436
2437itcl::body Rappture::FlowvisViewer::Resize {} {
2438    $_arcball resize $_width $_height
2439    SendCmd "screen size $_width $_height"
2440    set _resizePending 0
2441}
2442
2443itcl::body Rappture::FlowvisViewer::EventuallyResize { w h } {
2444    set _width $w
2445    set _height $h
2446    $_arcball resize $w $h
2447    if { !$_resizePending } {
2448        $_dispatcher event -after 200 !resize
2449        set _resizePending 1
2450    }
2451}
2452
2453itcl::body Rappture::FlowvisViewer::EventuallyResizeLegend {} {
2454    if { !$_resizeLegendPending } {
2455        $_dispatcher event -after 100 !legend
2456        set _resizeLegendPending 1
2457    }
2458}
2459
2460itcl::body Rappture::FlowvisViewer::EventuallyGoto { nSteps } {
2461    set _flow(goto) $nSteps
2462    if { !$_gotoPending } {
2463        $_dispatcher event -after 1000 !goto
2464        set _gotoPending 1
2465    }
2466}
2467
2468#  camera --
2469itcl::body Rappture::FlowvisViewer::camera {option args} {
2470    switch -- $option {
2471        "show" {
2472            puts [array get _view]
2473        }
2474        "set" {
2475            set what [lindex $args 0]
2476            set x $_settings(${this}${what})
2477            set code [catch { string is double $x } result]
2478            if { $code != 0 || !$result } {
2479                set _settings(${this}${what}) $_view($what)
2480                return
2481            }
2482            switch -- $what {
2483                "-xpan" - "-ypan" {
2484                    set _view($what) $_settings(${this}${what})
2485                    PanCamera
2486                }
2487                "-qx" - "-qy" - "-qz" - "-qw" {
2488                    set _view($what) $_settings(${this}${what})
2489                    set q [ViewToQuaternion]
2490                    $_arcball quaternion $q
2491                    SendCmd "camera orient $q"
2492                }
2493                "-zoom" {
2494                    set _view($what) $_settings(${this}${what})
2495                    SendCmd "camera zoom $_view($what)"
2496                }
2497            }
2498        }
2499    }
2500}
2501
2502itcl::body Rappture::FlowvisViewer::SendFlowCmd { dataobj comp nbytes extents } {
2503    set tag "$dataobj-$comp"
2504    if { ![info exists _dataset2flow($tag)] } {
2505        SendCmd "flow add $tag"
2506        SendCmd "$tag data follows $nbytes $extents"
2507        return 0
2508    }
2509    set flowobj $_dataset2flow($tag)
2510    if { $flowobj == "" } {
2511        puts stderr "no flowobj"
2512        return -1
2513    }
2514    SendCmd "if {\[flow exists $tag\]} {flow delete $tag}"
2515    array set info  [$flowobj hints]
2516    set _settings($this-volume) $info(volume)
2517    set _settings($this-outline) $info(outline)
2518    set _settings($this-arrows) $info(arrows)
2519    set _settings($this-duration) $info(duration)
2520    $itk_component(speed) value $info(speed)
2521    set cmd {}
2522    append cmd "flow add $tag"
2523    append cmd " -position $info(position)"
2524    append cmd " -axis $info(axis)"
2525    append cmd " -volume $info(volume)"
2526    append cmd " -outline $info(outline)"
2527    append cmd " -slice $info(streams)"
2528    append cmd " -arrows $info(arrows)"
2529    SendCmd $cmd
2530    foreach part [$flowobj particles] {
2531        set cmd {}
2532        array unset info
2533        array set info $part
2534        set color [Color2RGB $info(color)]
2535        append cmd "$tag particles add $info(name)"
2536        append cmd " -position $info(position)"
2537        append cmd " -hide $info(hide)"
2538        append cmd " -axis $info(axis)"
2539        append cmd " -color {$color}"
2540        append cmd " -size $info(size)"
2541        SendCmd $cmd
2542    }
2543    foreach box [$flowobj boxes] {
2544        set cmd {}
2545        array unset info
2546        set info(corner1) ""
2547        set info(corner2) ""
2548        array set info $box
2549        if { $info(corner1) == "" || $info(corner2) == "" } {
2550            continue
2551        }
2552        set color [Color2RGB $info(color)]
2553        append cmd "$tag box add $info(name)"
2554        append cmd " -color {$color}"
2555        append cmd " -hide $info(hide)"
2556        append cmd " -linewidth $info(linewidth) "
2557        append cmd " -corner1 {$info(corner1)} "
2558        append cmd " -corner2 {$info(corner2)}"
2559        SendCmd $cmd
2560    }
2561    SendCmd "$tag data follows $nbytes $extents"
2562    return 0
2563}
2564
2565#
2566# flow --
2567#
2568# Called when the user clicks on the stop or play buttons
2569# for flow visualization.
2570#
2571#        $this flow play
2572#        $this flow stop
2573#        $this flow toggle
2574#        $this flow reset
2575#        $this flow pause
2576#        $this flow next
2577#
2578itcl::body Rappture::FlowvisViewer::flow { args } {
2579    set option [lindex $args 0]
2580    switch -- $option {
2581        "goto2" {
2582            puts stderr "actually sending \"flow goto $_flow(goto)\""
2583            SendCmd "flow goto $_flow(goto)"
2584            set _gotoPending 0
2585        }
2586        "goto" {
2587            puts stderr "flow goto to $_settings(-currenttime)"
2588            # Figure out how many steps to the current time based upon
2589            # the speed and duration.
2590            set current $_settings(-currenttime)
2591            set speed [$itk_component(speed) value]
2592            set time [str2millisecs $_settings(-duration)]
2593            $itk_component(dial) configure -max $time
2594            set delay [expr int(round(500.0/$speed))]
2595            set timePerStep [expr {double($time) / $delay}]
2596            set nSteps [expr {int(ceil($current/$timePerStep))}]
2597            EventuallyGoto $nSteps
2598        }
2599        "speed" {
2600            set speed [$itk_component(speed) value]
2601            set _flow(delay) [expr int(round(500.0/$speed))]
2602        }
2603        "duration" {
2604            set max [str2millisecs $_settings(-duration)]
2605            if { $max < 0 } {
2606                bell
2607                return
2608            }
2609            set _flow(duration) $max
2610            set _settings(-duration) [millisecs2str $max]
2611            $itk_component(dial) configure -max $max
2612        }
2613        "off" {
2614            set _flow(state) 0
2615            $_dispatcher cancel !play
2616            $itk_component(play) deselect
2617        }
2618        "on" {
2619            flow speed
2620            flow duration
2621            set _flow(state) 1
2622            set _settings(-currenttime) 0
2623            $itk_component(play) select
2624        }
2625        "stop" {
2626            if { $_flow(state) } {
2627                flow off
2628                flow reset
2629            }
2630        }
2631        "pause" {
2632            if { $_flow(state) } {
2633                flow off
2634            }
2635        }
2636        "play" {
2637            # If the flow is currently off, then restart it.
2638            if { !$_flow(state) } {
2639                flow on
2640                # If we're at the end of the flow, reset the flow.
2641                set _settings(-currenttime) \
2642                    [expr {$_settings(-currenttime) + $_flow(delay)}]
2643                if { $_settings(-currenttime) >= $_flow(duration) } {
2644                    set _settings(-step) 1
2645                    SendCmd "flow reset"
2646                }
2647                flow next
2648            }
2649        }
2650        "toggle" {
2651            if { $_settings(-play) } {
2652                flow play
2653            } else {
2654                flow pause
2655            }
2656        }
2657        "reset" {
2658            set _settings(-currenttime) 0
2659            SendCmd "flow reset"
2660        }
2661        "next" {
2662            if { ![winfo viewable $itk_component(3dview)] } {
2663                flow stop
2664                return
2665            }
2666            set _settings(-currenttime) \
2667                [expr {$_settings(-currenttime) + $_flow(delay)}]
2668            if { $_settings(-currenttime) >= $_flow(duration) } {
2669                if { !$_settings(-loop) } {
2670                    flow off
2671                    return
2672                }
2673                flow reset
2674            } else {
2675                SendCmd "flow next"
2676            }
2677            $_dispatcher event -after $_flow(delay) !play
2678        }
2679        default {
2680            error "bad option \"$option\": should be play, stop, toggle, or reset."
2681        }
2682    }
2683}
2684
2685itcl::body Rappture::FlowvisViewer::WaitIcon  { option widget } {
2686    switch -- $option {
2687        "start" {
2688            $_dispatcher dispatch $this !waiticon \
2689                "[itcl::code $this WaitIcon "next" $widget] ; list"
2690            set _icon 0
2691            $widget configure -image [Rappture::icon bigroller${_icon}]
2692            $_dispatcher event -after 100 !waiticon
2693        }
2694        "next" {
2695            incr _icon
2696            if { $_icon >= 8 } {
2697                set _icon 0
2698            }
2699            $widget configure -image [Rappture::icon bigroller${_icon}]
2700            $_dispatcher event -after 100 !waiticon
2701        }
2702        "stop" {
2703            $_dispatcher cancel !waiticon
2704        }
2705    }
2706}
2707
2708itcl::body Rappture::FlowvisViewer::GetPngImage { widget width height } {
2709    set token "print[incr _nextToken]"
2710    set var ::Rappture::FlowvisViewer::_hardcopy($this-$token)
2711    set $var ""
2712
2713    # Setup an automatic timeout procedure.
2714    $_dispatcher dispatch $this !pngtimeout "set $var {} ; list"
2715
2716    set popup .flowvisviewerprint
2717    if {![winfo exists $popup]} {
2718        Rappture::Balloon $popup -title "Generating file..."
2719        set inner [$popup component inner]
2720        label $inner.title -text "Generating hardcopy." -font "Arial 10 bold"
2721        label $inner.please -text "This may take a minute." -font "Arial 10"
2722        label $inner.icon -image [Rappture::icon bigroller0]
2723        button $inner.cancel -text "Cancel" -font "Arial 10 bold" \
2724            -command [list set $var ""]
2725        blt::table $inner \
2726            0,0 $inner.title -cspan 2 \
2727            1,0 $inner.please -anchor w \
2728            1,1 $inner.icon -anchor e  \
2729            2,0 $inner.cancel -cspan 2
2730        blt::table configure $inner r0 -pady 4
2731        blt::table configure $inner r2 -pady 4
2732        bind $inner.cancel <KeyPress-Return> [list $inner.cancel invoke]
2733    } else {
2734        set inner [$popup component inner]
2735    }
2736
2737    $_dispatcher event -after 60000 !pngtimeout
2738    WaitIcon start $inner.icon
2739    grab set $inner
2740    focus $inner.cancel
2741
2742    SendCmd "print $token $width $height"
2743
2744    $popup activate $widget below
2745    update idletasks
2746    update
2747    # We wait here for either
2748    #  1) the png to be delivered or
2749    #  2) timeout or
2750    #  3) user cancels the operation.
2751    tkwait variable $var
2752
2753    # Clean up.
2754    $_dispatcher cancel !pngtimeout
2755    WaitIcon stop $inner.icon
2756    grab release $inner
2757    $popup deactivate
2758    update
2759
2760    if { $_hardcopy($this-$token) != "" } {
2761        return [list .png $_hardcopy($this-$token)]
2762    }
2763    return ""
2764}
2765
2766itcl::body Rappture::FlowvisViewer::GetMovie { widget w h } {
2767    set token "movie[incr _nextToken]"
2768    set var ::Rappture::FlowvisViewer::_hardcopy($this-$token)
2769    set $var ""
2770
2771    # Setup an automatic timeout procedure.
2772    $_dispatcher dispatch $this !movietimeout "set $var {} ; list"
2773    set popup .flowvisviewermovie
2774    if {![winfo exists $popup]} {
2775        Rappture::Balloon $popup -title "Generating movie..."
2776        set inner [$popup component inner]
2777        label $inner.title -text "Generating movie for download" \
2778                -font "Arial 10 bold"
2779        label $inner.please -text "This may take a few minutes." \
2780                -font "Arial 10"
2781        label $inner.icon -image [Rappture::icon bigroller0]
2782        button $inner.cancel -text "Cancel" -font "Arial 10 bold" \
2783            -command [list set $var ""]
2784        blt::table $inner \
2785            0,0 $inner.title -cspan 2 \
2786            1,0 $inner.please -anchor w \
2787            1,1 $inner.icon -anchor e  \
2788            2,0 $inner.cancel -cspan 2
2789        blt::table configure $inner r0 -pady 4
2790        blt::table configure $inner r2 -pady 4
2791        bind $inner.cancel <KeyPress-Return> [list $inner.cancel invoke]
2792    } else {
2793        set inner [$popup component inner]
2794    }
2795    update
2796    # Timeout is set to 10 minutes.
2797    $_dispatcher event -after 600000 !movietimeout
2798    WaitIcon start $inner.icon
2799    grab set $inner
2800    focus $inner.cancel
2801
2802    flow duration
2803    flow speed
2804    set nframes [expr round($_flow(duration) / $_flow(delay))]
2805    set framerate [expr 1000.0 / $_flow(delay)]
2806
2807    # These are specific to MPEG1 video generation
2808    set framerate 25.0
2809    set bitrate 6.0e+6
2810
2811    set start [clock seconds]
2812    SendCmd "flow video $token -width $w -height $h -numframes $nframes "
2813
2814    $popup activate $widget below
2815    update idletasks
2816    update
2817    # We wait here until
2818    #  1. the movie is delivered or
2819    #  2. we've timed out or
2820    #  3. the user has canceled the operation.b
2821    tkwait variable $var
2822
2823    puts stderr "Video generated in [expr [clock seconds] - $start] seconds."
2824
2825    # Clean up.
2826    $_dispatcher cancel !movietimeout
2827    WaitIcon stop $inner.icon
2828    grab release $inner
2829    $popup deactivate
2830    destroy $popup
2831    update
2832
2833    # This will both cancel the movie generation (if it hasn't already
2834    # completed) and reset the flow.
2835    SendCmd "flow reset"
2836    if { $_hardcopy($this-$token) != "" } {
2837        return [list .mpg $_hardcopy($this-$token)]
2838    }
2839    return ""
2840}
2841
2842itcl::body Rappture::FlowvisViewer::str2millisecs { value } {
2843    set parts [split $value :]
2844    set secs 0
2845    set mins 0
2846    if { [llength $parts] == 1 } {
2847        scan [lindex $parts 0] "%d" secs
2848    } else {
2849        scan [lindex $parts 1] "%d" secs
2850        scan [lindex $parts 0] "%d" mins
2851    }
2852    set ms [expr {(($mins * 60) + $secs) * 1000.0}]
2853    if { $ms > 600000.0 } {
2854        set ms 600000.0
2855    }
2856    if { $ms == 0.0 } {
2857        set ms 60000.0
2858    }
2859    return $ms
2860}
2861
2862itcl::body Rappture::FlowvisViewer::millisecs2str { value } {
2863    set min [expr floor($value / 60000.0)]
2864    set sec [expr ($value - ($min*60000.0)) / 1000.0]
2865    return [format %02d:%02d [expr round($min)] [expr round($sec)]]
2866}
2867
2868itcl::body Rappture::FlowvisViewer::SetOrientation { side } {
2869    array set positions {
2870        front "1 0 0 0"
2871        back  "0 0 1 0"
2872        left  "0.707107 0 -0.707107 0"
2873        right "0.707107 0 0.707107 0"
2874        top   "0.707107 -0.707107 0 0"
2875        bottom "0.707107 0.707107 0 0"
2876    }
2877    foreach name { -qw -qx -qy -qz } value $positions($side) {
2878        set _view($name) $value
2879    }
2880    set q [ViewToQuaternion]
2881    $_arcball quaternion $q
2882    SendCmd "camera orient $q"
2883    SendCmd "camera reset"
2884    set _view(-xpan) 0.0
2885    set _view(-ypan) 0.0
2886    set _view(-zoom) 1.0
2887    set _settings(-xpan) $_view(-xpan)
2888    set _settings(-ypan) $_view(-ypan)
2889    set _settings(-zoom) $_view(-zoom)
2890}
2891
2892# Reset global settings from dataset's settings.
2893itcl::body Rappture::FlowvisViewer::BuildVolumeComponents {} {
2894    $itk_component(volcomponents) choices delete 0 end
2895    foreach name $_componentsList {
2896        $itk_component(volcomponents) choices insert end $name $name
2897    }
2898    set _current [lindex $_componentsList 0]
2899    $itk_component(volcomponents) value $_current
2900}
2901
2902# Reset global settings from dataset's settings.
2903itcl::body Rappture::FlowvisViewer::GetDatasetsWithComponent { cname } {
2904    if { ![info exists _volcomponents($cname)] } {
2905        return ""
2906    }
2907    set list ""
2908    foreach tag $_volcomponents($cname) {
2909        if { ![info exists _serverDatasets($tag)] } {
2910            continue
2911        }
2912        lappend list $tag
2913    }
2914    return $list
2915}
Note: See TracBrowser for help on using the repository browser.