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

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

Add build info to clientinfo command

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