source: branches/1.3/gui/scripts/flowvisviewer.tcl @ 5277

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

More merging/backporting in flowvis viewer

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