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

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

More syncing nanovis/flowvis viewers. Only call SetObjectStyle? on first load
of data. Init cutplane positions in Rebuild, add some checks to DrawLegend?.

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