source: branches/1.7/gui/scripts/flowvisviewer.tcl @ 6266

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

merge r6265 from 1.6 branch

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