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

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

Fix initial download format for flowvis viewer

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