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

Last change on this file since 3394 was 3394, checked in by gah, 11 years ago

fix up stats reporting in servers

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