source: branches/1.7/gui/scripts/vtkvolumeviewer.tcl @ 6306

Last change on this file since 6306 was 6306, checked in by ldelgass, 6 years ago

merge fixes from trunk

File size: 82.0 KB
Line 
1# -*- mode: tcl; indent-tabs-mode: nil -*-
2# ----------------------------------------------------------------------
3#  COMPONENT: vtkvolumeviewer - Vtk volume viewer
4#
5#  This widget performs volume rendering on 3D scalar/vector datasets.
6#  It connects to the Vtkvis server running on a rendering farm,
7#  transmits data, and displays the results.
8# ======================================================================
9#  AUTHOR:  Michael McLennan, Purdue University
10#  Copyright (c) 2004-2016  HUBzero Foundation, LLC
11#
12#  See the file "license.terms" for information on usage and
13#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
14# ======================================================================
15package require Itk
16package require BLT
17#package require Img
18
19option add *VtkVolumeViewer.width 4i widgetDefault
20option add *VtkVolumeViewer*cursor crosshair widgetDefault
21option add *VtkVolumeViewer.height 4i widgetDefault
22option add *VtkVolumeViewer.foreground black widgetDefault
23option add *VtkVolumeViewer.controlBackground gray widgetDefault
24option add *VtkVolumeViewer.controlDarkBackground #999999 widgetDefault
25option add *VtkVolumeViewer.plotBackground black widgetDefault
26option add *VtkVolumeViewer.plotForeground white widgetDefault
27option add *VtkVolumeViewer.font \
28    -*-helvetica-medium-r-normal-*-12-* widgetDefault
29
30# must use this name -- plugs into Rappture::resources::load
31proc VtkVolumeViewer_init_resources {} {
32    Rappture::resources::register \
33        vtkvis_server Rappture::VtkVolumeViewer::SetServerList
34}
35
36itcl::class Rappture::VtkVolumeViewer {
37    inherit Rappture::VisViewer
38
39    itk_option define -plotforeground plotForeground Foreground ""
40    itk_option define -plotbackground plotBackground Background ""
41
42    constructor { args } {
43        Rappture::VisViewer::constructor
44    } {
45        # defined below
46    }
47    destructor {
48        # defined below
49    }
50    public proc SetServerList { namelist } {
51        Rappture::VisViewer::SetServerList "vtkvis" $namelist
52    }
53    public method add {dataobj {settings ""}}
54    public method camera {option args}
55    public method delete {args}
56    public method disconnect {}
57    public method download {option args}
58    public method get {args}
59    public method isconnected {}
60    public method parameters {title args} {
61        # do nothing
62    }
63    public method scale {args}
64
65    # The following methods are only used by this class.
66    private method AdjustSetting {what {value ""}}
67    private method BuildAxisTab {}
68    private method BuildCameraTab {}
69    private method BuildColormap { name colors }
70    private method BuildCutplanesTab {}
71    private method BuildDownloadPopup { widget command }
72    private method BuildViewTab {}
73    private method BuildVolumeTab {}
74    private method ChangeColormap { dataobj comp color }
75    private method Combo { option }
76    private method Connect {}
77    private method CurrentDatasets {args}
78    private method Disconnect {}
79    private method DoResize {}
80    private method DoRotate {}
81    private method DrawLegend {}
82    private method EnterLegend { x y }
83    private method EventuallyRequestLegend {}
84    private method EventuallyResize { w h }
85    private method EventuallyRotate { q }
86    private method EventuallySetCutplane { axis args }
87    private method GetDatasetsWithComponent { cname }
88    private method GetImage { args }
89    private method GetVtkData { args }
90    private method InitSettings { args }
91    private method IsValidObject { dataobj }
92    private method LeaveLegend {}
93    private method MotionLegend { x y }
94    private method Pan {option x y}
95    private method PanCamera {}
96    private method Pick {x y}
97    private method QuaternionToView { q } {
98        foreach { _view(-qw) _view(-qx) _view(-qy) _view(-qz) } $q break
99    }
100    private method Rebuild {}
101    private method ReceiveDataset { args }
102    private method ReceiveImage { args }
103    private method ReceiveLegend { colormap title vmin vmax size }
104    private method RequestLegend {}
105    private method Rotate {option x y}
106    private method SetColormap { dataobj comp }
107    private method SetLegendTip { x y }
108    private method SetObjectStyle { dataobj cname }
109    private method SetOrientation { side }
110    private method Slice {option args}
111    private method ViewToQuaternion {} {
112        return [list $_view(-qw) $_view(-qx) $_view(-qy) $_view(-qz)]
113    }
114    private method Zoom {option}
115
116    private variable _arcball ""
117    private variable _dlist "";         # list of data objects
118    private variable _obj2ovride;       # maps dataobj => style override
119    private variable _datasets;         # contains all the dataobj-component
120                                        # datasets in the server
121    private variable _colormaps;        # contains all the colormaps
122                                        # in the server.
123    private variable _dataset2style;    # maps dataobj-component to transfunc
124
125    private variable _reset 1;          # Connection to server has been reset.
126    private variable _click;            # Info used for rotate operations.
127    private variable _limits;           # Autoscale min/max for all axes
128    private variable _view;             # View params for 3D view
129    private variable _settings
130    private variable _style;            # Array of current component styles.
131    private variable _initialStyle;     # Array of initial component styles.
132
133    private variable _start 0
134    private variable _title ""
135    private variable _fields
136    private variable _curFldName ""
137    private variable _curFldLabel ""
138    private variable _colorMode "scalar"; # Mode of colormap (vmag or scalar)
139    private variable _cutplaneCmd "imgcutplane"
140    private variable _allowMultiComponent 0
141
142    private variable _first "";         # This is the topmost dataset.
143    private variable _volcomponents;    # Maps component name to list of
144                                        # dataobj-component tags
145    private variable _componentsList;   # List of components found
146
147    private variable _width 0
148    private variable _height 0
149    private variable _resizePending 0
150    private variable _legendPending 0
151    private variable _rotatePending 0
152    private variable _cutplanePending 0
153
154    private common _downloadPopup;      # download options from popup
155    private common _hardcopy
156}
157
158itk::usual VtkVolumeViewer {
159    keep -background -foreground -cursor -font
160    keep -plotbackground -plotforeground
161}
162
163# ----------------------------------------------------------------------
164# CONSTRUCTOR
165# ----------------------------------------------------------------------
166itcl::body Rappture::VtkVolumeViewer::constructor {args} {
167    set _serverType "vtkvis"
168
169    #DebugOn
170    EnableWaitDialog 900
171
172    # Rebuild event
173    $_dispatcher register !rebuild
174    $_dispatcher dispatch $this !rebuild "[itcl::code $this Rebuild]; list"
175
176    # Resize event
177    $_dispatcher register !resize
178    $_dispatcher dispatch $this !resize "[itcl::code $this DoResize]; list"
179
180    # Legend event
181    $_dispatcher register !legend
182    $_dispatcher dispatch $this !legend "[itcl::code $this RequestLegend]; list"
183
184    # Rotate event
185    $_dispatcher register !rotate
186    $_dispatcher dispatch $this !rotate "[itcl::code $this DoRotate]; list"
187
188    # X-Cutplane event
189    $_dispatcher register !xcutplane
190    $_dispatcher dispatch $this !xcutplane \
191        "[itcl::code $this AdjustSetting -xcutplaneposition]; list"
192
193    # Y-Cutplane event
194    $_dispatcher register !ycutplane
195    $_dispatcher dispatch $this !ycutplane \
196        "[itcl::code $this AdjustSetting -ycutplaneposition]; list"
197
198    # Z-Cutplane event
199    $_dispatcher register !zcutplane
200    $_dispatcher dispatch $this !zcutplane \
201        "[itcl::code $this AdjustSetting -zcutplaneposition]; list"
202
203    #
204    # Populate parser with commands handle incoming requests
205    #
206    $_parser alias image [itcl::code $this ReceiveImage]
207    $_parser alias legend [itcl::code $this ReceiveLegend]
208    $_parser alias dataset [itcl::code $this ReceiveDataset]
209
210    # Initialize the view to some default parameters.
211    array set _view {
212        -ortho    0
213        -qw       0.853553
214        -qx       -0.353553
215        -qy       0.353553
216        -qz       0.146447
217        -xpan     0
218        -ypan     0
219        -zoom     1.0
220    }
221    set _arcball [blt::arcball create 100 100]
222    $_arcball quaternion [ViewToQuaternion]
223
224    array set _settings {
225        -axesvisible            1
226        -axisflymode            static
227        -axislabels             1
228        -axisminorticks         1
229        -background             black
230        -color                  BCGYR
231        -cutplanelighting       1
232        -cutplaneopacity        100
233        -cutplanesvisible       0
234        -legendvisible          1
235        -volumelighting         1
236        -volumematerial         80
237        -volumeopacity          50
238        -volumeoutline          0
239        -volumequality          80
240        -volumevisible          1
241        -xcutplaneposition      50
242        -xcutplanevisible       1
243        -xgrid                  0
244        -ycutplaneposition      50
245        -ycutplanevisible       1
246        -ygrid                  0
247        -zcutplaneposition      50
248        -zcutplanevisible       1
249        -zgrid                  0
250    }
251
252    itk_component add view {
253        canvas $itk_component(plotarea).view \
254            -highlightthickness 0 -borderwidth 0
255    } {
256        usual
257        ignore -highlightthickness -borderwidth -background
258    }
259
260    itk_component add fieldmenu {
261        menu $itk_component(plotarea).menu -bg black -fg white -relief flat \
262            -tearoff 0
263    } {
264        usual
265        ignore -background -foreground -relief -tearoff
266    }
267    set c $itk_component(view)
268    bind $c <Configure> [itcl::code $this EventuallyResize %w %h]
269    bind $c <Control-F1> [itcl::code $this ToggleConsole]
270
271    # Fixes the scrollregion in case we go off screen
272    $c configure -scrollregion [$c bbox all]
273
274    set _map(id) [$c create image 0 0 -anchor nw -image $_image(plot)]
275    set _map(cwidth) -1
276    set _map(cheight) -1
277    set _map(zoom) 1.0
278    set _map(original) ""
279
280    set f [$itk_component(main) component controls]
281    itk_component add reset {
282        button $f.reset -borderwidth 1 -padx 1 -pady 1 \
283            -highlightthickness 0 \
284            -image [Rappture::icon reset-view] \
285            -command [itcl::code $this Zoom reset]
286    } {
287        usual
288        ignore -highlightthickness
289    }
290    pack $itk_component(reset) -side top -padx 2 -pady 2
291    Rappture::Tooltip::for $itk_component(reset) \
292        "Reset the view to the default zoom level"
293
294    itk_component add zoomin {
295        button $f.zin -borderwidth 1 -padx 1 -pady 1 \
296            -highlightthickness 0 \
297            -image [Rappture::icon zoom-in] \
298            -command [itcl::code $this Zoom in]
299    } {
300        usual
301        ignore -highlightthickness
302    }
303    pack $itk_component(zoomin) -side top -padx 2 -pady 2
304    Rappture::Tooltip::for $itk_component(zoomin) "Zoom in"
305
306    itk_component add zoomout {
307        button $f.zout -borderwidth 1 -padx 1 -pady 1 \
308            -highlightthickness 0 \
309            -image [Rappture::icon zoom-out] \
310            -command [itcl::code $this Zoom out]
311    } {
312        usual
313        ignore -highlightthickness
314    }
315    pack $itk_component(zoomout) -side top -padx 2 -pady 2
316    Rappture::Tooltip::for $itk_component(zoomout) "Zoom out"
317
318    itk_component add volume {
319        Rappture::PushButton $f.volume \
320            -onimage [Rappture::icon volume-on] \
321            -offimage [Rappture::icon volume-off] \
322            -variable [itcl::scope _settings(-volumevisible)] \
323            -command [itcl::code $this AdjustSetting -volumevisible]
324    }
325    $itk_component(volume) select
326    Rappture::Tooltip::for $itk_component(volume) \
327        "Don't display the volume"
328    pack $itk_component(volume) -padx 2 -pady 2
329
330    itk_component add cutplane {
331        Rappture::PushButton $f.cutplane \
332            -onimage [Rappture::icon cutbutton] \
333            -offimage [Rappture::icon cutbutton] \
334            -variable [itcl::scope _settings(-cutplanesvisible)] \
335            -command [itcl::code $this AdjustSetting -cutplanesvisible]
336    }
337    Rappture::Tooltip::for $itk_component(cutplane) \
338        "Show/Hide cutplanes"
339    pack $itk_component(cutplane) -padx 2 -pady 2
340
341    if { [catch {
342        BuildViewTab
343        BuildVolumeTab
344        BuildCutplanesTab
345        BuildAxisTab
346        BuildCameraTab
347    } errs] != 0 } {
348        puts stderr errs=$errs
349    }
350
351    # Legend
352    set _image(legend) [image create photo]
353    itk_component add legend {
354        canvas $itk_component(plotarea).legend -width 50 -highlightthickness 0
355    } {
356        usual
357        ignore -highlightthickness
358        rename -background -plotbackground plotBackground Background
359    }
360
361    # Hack around the Tk panewindow.  The problem is that the requested
362    # size of the 3d view isn't set until an image is retrieved from
363    # the server.  So the panewindow uses the tiny size.
364    set w 10000
365    pack forget $itk_component(view)
366    blt::table $itk_component(plotarea) \
367        0,0 $itk_component(view) -fill both -reqwidth $w
368    blt::table configure $itk_component(plotarea) c1 -resize none
369
370    # Bindings for rotation via mouse
371    bind $itk_component(view) <ButtonPress-1> \
372        [itcl::code $this Rotate click %x %y]
373    bind $itk_component(view) <B1-Motion> \
374        [itcl::code $this Rotate drag %x %y]
375    bind $itk_component(view) <ButtonRelease-1> \
376        [itcl::code $this Rotate release %x %y]
377
378    # Bindings for panning via mouse
379    bind $itk_component(view) <ButtonPress-2> \
380        [itcl::code $this Pan click %x %y]
381    bind $itk_component(view) <B2-Motion> \
382        [itcl::code $this Pan drag %x %y]
383    bind $itk_component(view) <ButtonRelease-2> \
384        [itcl::code $this Pan release %x %y]
385
386    #bind $itk_component(view) <ButtonRelease-3> \
387    #    [itcl::code $this Pick %x %y]
388
389    # Bindings for panning via keyboard
390    bind $itk_component(view) <KeyPress-Left> \
391        [itcl::code $this Pan set -10 0]
392    bind $itk_component(view) <KeyPress-Right> \
393        [itcl::code $this Pan set 10 0]
394    bind $itk_component(view) <KeyPress-Up> \
395        [itcl::code $this Pan set 0 -10]
396    bind $itk_component(view) <KeyPress-Down> \
397        [itcl::code $this Pan set 0 10]
398    bind $itk_component(view) <Shift-KeyPress-Left> \
399        [itcl::code $this Pan set -2 0]
400    bind $itk_component(view) <Shift-KeyPress-Right> \
401        [itcl::code $this Pan set 2 0]
402    bind $itk_component(view) <Shift-KeyPress-Up> \
403        [itcl::code $this Pan set 0 -2]
404    bind $itk_component(view) <Shift-KeyPress-Down> \
405        [itcl::code $this Pan set 0 2]
406
407    # Bindings for zoom via keyboard
408    bind $itk_component(view) <KeyPress-Prior> \
409        [itcl::code $this Zoom out]
410    bind $itk_component(view) <KeyPress-Next> \
411        [itcl::code $this Zoom in]
412
413    bind $itk_component(view) <Enter> "focus $itk_component(view)"
414
415    if {[string equal "x11" [tk windowingsystem]]} {
416        # Bindings for zoom via mouse
417        bind $itk_component(view) <4> [itcl::code $this Zoom out]
418        bind $itk_component(view) <5> [itcl::code $this Zoom in]
419    }
420
421    set _image(download) [image create photo]
422
423    eval itk_initialize $args
424    Connect
425}
426
427# ----------------------------------------------------------------------
428# DESTRUCTOR
429# ----------------------------------------------------------------------
430itcl::body Rappture::VtkVolumeViewer::destructor {} {
431    Disconnect
432    image delete $_image(plot)
433    image delete $_image(download)
434    catch { blt::arcball destroy $_arcball }
435}
436
437itcl::body Rappture::VtkVolumeViewer::DoResize {} {
438    if { $_width < 2 } {
439        set _width 500
440    }
441    if { $_height < 2 } {
442        set _height 500
443    }
444    set _start [clock clicks -milliseconds]
445    SendCmd "screen size $_width $_height"
446
447    EventuallyRequestLegend
448    set _resizePending 0
449}
450
451itcl::body Rappture::VtkVolumeViewer::DoRotate {} {
452    SendCmd "camera orient [ViewToQuaternion]"
453    set _rotatePending 0
454}
455
456itcl::body Rappture::VtkVolumeViewer::EventuallyResize { w h } {
457    set _width $w
458    set _height $h
459    $_arcball resize $w $h
460    if { !$_resizePending } {
461        set _resizePending 1
462        $_dispatcher event -after 400 !resize
463    }
464}
465
466itcl::body Rappture::VtkVolumeViewer::EventuallyRequestLegend {} {
467    if { !$_legendPending } {
468        set _legendPending 1
469        $_dispatcher event -idle !legend
470    }
471}
472
473itcl::body Rappture::VtkVolumeViewer::EventuallyRotate { q } {
474    QuaternionToView $q
475    if { !$_rotatePending } {
476        set _rotatePending 1
477        $_dispatcher event -after 100 !rotate
478    }
479}
480
481itcl::body Rappture::VtkVolumeViewer::EventuallySetCutplane { axis args } {
482    if { !$_cutplanePending } {
483        set _cutplanePending 1
484        $_dispatcher event -after 100 !${axis}cutplane
485    }
486}
487
488# ----------------------------------------------------------------------
489# USAGE: add <dataobj> ?<settings>?
490#
491# Clients use this to add a data object to the plot.  The optional
492# <settings> are used to configure the plot.  Allowed settings are
493# -color, -brightness, -width, -linestyle, and -raise.
494# ----------------------------------------------------------------------
495itcl::body Rappture::VtkVolumeViewer::add {dataobj {settings ""}} {
496    DebugTrace "Enter"
497    if { ![IsValidObject $dataobj] } {
498        DebugTrace "Invalid"
499        return;                         # Ignore invalid objects.
500    }
501    array set params {
502        -color auto
503        -width 1
504        -linestyle solid
505        -brightness 0
506        -raise 0
507        -description ""
508        -param ""
509        -type ""
510    }
511    array set params $settings
512
513    if {$params(-color) == "auto" || $params(-color) == "autoreset"} {
514        # can't handle -autocolors yet
515        set params(-color) black
516    }
517    set pos [lsearch -exact $_dlist $dataobj]
518    if {$pos < 0} {
519        lappend _dlist $dataobj
520    }
521    set _obj2ovride($dataobj-color) $params(-color)
522    set _obj2ovride($dataobj-width) $params(-width)
523    set _obj2ovride($dataobj-raise) $params(-raise)
524    $_dispatcher event -idle !rebuild
525}
526
527
528# ----------------------------------------------------------------------
529# USAGE: delete ?<dataobj1> <dataobj2> ...?
530#
531# Clients use this to delete a dataobj from the plot.  If no dataobjs
532# are specified, then all dataobjs are deleted.  No data objects are
533# deleted.  They are only removed from the display list.
534# ----------------------------------------------------------------------
535itcl::body Rappture::VtkVolumeViewer::delete {args} {
536    DebugTrace "Enter"
537    if { [llength $args] == 0} {
538        set args $_dlist
539    }
540    # Delete all specified dataobjs
541    set changed 0
542    foreach dataobj $args {
543        set pos [lsearch -exact $_dlist $dataobj]
544        if { $pos < 0 } {
545            continue;                   # Don't know anything about it.
546        }
547        # Remove it from the dataobj list.
548        set _dlist [lreplace $_dlist $pos $pos]
549        array unset _obj2ovride $dataobj-*
550        array unset _settings $dataobj-*
551        set changed 1
552    }
553    # If anything changed, then rebuild the plot
554    if { $changed } {
555        $_dispatcher event -idle !rebuild
556    }
557}
558
559# ----------------------------------------------------------------------
560# USAGE: get ?-objects?
561# USAGE: get ?-visible?
562# USAGE: get ?-image view?
563#
564# Clients use this to query the list of objects being plotted, in
565# order from bottom to top of this result.  The optional "-image"
566# flag can also request the internal images being shown.
567# ----------------------------------------------------------------------
568itcl::body Rappture::VtkVolumeViewer::get {args} {
569    if {[llength $args] == 0} {
570        set args "-objects"
571    }
572
573    set op [lindex $args 0]
574    switch -- $op {
575        "-objects" {
576            # put the dataobj list in order according to -raise options
577            set dlist {}
578            foreach dataobj $_dlist {
579                if { ![IsValidObject $dataobj] } {
580                    continue
581                }
582                if {[info exists _obj2ovride($dataobj-raise)] &&
583                    $_obj2ovride($dataobj-raise)} {
584                    set dlist [linsert $dlist 0 $dataobj]
585                } else {
586                    lappend dlist $dataobj
587                }
588            }
589            return $dlist
590        }
591        "-visible" {
592            set dlist {}
593            foreach dataobj $_dlist {
594                if { ![IsValidObject $dataobj] } {
595                    continue
596                }
597                if { ![info exists _obj2ovride($dataobj-raise)] } {
598                    # No setting indicates that the object isn't visible.
599                    continue
600                }
601                # Otherwise use the -raise parameter to put the object to
602                # the front of the list.
603                if { $_obj2ovride($dataobj-raise) } {
604                    set dlist [linsert $dlist 0 $dataobj]
605                } else {
606                    lappend dlist $dataobj
607                }
608            }
609            return $dlist
610        }
611        "-image" {
612            if {[llength $args] != 2} {
613                error "wrong # args: should be \"get -image view\""
614            }
615            switch -- [lindex $args end] {
616                view {
617                    return $_image(plot)
618                }
619                default {
620                    error "bad image name \"[lindex $args end]\": should be view"
621                }
622            }
623        }
624        default {
625            error "bad option \"$op\": should be -objects, -visible or -image"
626        }
627    }
628}
629
630# ----------------------------------------------------------------------
631# USAGE: scale ?<data1> <data2> ...?
632#
633# Sets the default limits for the overall plot according to the
634# limits of the data for all of the given <data> objects.  This
635# accounts for all objects--even those not showing on the screen.
636# Because of this, the limits are appropriate for all objects as
637# the user scans through data in the ResultSet viewer.
638# ----------------------------------------------------------------------
639itcl::body Rappture::VtkVolumeViewer::scale {args} {
640    DebugTrace "Enter"
641    array unset _limits
642    array unset _volcomponents
643    set _componentsList ""
644
645    foreach dataobj $args {
646        if { ![$dataobj isvalid] } {
647            continue;                     # Object doesn't contain valid data.
648        }
649        # Determine limits for each axis.
650        foreach axis { x y z } {
651            set lim [$dataobj limits $axis]
652            if { ![info exists _limits($axis)] } {
653                set _limits($axis) $lim
654                continue
655            }
656            foreach {min max} $lim break
657            foreach {amin amax} $_limits($axis) break
658            if { $amin > $min } {
659                set amin $min
660            }
661            if { $amax < $max } {
662                set amax $max
663            }
664            set _limits($axis) [list $amin $amax]
665        }
666        # Determine limits for each field.
667        foreach { fname lim } [$dataobj fieldlimits] {
668            if { ![info exists _limits($fname)] } {
669                set _limits($fname) $lim
670                continue
671            }
672            foreach {min max} $lim break
673            foreach {fmin fmax} $_limits($fname) break
674            if { $fmin > $min } {
675                set fmin $min
676            }
677            if { $fmax < $max } {
678                set fmax $max
679            }
680            set _limits($fname) [list $fmin $fmax]
681        }
682        # Get limits for each component.
683        foreach cname [$dataobj components] {
684            if { ![info exists _volcomponents($cname)] } {
685                lappend _componentsList $cname
686            }
687            lappend _volcomponents($cname) $dataobj-$cname
688            array unset limits
689            array set limits [$dataobj valueLimits $cname]
690            if { ![info exists _limits($cname)] } {
691                set _limits($cname) $limits(v)
692                continue
693            }
694            foreach {min max} $limits(v) break
695            foreach {vmin vmax} $_limits($cname) break
696            if { $vmin > $min } {
697                set vmin $min
698            }
699            if { $vmax < $max } {
700                set vmax $max
701            }
702            set _limits($cname) [list $vmin $vmax]
703        }
704    }
705}
706
707# ----------------------------------------------------------------------
708# USAGE: download coming
709# USAGE: download controls <downloadCommand>
710# USAGE: download now
711#
712# Clients use this method to create a downloadable representation
713# of the plot.  Returns a list of the form {ext string}, where
714# "ext" is the file extension (indicating the type of data) and
715# "string" is the data itself.
716# ----------------------------------------------------------------------
717itcl::body Rappture::VtkVolumeViewer::download {option args} {
718    switch $option {
719        coming {
720            if {[catch {
721                blt::winop snap $itk_component(plotarea) $_image(download)
722            }]} {
723                $_image(download) configure -width 1 -height 1
724                $_image(download) put #000000
725            }
726        }
727        controls {
728            set popup .vtkviewerdownload
729            if { ![winfo exists .vtkviewerdownload] } {
730                set inner [BuildDownloadPopup $popup [lindex $args 0]]
731            } else {
732                set inner [$popup component inner]
733            }
734            set _downloadPopup(image_controls) $inner.image_frame
735            set num [llength [get]]
736            set num [expr {($num == 1) ? "1 result" : "$num results"}]
737            set word [Rappture::filexfer::label downloadWord]
738            $inner.summary configure -text "$word $num in the following format:"
739            update idletasks            ;# Fix initial sizes
740            return $popup
741        }
742        now {
743            set popup .vtkviewerdownload
744            if {[winfo exists .vtkviewerdownload]} {
745                $popup deactivate
746            }
747            switch -- $_downloadPopup(format) {
748                "image" {
749                    return [$this GetImage [lindex $args 0]]
750                }
751                "vtk" {
752                    return [$this GetVtkData [lindex $args 0]]
753                }
754            }
755            return ""
756        }
757        default {
758            error "bad option \"$option\": should be coming, controls, now"
759        }
760    }
761}
762
763# ----------------------------------------------------------------------
764# USAGE: Connect ?<host:port>,<host:port>...?
765#
766# Clients use this method to establish a connection to a new
767# server, or to reestablish a connection to the previous server.
768# Any existing connection is automatically closed.
769# ----------------------------------------------------------------------
770itcl::body Rappture::VtkVolumeViewer::Connect {} {
771    set _hosts [GetServerList "vtkvis"]
772    if { "" == $_hosts } {
773        return 0
774    }
775    set _reset 1
776    set result [VisViewer::Connect $_hosts]
777    if { $result } {
778        if { $_reportClientInfo }  {
779            # Tell the server the viewer, hub, user and session.
780            # Do this immediately on connect before buffering any commands
781            global env
782
783            set info {}
784            set user "???"
785            if { [info exists env(USER)] } {
786                set user $env(USER)
787            }
788            set session "???"
789            if { [info exists env(SESSION)] } {
790                set session $env(SESSION)
791            }
792            lappend info "version" "$Rappture::version"
793            lappend info "build" "$Rappture::build"
794            lappend info "svnurl" "$Rappture::svnurl"
795            lappend info "installdir" "$Rappture::installdir"
796            lappend info "hub" [exec hostname]
797            lappend info "client" "vtkvolumeviewer"
798            lappend info "user" $user
799            lappend info "session" $session
800            SendCmd "clientinfo [list $info]"
801        }
802
803        set w [winfo width $itk_component(view)]
804        set h [winfo height $itk_component(view)]
805        EventuallyResize $w $h
806    }
807    return $result
808}
809
810#
811# isconnected --
812#
813# Indicates if we are currently connected to the visualization server.
814#
815itcl::body Rappture::VtkVolumeViewer::isconnected {} {
816    return [VisViewer::IsConnected]
817}
818
819#
820# disconnect --
821#
822itcl::body Rappture::VtkVolumeViewer::disconnect {} {
823    Disconnect
824    set _reset 1
825}
826
827#
828# Disconnect --
829#
830# Clients use this method to disconnect from the current rendering server.
831#
832itcl::body Rappture::VtkVolumeViewer::Disconnect {} {
833    VisViewer::Disconnect
834
835    $_dispatcher cancel !rebuild
836    $_dispatcher cancel !resize
837    $_dispatcher cancel !rotate
838    $_dispatcher cancel !xcutplane
839    $_dispatcher cancel !ycutplane
840    $_dispatcher cancel !zcutplane
841    $_dispatcher cancel !legend
842    # disconnected -- no more data sitting on server
843    array unset _datasets
844    array unset _colormaps
845    array unset _dataset2style
846
847    set _resizePending 0
848    set _rotatePending 0
849    set _cutplanePending 0
850    set _legendPending 0
851}
852
853# ----------------------------------------------------------------------
854# USAGE: ReceiveImage -bytes <size> -type <type> -token <token>
855#
856# Invoked automatically whenever the "image" command comes in from
857# the rendering server.  Indicates that binary image data with the
858# specified <size> will follow.
859# ----------------------------------------------------------------------
860itcl::body Rappture::VtkVolumeViewer::ReceiveImage { args } {
861    array set info {
862        -token "???"
863        -bytes 0
864        -type image
865    }
866    array set info $args
867    set bytes [ReceiveBytes $info(-bytes)]
868    StopWaiting
869    if { $info(-type) == "image" } {
870        if 0 {
871            set f [open "last.ppm" "w"]
872            fconfigure $f -encoding binary
873            puts -nonewline $f $bytes
874            close $f
875        }
876        $_image(plot) configure -data $bytes
877        #puts stderr "[clock format [clock seconds]]: received image [image width $_image(plot)]x[image height $_image(plot)] image>"
878        if { $_start > 0 } {
879            set finish [clock clicks -milliseconds]
880            #puts stderr "round trip time [expr $finish -$_start] milliseconds"
881            set _start 0
882        }
883    } elseif { $info(type) == "print" } {
884        set tag $this-print-$info(-token)
885        set _hardcopy($tag) $bytes
886    }
887}
888
889#
890# ReceiveDataset --
891#
892itcl::body Rappture::VtkVolumeViewer::ReceiveDataset { args } {
893    if { ![isconnected] } {
894        return
895    }
896    set option [lindex $args 0]
897    switch -- $option {
898        "scalar" {
899            set option [lindex $args 1]
900            switch -- $option {
901                "world" {
902                    foreach { x y z value tag } [lrange $args 2 end] break
903                }
904                "pixel" {
905                    foreach { x y value tag } [lrange $args 2 end] break
906                }
907            }
908        }
909        "vector" {
910            set option [lindex $args 1]
911            switch -- $option {
912                "world" {
913                    foreach { x y z vx vy vz tag } [lrange $args 2 end] break
914                }
915                "pixel" {
916                    foreach { x y vx vy vz tag } [lrange $args 2 end] break
917                }
918            }
919        }
920        "names" {
921            foreach { name } [lindex $args 1] {
922                #puts stderr "Dataset: $name"
923            }
924        }
925        default {
926            error "unknown dataset option \"$option\" from server"
927        }
928    }
929}
930
931# ----------------------------------------------------------------------
932# USAGE: Rebuild
933#
934# Called automatically whenever something changes that affects the
935# data in the widget.  Clears any existing data and rebuilds the
936# widget to display new data.
937# ----------------------------------------------------------------------
938itcl::body Rappture::VtkVolumeViewer::Rebuild {} {
939    set w [winfo width $itk_component(view)]
940    set h [winfo height $itk_component(view)]
941    if { $w < 2 || $h < 2 } {
942        update
943        $_dispatcher event -idle !rebuild
944        return
945    }
946
947    # Turn on buffering of commands to the server.  We don't want to
948    # be preempted by a server disconnect/reconnect (which automatically
949    # generates a new call to Rebuild).
950    StartBufferingCommands
951
952    if { $_width != $w || $_height != $h || $_reset } {
953        set _width $w
954        set _height $h
955        $_arcball resize $w $h
956        DoResize
957    }
958    if { $_reset } {
959        #
960        # Reset the camera and other view parameters
961        #
962        $_arcball quaternion [ViewToQuaternion]
963        if {$_view(-ortho)} {
964            SendCmd "camera mode ortho"
965        } else {
966            SendCmd "camera mode persp"
967        }
968        DoRotate
969        PanCamera
970        set _first ""
971        InitSettings -background \
972            -xgrid -ygrid -zgrid -axisflymode \
973            -axesvisible -axislabels -axisminorticks
974        StopBufferingCommands
975        SendCmd "imgflush"
976        StartBufferingCommands
977    }
978
979    set _first ""
980    # No volumes are active (i.e. in the working set of displayed volumes).
981    # A volume is always invisible if it's not in the working set.  A
982    # volume in the working set may be visible/invisible depending upon the
983    # global visibility value.
984    SendCmd "dataset visible 0"
985    foreach dataobj [get -objects] {
986        if { [info exists _obj2ovride($dataobj-raise)] &&  $_first == "" } {
987            set _first $dataobj
988        }
989        foreach cname [$dataobj components] {
990            set tag $dataobj-$cname
991            if { ![info exists _datasets($tag)] } {
992                set bytes [$dataobj vtkdata $cname]
993                if 0 {
994                    set f [open /tmp/vtkvolume.vtk "w"]
995                    fconfigure $f -translation binary -encoding binary
996                    puts -nonewline $f $bytes
997                    close $f
998                }
999                set length [string length $bytes]
1000                if { $_reportClientInfo }  {
1001                    set info {}
1002                    lappend info "tool_id"       [$dataobj hints toolid]
1003                    lappend info "tool_name"     [$dataobj hints toolname]
1004                    lappend info "tool_title"    [$dataobj hints tooltitle]
1005                    lappend info "tool_command"  [$dataobj hints toolcommand]
1006                    lappend info "tool_revision" [$dataobj hints toolrevision]
1007                    lappend info "dataset_label" [$dataobj hints label]
1008                    lappend info "dataset_size"  $length
1009                    lappend info "dataset_tag"   $tag
1010                    SendCmd "clientinfo [list $info]"
1011                }
1012                SendCmd "dataset add $tag data follows $length"
1013                SendData $bytes
1014                set _datasets($tag) 1
1015                SetObjectStyle $dataobj $cname
1016            }
1017            if { [info exists _obj2ovride($dataobj-raise)] } {
1018                SendCmd "volume visible 1 $tag"
1019            }
1020            break
1021        }
1022    }
1023    if {"" != $_first} {
1024        foreach axis { x y z } {
1025            set label [$_first hints ${axis}label]
1026            if { $label != "" } {
1027                SendCmd [list axis name $axis $label]
1028            }
1029            set units [$_first hints ${axis}units]
1030            if { $units != "" } {
1031                SendCmd [list axis units $axis $units]
1032            }
1033        }
1034        $itk_component(field) choices delete 0 end
1035        $itk_component(fieldmenu) delete 0 end
1036        array unset _fields
1037        set _curFldName ""
1038        foreach cname [$_first components] {
1039            foreach fname [$_first fieldnames $cname] {
1040                if { [info exists _fields($fname)] } {
1041                    continue
1042                }
1043                foreach { label units components } \
1044                    [$_first fieldinfo $fname] break
1045                # Only scalar fields are valid
1046                if {$_allowMultiComponent || $components == 1} {
1047                    $itk_component(field) choices insert end "$fname" "$label"
1048                    $itk_component(fieldmenu) add radiobutton -label "$label" \
1049                        -value $label -variable [itcl::scope _curFldLabel] \
1050                        -selectcolor red \
1051                        -activebackground $itk_option(-plotbackground) \
1052                        -activeforeground $itk_option(-plotforeground) \
1053                        -font "Arial 8" \
1054                        -command [itcl::code $this Combo invoke]
1055                    set _fields($fname) [list $label $units $components]
1056                    if { $_curFldName == "" } {
1057                        set _curFldName $fname
1058                        set _curFldLabel $label
1059                    }
1060                }
1061            }
1062        }
1063        $itk_component(field) value $_curFldLabel
1064    }
1065
1066    InitSettings -color \
1067        -volumevisible \
1068        -volumematerial \
1069        -volumelighting -volumeopacity -volumequality -volumeoutline \
1070        -cutplanesvisible \
1071        -xcutplaneposition -ycutplaneposition -zcutplaneposition \
1072        -xcutplanevisible -ycutplanevisible -zcutplanevisible
1073
1074    if { $_reset } {
1075        SendCmd "camera reset"
1076        SendCmd "camera zoom $_view(-zoom)"
1077        RequestLegend
1078        set _reset 0
1079    }
1080    # Actually write the commands to the server socket.  If it fails, we don't
1081    # care.  We're finished here.
1082    blt::busy hold $itk_component(hull)
1083    StopBufferingCommands
1084    blt::busy release $itk_component(hull)
1085}
1086
1087# ----------------------------------------------------------------------
1088# USAGE: CurrentDatasets ?-all -visible? ?dataobjs?
1089#
1090# Returns a list of server IDs for the current datasets being displayed.  This
1091# is normally a single ID, but it might be a list of IDs if the current data
1092# object has multiple components.
1093# ----------------------------------------------------------------------
1094itcl::body Rappture::VtkVolumeViewer::CurrentDatasets {args} {
1095    set flag [lindex $args 0]
1096    switch -- $flag {
1097        "-all" {
1098            if { [llength $args] > 1 } {
1099                error "CurrentDatasets: can't specify dataobj after \"-all\""
1100            }
1101            set dlist [get -objects]
1102        }
1103        "-visible" {
1104            if { [llength $args] > 1 } {
1105                set dlist {}
1106                set args [lrange $args 1 end]
1107                foreach dataobj $args {
1108                    if { [info exists _obj2ovride($dataobj-raise)] } {
1109                        lappend dlist $dataobj
1110                    }
1111                }
1112            } else {
1113                set dlist [get -visible]
1114            }
1115        }
1116        default {
1117            set dlist $args
1118        }
1119    }
1120    set rlist ""
1121    foreach dataobj $dlist {
1122        foreach comp [$dataobj components] {
1123            set tag $dataobj-$comp
1124            if { [info exists _datasets($tag)] && $_datasets($tag) } {
1125                lappend rlist $tag
1126            }
1127        }
1128    }
1129    return $rlist
1130}
1131
1132# ----------------------------------------------------------------------
1133# USAGE: Zoom in
1134# USAGE: Zoom out
1135# USAGE: Zoom reset
1136#
1137# Called automatically when the user clicks on one of the zoom
1138# controls for this widget.  Changes the zoom for the current view.
1139# ----------------------------------------------------------------------
1140itcl::body Rappture::VtkVolumeViewer::Zoom {option} {
1141    switch -- $option {
1142        "in" {
1143            set _view(-zoom) [expr {$_view(-zoom)*1.25}]
1144            SendCmd "camera zoom $_view(-zoom)"
1145        }
1146        "out" {
1147            set _view(-zoom) [expr {$_view(-zoom)*0.8}]
1148            SendCmd "camera zoom $_view(-zoom)"
1149        }
1150        "reset" {
1151            array set _view {
1152                -qw      0.853553
1153                -qx      -0.353553
1154                -qy      0.353553
1155                -qz      0.146447
1156                -xpan    0
1157                -ypan    0
1158                -zoom    1.0
1159            }
1160            if { $_first != "" } {
1161                set location [$_first hints camera]
1162                if { $location != "" } {
1163                    array set _view $location
1164                }
1165            }
1166            $_arcball quaternion [ViewToQuaternion]
1167            DoRotate
1168            SendCmd "camera reset"
1169        }
1170    }
1171}
1172
1173itcl::body Rappture::VtkVolumeViewer::PanCamera {} {
1174    set x $_view(-xpan)
1175    set y $_view(-ypan)
1176    SendCmd "camera pan $x $y"
1177}
1178
1179# ----------------------------------------------------------------------
1180# USAGE: Rotate click <x> <y>
1181# USAGE: Rotate drag <x> <y>
1182# USAGE: Rotate release <x> <y>
1183#
1184# Called automatically when the user clicks/drags/releases in the
1185# plot area.  Moves the plot according to the user's actions.
1186# ----------------------------------------------------------------------
1187itcl::body Rappture::VtkVolumeViewer::Rotate {option x y} {
1188    switch -- $option {
1189        "click" {
1190            $itk_component(view) configure -cursor fleur
1191            set _click(x) $x
1192            set _click(y) $y
1193        }
1194        "drag" {
1195            if {[array size _click] == 0} {
1196                Rotate click $x $y
1197            } else {
1198                set w [winfo width $itk_component(view)]
1199                set h [winfo height $itk_component(view)]
1200                if {$w <= 0 || $h <= 0} {
1201                    return
1202                }
1203
1204                if {[catch {
1205                    # this fails sometimes for no apparent reason
1206                    set dx [expr {double($x-$_click(x))/$w}]
1207                    set dy [expr {double($y-$_click(y))/$h}]
1208                }]} {
1209                    return
1210                }
1211                if { $dx == 0 && $dy == 0 } {
1212                    return
1213                }
1214                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1215                EventuallyRotate $q
1216                set _click(x) $x
1217                set _click(y) $y
1218            }
1219        }
1220        "release" {
1221            Rotate drag $x $y
1222            $itk_component(view) configure -cursor ""
1223            catch {unset _click}
1224        }
1225        default {
1226            error "bad option \"$option\": should be click, drag, release"
1227        }
1228    }
1229}
1230
1231itcl::body Rappture::VtkVolumeViewer::Pick {x y} {
1232    foreach tag [CurrentDatasets -visible] {
1233        SendCmd "dataset getscalar pixel $x $y $tag"
1234    }
1235}
1236
1237# ----------------------------------------------------------------------
1238# USAGE: $this Pan click x y
1239#        $this Pan drag x y
1240#        $this Pan release x y
1241#
1242# Called automatically when the user clicks on one of the zoom
1243# controls for this widget.  Changes the zoom for the current view.
1244# ----------------------------------------------------------------------
1245itcl::body Rappture::VtkVolumeViewer::Pan {option x y} {
1246    switch -- $option {
1247        "set" {
1248            set w [winfo width $itk_component(view)]
1249            set h [winfo height $itk_component(view)]
1250            set x [expr $x / double($w)]
1251            set y [expr $y / double($h)]
1252            set _view(-xpan) [expr $_view(-xpan) + $x]
1253            set _view(-ypan) [expr $_view(-ypan) + $y]
1254            PanCamera
1255            return
1256        }
1257        "click" {
1258            set _click(x) $x
1259            set _click(y) $y
1260            $itk_component(view) configure -cursor hand1
1261        }
1262        "drag" {
1263            if { ![info exists _click(x)] } {
1264                set _click(x) $x
1265            }
1266            if { ![info exists _click(y)] } {
1267                set _click(y) $y
1268            }
1269            set w [winfo width $itk_component(view)]
1270            set h [winfo height $itk_component(view)]
1271            set dx [expr ($_click(x) - $x)/double($w)]
1272            set dy [expr ($_click(y) - $y)/double($h)]
1273            set _click(x) $x
1274            set _click(y) $y
1275            set _view(-xpan) [expr $_view(-xpan) - $dx]
1276            set _view(-ypan) [expr $_view(-ypan) - $dy]
1277            PanCamera
1278        }
1279        "release" {
1280            Pan drag $x $y
1281            $itk_component(view) configure -cursor ""
1282        }
1283        default {
1284            error "unknown option \"$option\": should set, click, drag, or release"
1285        }
1286    }
1287}
1288
1289# ----------------------------------------------------------------------
1290# USAGE: InitSettings <what> ?<value>?
1291#
1292# Used internally to update rendering settings whenever parameters
1293# change in the popup settings panel.  Sends the new settings off
1294# to the back end.
1295# ----------------------------------------------------------------------
1296itcl::body Rappture::VtkVolumeViewer::InitSettings { args } {
1297    foreach spec $args {
1298        if { [info exists _settings($_first${spec})] } {
1299            # Reset global setting with dataobj specific setting
1300            set _settings($spec) $_settings($_first${spec})
1301        }
1302        AdjustSetting $spec
1303    }
1304}
1305
1306#
1307# AdjustSetting --
1308#
1309# Changes/updates a specific setting in the widget.  There are
1310# usually user-setable option.  Commands are sent to the render
1311# server.
1312#
1313itcl::body Rappture::VtkVolumeViewer::AdjustSetting {what {value ""}} {
1314    if { ![isconnected] } {
1315        return
1316    }
1317    switch -- $what {
1318        "-background" {
1319            set bgcolor [$itk_component(background) value]
1320            set _settings($what) $bgcolor
1321            array set fgcolors {
1322                "black" "white"
1323                "white" "black"
1324                "grey"  "black"
1325            }
1326            configure -plotbackground $bgcolor \
1327                -plotforeground $fgcolors($bgcolor)
1328            $itk_component(view) delete "legend"
1329            DrawLegend
1330        }
1331        "-volumeoutline" {
1332            set bool $_settings($what)
1333            SendCmd "outline visible 0"
1334            foreach tag [CurrentDatasets -visible] {
1335                SendCmd "outline visible $bool $tag"
1336            }
1337        }
1338        "-legendvisible" {
1339            DrawLegend
1340        }
1341        "-volumevisible" {
1342            set bool $_settings($what)
1343            foreach tag [CurrentDatasets -visible] {
1344                SendCmd "volume visible $bool $tag"
1345            }
1346            if { $bool } {
1347                Rappture::Tooltip::for $itk_component(volume) \
1348                    "Hide the volume"
1349            } else {
1350                Rappture::Tooltip::for $itk_component(volume) \
1351                    "Show the volume"
1352            }
1353        }
1354        "-volumematerial" {
1355            set val $_settings($what)
1356            set diffuse [expr {0.01*$val}]
1357            set specular [expr {0.01*$val}]
1358            #set power [expr {sqrt(160*$val+1.0)}]
1359            set power [expr {$val+1.0}]
1360            foreach tag [CurrentDatasets -visible] {
1361                SendCmd "volume shading diffuse $diffuse $tag"
1362                SendCmd "volume shading specular $specular $power $tag"
1363            }
1364        }
1365        "-volumelighting" {
1366            set bool $_settings($what)
1367            foreach tag [CurrentDatasets -visible] {
1368                SendCmd "volume lighting $bool $tag"
1369            }
1370        }
1371        "-volumeopacity" {
1372            set val $_settings($what)
1373            set val [expr {0.01*$val}]
1374            foreach tag [CurrentDatasets -visible] {
1375                SendCmd "volume opacity $val $tag"
1376            }
1377        }
1378        "-volumequality" {
1379            set val $_settings($what)
1380            set val [expr {0.01*$val}]
1381            foreach tag [CurrentDatasets -visible] {
1382                SendCmd "volume quality $val $tag"
1383            }
1384        }
1385        "-axesvisible" {
1386            set bool $_settings($what)
1387            SendCmd "axis visible all $bool"
1388        }
1389        "-axislabels" {
1390            set bool $_settings($what)
1391            SendCmd "axis labels all $bool"
1392        }
1393        "-axisminorticks" {
1394            set bool $_settings($what)
1395            SendCmd "axis minticks all $bool"
1396        }
1397        "-xgrid" - "-ygrid" - "-zgrid" {
1398            set axis [string range $what 1 1]
1399            set bool $_settings($what)
1400            SendCmd "axis grid $axis $bool"
1401        }
1402        "-axisflymode" {
1403            set mode [$itk_component(axismode) value]
1404            set mode [$itk_component(axismode) translate $mode]
1405            set _settings($what) $mode
1406            SendCmd "axis flymode $mode"
1407        }
1408        "-cutplanesvisible" {
1409            set bool $_settings($what)
1410            foreach dataset [CurrentDatasets -visible] {
1411                SendCmd "$_cutplaneCmd visible $bool $dataset"
1412            }
1413        }
1414        "-cutplanelighting" {
1415            set bool $_settings($what)
1416            foreach dataset [CurrentDatasets -visible] {
1417                if {$_cutplaneCmd != "imgcutplane"} {
1418                    SendCmd "$_cutplaneCmd lighting $bool $dataset"
1419                } else {
1420                    if {$bool} {
1421                        set ambient 0.0
1422                        set diffuse 1.0
1423                    } else {
1424                        set ambient 1.0
1425                        set diffuse 0.0
1426                    }
1427                    SendCmd "imgcutplane material $ambient $diffuse $dataset"
1428                }
1429            }
1430        }
1431        "-cutplaneopacity" {
1432            set val $_settings($what)
1433            set sval [expr { 0.01 * double($val) }]
1434            foreach dataset [CurrentDatasets -visible] {
1435                SendCmd "$_cutplaneCmd opacity $sval $dataset"
1436            }
1437        }
1438        "-xcutplanevisible" - "-ycutplanevisible" - "-zcutplanevisible" {
1439            set axis [string range $what 1 1]
1440            set bool $_settings($what)
1441            if { $bool } {
1442                $itk_component(${axis}CutScale) configure -state normal \
1443                    -troughcolor white
1444            } else {
1445                $itk_component(${axis}CutScale) configure -state disabled \
1446                    -troughcolor grey82
1447            }
1448            foreach dataset [CurrentDatasets -visible] {
1449                SendCmd "$_cutplaneCmd axis $axis $bool $dataset"
1450            }
1451        }
1452        "-xcutplaneposition" - "-ycutplaneposition" - "-zcutplaneposition" {
1453            set axis [string range $what 1 1]
1454            set pos [expr $_settings($what) * 0.01]
1455            foreach dataset [CurrentDatasets -visible] {
1456                SendCmd "$_cutplaneCmd slice ${axis} ${pos} $dataset"
1457            }
1458            set _cutplanePending 0
1459        }
1460        "-color" {
1461            set color [$itk_component(colormap) value]
1462            set _settings($what) $color
1463            foreach dataset [CurrentDatasets -visible $_first] {
1464                foreach {dataobj comp} [split $dataset -] break
1465                ChangeColormap $dataobj $comp $color
1466            }
1467            EventuallyRequestLegend
1468        }
1469        "-field" {
1470            set label [$itk_component(field) value]
1471            set fname [$itk_component(field) translate $label]
1472            set _settings($what) $fname
1473            if { [info exists _fields($fname)] } {
1474                foreach { label units components } $_fields($fname) break
1475                if { !$_allowMultiComponent && $components > 1 } {
1476                    puts stderr "Can't use a vector field in a volume"
1477                    return
1478                } else {
1479                    if { $components > 1 } {
1480                        set _colorMode vmag
1481                    } else {
1482                        set _colorMode scalar
1483                    }
1484                }
1485                set _curFldName $fname
1486                set _curFldLabel $label
1487            } else {
1488                puts stderr "unknown field \"$fname\""
1489                return
1490            }
1491            foreach dataset [CurrentDatasets -visible $_first] {
1492                #SendCmd "$_cutplaneCmd colormode $_colorMode $_curFldName $dataset"
1493                SendCmd "dataset scalar $_curFldName $dataset"
1494            }
1495            SendCmd "camera reset"
1496            DrawLegend
1497        }
1498        default {
1499            error "don't know how to fix $what"
1500        }
1501    }
1502}
1503
1504#
1505# RequestLegend --
1506#
1507# Request a new legend from the server.  The size of the legend
1508# is determined from the height of the canvas.
1509#
1510itcl::body Rappture::VtkVolumeViewer::RequestLegend {} {
1511    set _legendPending 0
1512    set font "Arial 8"
1513    set lineht [font metrics $font -linespace]
1514    set w 12
1515    set h [expr {$_height - 3 * ($lineht + 2)}]
1516    if { $h < 1 } {
1517        return
1518    }
1519    # Set the legend on the first dataset.
1520    foreach dataset [CurrentDatasets -visible $_first] {
1521        foreach {dataobj comp} [split $dataset -] break
1522        if { [info exists _dataset2style($dataset)] } {
1523            #SendCmd "legend $_dataset2style($dataset) $_colorMode $_curFldName {} $w $h 0"
1524            SendCmd "legend2 $_dataset2style($dataset) $w $h"
1525            break;
1526        }
1527    }
1528}
1529
1530#
1531# ChangeColormap --
1532#
1533itcl::body Rappture::VtkVolumeViewer::ChangeColormap {dataobj comp color} {
1534    set tag $dataobj-$comp
1535    if { ![info exist _style($tag)] } {
1536        error "no initial colormap"
1537    }
1538    array set style $_style($tag)
1539    set style(-color) $color
1540    set _style($tag) [array get style]
1541    SetColormap $dataobj $comp
1542}
1543
1544#
1545# SetColormap --
1546#
1547itcl::body Rappture::VtkVolumeViewer::SetColormap { dataobj comp } {
1548    array set style {
1549        -color BCGYR
1550        -levels 6
1551    }
1552    set tag $dataobj-$comp
1553    if { ![info exists _initialStyle($tag)] } {
1554        # Save the initial component style.
1555        set _initialStyle($tag) [$dataobj style $comp]
1556    }
1557
1558    # Override defaults with initial style defined in xml.
1559    array set style $_initialStyle($tag)
1560
1561    if { ![info exists _style($tag)] } {
1562        set _style($tag) [array get style]
1563    }
1564    # Override initial style with current style.
1565    array set style $_style($tag)
1566
1567    set name "$style(-color):$style(-levels)"
1568    if { ![info exists _colormaps($name)] } {
1569        BuildColormap $name [array get style]
1570        set _colormaps($name) 1
1571    }
1572    if { ![info exists _dataset2style($tag)] ||
1573         $_dataset2style($tag) != $name } {
1574        SendCmd "volume colormap $name $tag"
1575        SendCmd "$_cutplaneCmd colormap $name-opaque $tag"
1576        set _dataset2style($tag) $name
1577    }
1578}
1579
1580#
1581# BuildColormap --
1582#
1583# Alpha map is in the format: normalized_value opacity midpoint sharpness
1584#
1585itcl::body Rappture::VtkVolumeViewer::BuildColormap { name styles } {
1586    array set style $styles
1587    set cmap [ColorsToColormap $style(-color)]
1588    if { [llength $cmap] == 0 } {
1589        set cmap "0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0"
1590    }
1591
1592    set amap "0.0 0.0 0.5 0.0 1.0 1.0 0.5 0.0"
1593    set opaqueAmap "0.0 1.0 1.0 1.0"
1594    SendCmd [list colormap define $name $cmap -spline $amap]
1595    SendCmd [list colormap define $name-opaque $cmap $opaqueAmap]
1596}
1597
1598# ----------------------------------------------------------------------
1599# CONFIGURATION OPTION: -plotbackground
1600# ----------------------------------------------------------------------
1601itcl::configbody Rappture::VtkVolumeViewer::plotbackground {
1602    if { [isconnected] } {
1603        set color $itk_option(-plotbackground)
1604        set rgb [Color2RGB $color]
1605        SendCmd "screen bgcolor $rgb"
1606        $itk_component(legend) configure -background $color
1607    }
1608}
1609
1610# ----------------------------------------------------------------------
1611# CONFIGURATION OPTION: -plotforeground
1612# ----------------------------------------------------------------------
1613itcl::configbody Rappture::VtkVolumeViewer::plotforeground {
1614    if { [isconnected] } {
1615        set color $itk_option(-plotforeground)
1616        set rgb [Color2RGB $color]
1617        SendCmd "axis color all $rgb"
1618        SendCmd "outline color $rgb"
1619        SendCmd "$_cutplaneCmd color $rgb"
1620        $itk_component(legend) itemconfigure labels -fill $color
1621        $itk_component(legend) itemconfigure limits -fill $color
1622    }
1623}
1624
1625itcl::body Rappture::VtkVolumeViewer::BuildViewTab {} {
1626    set font [option get $itk_component(hull) font Font]
1627
1628    set inner [$itk_component(main) insert end \
1629        -title "View Settings" \
1630        -icon [Rappture::icon wrench]]
1631    $inner configure -borderwidth 4
1632
1633    checkbutton $inner.axes \
1634        -text "Axes" \
1635        -variable [itcl::scope _settings(-axesvisible)] \
1636        -command [itcl::code $this AdjustSetting -axesvisible] \
1637        -font $font
1638
1639    checkbutton $inner.outline \
1640        -text "Outline" \
1641        -variable [itcl::scope _settings(-volumeoutline)] \
1642        -command [itcl::code $this AdjustSetting -volumeoutline] \
1643        -font $font
1644
1645    checkbutton $inner.legend \
1646        -text "Legend" \
1647        -variable [itcl::scope _settings(-legendvisible)] \
1648        -command [itcl::code $this AdjustSetting -legendvisible] \
1649        -font $font
1650
1651    checkbutton $inner.volume \
1652        -text "Volume" \
1653        -variable [itcl::scope _settings(-volumevisible)] \
1654        -command [itcl::code $this AdjustSetting -volumevisible] \
1655        -font $font
1656
1657    label $inner.background_l -text "Background" -font $font
1658    itk_component add background {
1659        Rappture::Combobox $inner.background -width 10 -editable 0
1660    }
1661    $inner.background choices insert end \
1662        "black" "black" \
1663        "white" "white" \
1664        "grey"  "grey"
1665
1666    $itk_component(background) value $_settings(-background)
1667    bind $inner.background <<Value>> \
1668        [itcl::code $this AdjustSetting -background]
1669
1670    blt::table $inner \
1671        0,0 $inner.axes -cspan 2 -anchor w \
1672        1,0 $inner.outline -cspan 2 -anchor w \
1673        2,0 $inner.volume -cspan 2 -anchor w \
1674        3,0 $inner.legend -cspan 2 -anchor w \
1675        4,0 $inner.background_l -anchor e -pady 2 \
1676        4,1 $inner.background -fill x
1677
1678    blt::table configure $inner r* -resize none
1679    blt::table configure $inner r5 -resize expand
1680}
1681
1682itcl::body Rappture::VtkVolumeViewer::BuildVolumeTab {} {
1683    set font [option get $itk_component(hull) font Font]
1684    #set bfont [option get $itk_component(hull) boldFont Font]
1685    set bfont "Arial 9 bold"
1686
1687    set inner [$itk_component(main) insert end \
1688        -title "Volume Settings" \
1689        -icon [Rappture::icon volume-on]]
1690    $inner configure -borderwidth 4
1691
1692    checkbutton $inner.visibility \
1693        -text "Visible" \
1694        -font $font \
1695        -variable [itcl::scope _settings(-volumevisible)] \
1696        -command [itcl::code $this AdjustSetting -volumevisible]
1697
1698    checkbutton $inner.lighting \
1699        -text "Enable Lighting" \
1700        -font $font \
1701        -variable [itcl::scope _settings(-volumelighting)] \
1702        -command [itcl::code $this AdjustSetting -volumelighting]
1703
1704    label $inner.dim_l -text "Dim" -font $font
1705    ::scale $inner.material -from 0 -to 100 -orient horizontal \
1706        -variable [itcl::scope _settings(-volumematerial)] \
1707        -showvalue off \
1708        -command [itcl::code $this AdjustSetting -volumematerial]
1709    label $inner.bright_l -text "Bright" -font $font
1710
1711    label $inner.opacity_l -text "Opacity" -font $font
1712    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1713        -variable [itcl::scope _settings(-volumeopacity)] \
1714        -showvalue off \
1715        -command [itcl::code $this AdjustSetting -volumeopacity]
1716
1717    label $inner.quality_l -text "Quality" -font $font
1718    ::scale $inner.quality -from 0 -to 100 -orient horizontal \
1719        -variable [itcl::scope _settings(-volumequality)] \
1720        -showvalue off \
1721        -command [itcl::code $this AdjustSetting -volumequality]
1722
1723    label $inner.field_l -text "Field" -font $font
1724    itk_component add field {
1725        Rappture::Combobox $inner.field -editable 0
1726    }
1727    bind $inner.field <<Value>> \
1728        [itcl::code $this AdjustSetting -field]
1729
1730    label $inner.colormap_l -text "Colormap" -font $font
1731    itk_component add colormap {
1732        Rappture::Combobox $inner.colormap -editable 0
1733    }
1734    $inner.colormap choices insert end [GetColormapList]
1735    bind $inner.colormap <<Value>> \
1736        [itcl::code $this AdjustSetting -color]
1737    $itk_component(colormap) value $_settings(-color)
1738
1739    blt::table $inner \
1740        0,0 $inner.field_l -anchor w -pady 2 \
1741        0,1 $inner.field -fill x -pady 2 -cspan 3 \
1742        1,0 $inner.visibility -anchor w -pady 2 -cspan 4 \
1743        2,0 $inner.lighting -anchor w -pady 2 -cspan 4 \
1744        3,0 $inner.dim_l -anchor e -pady 2 \
1745        3,1 $inner.material -fill x -pady 2 -cspan 2 \
1746        3,3 $inner.bright_l -anchor w -pady 2 \
1747        4,0 $inner.opacity_l -anchor w -pady 2 -cspan 4 \
1748        5,0 $inner.opacity -fill x -pady 2 -cspan 4 \
1749        6,0 $inner.quality_l -anchor w -pady 2 -cspan 4 \
1750        7,0 $inner.quality -fill x -pady 2 -cspan 4 \
1751        8,0 $inner.colormap_l -anchor w -pady 2 \
1752        8,1 $inner.colormap -fill x -pady 2 -cspan 3
1753
1754    blt::table configure $inner r* c0 c1 c3 -resize none
1755    blt::table configure $inner r9 c2 -resize expand
1756}
1757
1758itcl::body Rappture::VtkVolumeViewer::BuildAxisTab {} {
1759    set font [option get $itk_component(hull) font Font]
1760
1761    set inner [$itk_component(main) insert end \
1762        -title "Axis Settings" \
1763        -icon [Rappture::icon axis2]]
1764    $inner configure -borderwidth 4
1765
1766    checkbutton $inner.visible \
1767        -text "Axes" \
1768        -variable [itcl::scope _settings(-axesvisible)] \
1769        -command [itcl::code $this AdjustSetting -axesvisible] \
1770        -font $font
1771
1772    checkbutton $inner.labels \
1773        -text "Axis Labels" \
1774        -variable [itcl::scope _settings(-axislabels)] \
1775        -command [itcl::code $this AdjustSetting -axislabels] \
1776        -font $font
1777    label $inner.grid_l -text "Grid" -font $font
1778    checkbutton $inner.xgrid \
1779        -text "X" \
1780        -variable [itcl::scope _settings(-xgrid)] \
1781        -command [itcl::code $this AdjustSetting -xgrid] \
1782        -font $font
1783    checkbutton $inner.ygrid \
1784        -text "Y" \
1785        -variable [itcl::scope _settings(-ygrid)] \
1786        -command [itcl::code $this AdjustSetting -ygrid] \
1787        -font $font
1788    checkbutton $inner.zgrid \
1789        -text "Z" \
1790        -variable [itcl::scope _settings(-zgrid)] \
1791        -command [itcl::code $this AdjustSetting -zgrid] \
1792        -font $font
1793    checkbutton $inner.minorticks \
1794        -text "Minor Ticks" \
1795        -variable [itcl::scope _settings(-axisminorticks)] \
1796        -command [itcl::code $this AdjustSetting -axisminorticks] \
1797        -font $font
1798
1799    label $inner.mode_l -text "Mode" -font $font
1800
1801    itk_component add axismode {
1802        Rappture::Combobox $inner.mode -width 10 -editable 0
1803    }
1804    $inner.mode choices insert end \
1805        "static_triad"    "static" \
1806        "closest_triad"   "closest" \
1807        "furthest_triad"  "farthest" \
1808        "outer_edges"     "outer"
1809    $itk_component(axismode) value $_settings(-axisflymode)
1810    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting -axisflymode]
1811
1812    blt::table $inner \
1813        0,0 $inner.visible -anchor w -cspan 4 \
1814        1,0 $inner.labels -anchor w -cspan 4 \
1815        2,0 $inner.minorticks -anchor w -cspan 4 \
1816        4,0 $inner.grid_l -anchor w \
1817        4,1 $inner.xgrid -anchor w \
1818        4,2 $inner.ygrid -anchor w \
1819        4,3 $inner.zgrid -anchor w \
1820        5,0 $inner.mode_l -anchor w -padx { 2 0 } \
1821        5,1 $inner.mode -fill x -cspan 3
1822
1823    blt::table configure $inner r* c* -resize none
1824    blt::table configure $inner r7 c6 -resize expand
1825    blt::table configure $inner r3 -height 0.125i
1826}
1827
1828itcl::body Rappture::VtkVolumeViewer::BuildCameraTab {} {
1829    set font [option get $itk_component(hull) font Font]
1830    set inner [$itk_component(main) insert end \
1831        -title "Camera Settings" \
1832        -icon [Rappture::icon camera]]
1833    $inner configure -borderwidth 4
1834
1835    label $inner.view_l -text "view" -font $font
1836    set f [frame $inner.view]
1837    foreach side { front back left right top bottom } {
1838        button $f.$side  -image [Rappture::icon view$side] \
1839            -command [itcl::code $this SetOrientation $side]
1840        Rappture::Tooltip::for $f.$side "Change the view to $side"
1841        pack $f.$side -side left
1842    }
1843    blt::table $inner \
1844        0,0 $inner.view_l -anchor e -pady 2 \
1845        0,1 $inner.view -anchor w -pady 2
1846    blt::table configure $inner r0 -resize none
1847
1848    set row 1
1849    set labels { qx qy qz qw xpan ypan zoom }
1850    foreach tag $labels {
1851        label $inner.${tag}label -text $tag -font $font
1852        entry $inner.${tag} -font $font  -bg white \
1853            -textvariable [itcl::scope _view(-$tag)]
1854        bind $inner.${tag} <Return> \
1855            [itcl::code $this camera set -${tag}]
1856        bind $inner.${tag} <KP_Enter> \
1857            [itcl::code $this camera set -${tag}]
1858        blt::table $inner \
1859            $row,0 $inner.${tag}label -anchor e -pady 2 \
1860            $row,1 $inner.${tag} -anchor w -pady 2
1861        blt::table configure $inner r$row -resize none
1862        incr row
1863    }
1864    checkbutton $inner.ortho \
1865        -text "Orthographic Projection" \
1866        -variable [itcl::scope _view(-ortho)] \
1867        -command [itcl::code $this camera set -ortho] \
1868        -font $font
1869    blt::table $inner \
1870            $row,0 $inner.ortho -cspan 2 -anchor w -pady 2
1871    blt::table configure $inner r$row -resize none
1872    incr row
1873
1874    blt::table configure $inner c0 c1 -resize none
1875    blt::table configure $inner c2 -resize expand
1876    blt::table configure $inner r$row -resize expand
1877}
1878
1879itcl::body Rappture::VtkVolumeViewer::BuildCutplanesTab {} {
1880    set font [option get $itk_component(hull) font Font]
1881
1882    set inner [$itk_component(main) insert end \
1883        -title "Cutplane Settings" \
1884        -icon [Rappture::icon cutbutton]]
1885
1886    $inner configure -borderwidth 4
1887
1888    checkbutton $inner.visible \
1889        -text "Show Cutplanes" \
1890        -variable [itcl::scope _settings(-cutplanesvisible)] \
1891        -command [itcl::code $this AdjustSetting -cutplanesvisible] \
1892        -font $font
1893
1894    checkbutton $inner.lighting \
1895        -text "Enable Lighting" \
1896        -variable [itcl::scope _settings(-cutplanelighting)] \
1897        -command [itcl::code $this AdjustSetting -cutplanelighting] \
1898        -font $font
1899
1900    label $inner.opacity_l -text "Opacity" -font $font
1901    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1902        -variable [itcl::scope _settings(-cutplaneopacity)] \
1903        -width 10 \
1904        -showvalue off \
1905        -command [itcl::code $this AdjustSetting -cutplaneopacity]
1906    $inner.opacity set $_settings(-cutplaneopacity)
1907
1908    # X-value slicer...
1909    itk_component add xCutButton {
1910        Rappture::PushButton $inner.xbutton \
1911            -onimage [Rappture::icon x-cutplane] \
1912            -offimage [Rappture::icon x-cutplane] \
1913            -command [itcl::code $this AdjustSetting -xcutplanevisible] \
1914            -variable [itcl::scope _settings(-xcutplanevisible)]
1915    }
1916    Rappture::Tooltip::for $itk_component(xCutButton) \
1917        "Toggle the X-axis cutplane on/off"
1918    $itk_component(xCutButton) select
1919
1920    itk_component add xCutScale {
1921        ::scale $inner.xval -from 100 -to 0 \
1922            -width 10 -orient vertical -showvalue 1 \
1923            -borderwidth 1 -highlightthickness 0 \
1924            -command [itcl::code $this EventuallySetCutplane x] \
1925            -variable [itcl::scope _settings(-xcutplaneposition)]
1926    } {
1927        usual
1928        ignore -borderwidth -highlightthickness
1929    }
1930    # Set the default cutplane value before disabling the scale.
1931    $itk_component(xCutScale) set 50
1932    $itk_component(xCutScale) configure -state disabled
1933    Rappture::Tooltip::for $itk_component(xCutScale) \
1934        "@[itcl::code $this Slice tooltip x]"
1935
1936    # Y-value slicer...
1937    itk_component add yCutButton {
1938        Rappture::PushButton $inner.ybutton \
1939            -onimage [Rappture::icon y-cutplane] \
1940            -offimage [Rappture::icon y-cutplane] \
1941            -command [itcl::code $this AdjustSetting -ycutplanevisible] \
1942            -variable [itcl::scope _settings(-ycutplanevisible)]
1943    }
1944    Rappture::Tooltip::for $itk_component(yCutButton) \
1945        "Toggle the Y-axis cutplane on/off"
1946    $itk_component(yCutButton) select
1947
1948    itk_component add yCutScale {
1949        ::scale $inner.yval -from 100 -to 0 \
1950            -width 10 -orient vertical -showvalue 1 \
1951            -borderwidth 1 -highlightthickness 0 \
1952            -command [itcl::code $this EventuallySetCutplane y] \
1953            -variable [itcl::scope _settings(-ycutplaneposition)]
1954    } {
1955        usual
1956        ignore -borderwidth -highlightthickness
1957    }
1958    Rappture::Tooltip::for $itk_component(yCutScale) \
1959        "@[itcl::code $this Slice tooltip y]"
1960    # Set the default cutplane value before disabling the scale.
1961    $itk_component(yCutScale) set 50
1962    $itk_component(yCutScale) configure -state disabled
1963
1964    # Z-value slicer...
1965    itk_component add zCutButton {
1966        Rappture::PushButton $inner.zbutton \
1967            -onimage [Rappture::icon z-cutplane] \
1968            -offimage [Rappture::icon z-cutplane] \
1969            -command [itcl::code $this AdjustSetting -zcutplanevisible] \
1970            -variable [itcl::scope _settings(-zcutplanevisible)]
1971    }
1972    Rappture::Tooltip::for $itk_component(zCutButton) \
1973        "Toggle the Z-axis cutplane on/off"
1974    $itk_component(zCutButton) select
1975
1976    itk_component add zCutScale {
1977        ::scale $inner.zval -from 100 -to 0 \
1978            -width 10 -orient vertical -showvalue 1 \
1979            -borderwidth 1 -highlightthickness 0 \
1980            -command [itcl::code $this EventuallySetCutplane z] \
1981            -variable [itcl::scope _settings(-zcutplaneposition)]
1982    } {
1983        usual
1984        ignore -borderwidth -highlightthickness
1985    }
1986    $itk_component(zCutScale) set 50
1987    $itk_component(zCutScale) configure -state disabled
1988    Rappture::Tooltip::for $itk_component(zCutScale) \
1989        "@[itcl::code $this Slice tooltip z]"
1990
1991    blt::table $inner \
1992        0,0 $inner.visible              -anchor w -pady 2 -cspan 4 \
1993        1,0 $inner.lighting             -anchor w -pady 2 -cspan 4 \
1994        2,0 $inner.opacity_l            -anchor w -pady 2 -cspan 3 \
1995        3,0 $inner.opacity              -fill x   -pady 2 -cspan 3 \
1996        4,0 $itk_component(xCutButton)  -anchor e -padx 2 -pady 2 \
1997        5,0 $itk_component(xCutScale)   -fill y \
1998        4,1 $itk_component(yCutButton)  -anchor e -padx 2 -pady 2 \
1999        5,1 $itk_component(yCutScale)   -fill y \
2000        4,2 $itk_component(zCutButton)  -anchor e -padx 2 -pady 2 \
2001        5,2 $itk_component(zCutScale)   -fill y
2002
2003    blt::table configure $inner r* c* -resize none
2004    blt::table configure $inner r5 c3 -resize expand
2005}
2006
2007#
2008# camera --
2009#
2010itcl::body Rappture::VtkVolumeViewer::camera {option args} {
2011    switch -- $option {
2012        "show" {
2013            puts [array get _view]
2014        }
2015        "set" {
2016            set what [lindex $args 0]
2017            set x $_view($what)
2018            set code [catch { string is double $x } result]
2019            if { $code != 0 || !$result } {
2020                return
2021            }
2022            switch -- $what {
2023                "-ortho" {
2024                    if {$_view($what)} {
2025                        SendCmd "camera mode ortho"
2026                    } else {
2027                        SendCmd "camera mode persp"
2028                    }
2029                }
2030                "-xpan" - "-ypan" {
2031                    PanCamera
2032                }
2033                "-qx" - "-qy" - "-qz" - "-qw" {
2034                    set q [ViewToQuaternion]
2035                    $_arcball quaternion $q
2036                    EventuallyRotate $q
2037                }
2038                "-zoom" {
2039                    SendCmd "camera zoom $_view($what)"
2040                }
2041            }
2042        }
2043    }
2044}
2045
2046itcl::body Rappture::VtkVolumeViewer::GetVtkData { args } {
2047    set bytes ""
2048    foreach dataobj [get] {
2049        foreach comp [$dataobj components] {
2050            set tag $dataobj-$comp
2051            set contents [$dataobj vtkdata $comp]
2052            append bytes "$contents\n"
2053        }
2054    }
2055    return [list .vtk $bytes]
2056}
2057
2058itcl::body Rappture::VtkVolumeViewer::GetImage { args } {
2059    if { [image width $_image(download)] > 0 &&
2060         [image height $_image(download)] > 0 } {
2061        set bytes [$_image(download) data -format "jpeg -quality 100"]
2062        set bytes [Rappture::encoding::decode -as b64 $bytes]
2063        return [list .jpg $bytes]
2064    }
2065    return ""
2066}
2067
2068itcl::body Rappture::VtkVolumeViewer::BuildDownloadPopup { popup command } {
2069    Rappture::Balloon $popup \
2070        -title "[Rappture::filexfer::label downloadWord] as..."
2071    set inner [$popup component inner]
2072    label $inner.summary -text "" -anchor w
2073    radiobutton $inner.vtk_button -text "VTK data file" \
2074        -variable [itcl::scope _downloadPopup(format)] \
2075        -font "Helvetica 9 " \
2076        -value vtk
2077    Rappture::Tooltip::for $inner.vtk_button "Save as VTK data file."
2078    radiobutton $inner.image_button -text "Image File" \
2079        -variable [itcl::scope _downloadPopup(format)] \
2080        -value image
2081    Rappture::Tooltip::for $inner.image_button \
2082        "Save as digital image."
2083
2084    button $inner.ok -text "Save" \
2085        -highlightthickness 0 -pady 2 -padx 3 \
2086        -command $command \
2087        -compound left \
2088        -image [Rappture::icon download]
2089
2090    button $inner.cancel -text "Cancel" \
2091        -highlightthickness 0 -pady 2 -padx 3 \
2092        -command [list $popup deactivate] \
2093        -compound left \
2094        -image [Rappture::icon cancel]
2095
2096    blt::table $inner \
2097        0,0 $inner.summary -cspan 2  \
2098        1,0 $inner.vtk_button -anchor w -cspan 2 -padx { 4 0 } \
2099        2,0 $inner.image_button -anchor w -cspan 2 -padx { 4 0 } \
2100        4,1 $inner.cancel -width .9i -fill y \
2101        4,0 $inner.ok -padx 2 -width .9i -fill y
2102    blt::table configure $inner r3 -height 4
2103    blt::table configure $inner r4 -pady 4
2104    raise $inner.image_button
2105    $inner.vtk_button invoke
2106    return $inner
2107}
2108
2109itcl::body Rappture::VtkVolumeViewer::SetObjectStyle { dataobj cname } {
2110    # Parse style string.
2111    set tag $dataobj-$cname
2112    array set style {
2113        -color      BCGYR
2114        -lighting   1
2115        -opacity    0.5
2116        -outline    0
2117        -visible    1
2118    }
2119    array set style [$dataobj style $cname]
2120    set _settings(-volumelighting) $style(-lighting)
2121    set _settings(-volumeopacity) [expr $style(-opacity) * 100.0]
2122    set _settings(-volumeoutline) $style(-outline)
2123    set _settings(-volumevisible) $style(-visible)
2124
2125    $itk_component(colormap) value $style(-color)
2126
2127    SendCmd "outline add $tag"
2128    SendCmd "outline color [Color2RGB $itk_option(-plotforeground)] $tag"
2129    SendCmd "outline visible $style(-outline) $tag"
2130
2131    SendCmd "$_cutplaneCmd add $tag"
2132    SendCmd "$_cutplaneCmd color [Color2RGB $itk_option(-plotforeground)] $tag"
2133    SendCmd "$_cutplaneCmd visible 0 $tag"
2134
2135    SendCmd "volume add $tag"
2136    SendCmd "volume lighting $style(-lighting) $tag"
2137    SendCmd "volume opacity $style(-opacity) $tag"
2138    SendCmd "volume visible $style(-visible) $tag"
2139    SetColormap $dataobj $cname
2140}
2141
2142itcl::body Rappture::VtkVolumeViewer::IsValidObject { dataobj } {
2143    if {[catch {$dataobj isa Rappture::Field} valid] != 0 || !$valid} {
2144        return 0
2145    }
2146    return 1
2147}
2148
2149# ----------------------------------------------------------------------
2150# USAGE: ReceiveLegend <colormap> <title> <vmin> <vmax> <size>
2151#
2152# Invoked automatically whenever the "legend" command comes in from
2153# the rendering server.  Indicates that binary image data with the
2154# specified <size> will follow.
2155# ----------------------------------------------------------------------
2156itcl::body Rappture::VtkVolumeViewer::ReceiveLegend { colormap title vmin vmax size } {
2157    if { [isconnected] } {
2158        set bytes [ReceiveBytes $size]
2159        if { ![info exists _image(legend)] } {
2160            set _image(legend) [image create photo]
2161        }
2162        $_image(legend) configure -data $bytes
2163        #puts stderr "read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
2164        if { [catch {DrawLegend} errs] != 0 } {
2165            puts stderr errs=$errs
2166        }
2167    }
2168}
2169
2170#
2171# DrawLegend --
2172#
2173itcl::body Rappture::VtkVolumeViewer::DrawLegend {} {
2174    set fname $_curFldName
2175    set c $itk_component(view)
2176    set w [winfo width $c]
2177    set h [winfo height $c]
2178    set font "Arial 8"
2179    set lineht [font metrics $font -linespace]
2180
2181    if { !$_settings(-legendvisible) } {
2182        $c delete legend
2183        return
2184    }
2185
2186    if { [info exists _fields($fname)] } {
2187        foreach { title units } $_fields($fname) break
2188        if { $units != "" } {
2189            set title [format "%s (%s)" $title $units]
2190        }
2191    } else {
2192        set title $fname
2193    }
2194
2195    set x [expr $w - 2]
2196    if { [$c find withtag "legend"] == "" } {
2197        set y 2
2198        $c create text $x $y \
2199            -anchor ne \
2200            -fill $itk_option(-plotforeground) -tags "title legend" \
2201            -font $font
2202        incr y $lineht
2203        $c create text $x $y \
2204            -anchor ne \
2205            -fill $itk_option(-plotforeground) -tags "vmax legend" \
2206            -font $font
2207        incr y $lineht
2208        $c create image $x $y \
2209            -anchor ne \
2210            -image $_image(legend) -tags "colormap legend"
2211        $c create text $x [expr {$h-2}] \
2212            -anchor se \
2213            -fill $itk_option(-plotforeground) -tags "vmin legend" \
2214            -font $font
2215        #$c bind colormap <Enter> [itcl::code $this EnterLegend %x %y]
2216        $c bind colormap <Leave> [itcl::code $this LeaveLegend]
2217        $c bind colormap <Motion> [itcl::code $this MotionLegend %x %y]
2218    }
2219    $c bind title <ButtonPress> [itcl::code $this Combo post]
2220    $c bind title <Enter> [itcl::code $this Combo activate]
2221    $c bind title <Leave> [itcl::code $this Combo deactivate]
2222    # Reset the item coordinates according the current size of the plot.
2223    $c itemconfigure title -text $title
2224    if { [info exists _limits($_curFldName)] } {
2225        foreach { vmin vmax } $_limits($_curFldName) break
2226        $c itemconfigure vmin -text [format %g $vmin]
2227        $c itemconfigure vmax -text [format %g $vmax]
2228    }
2229    set y 2
2230    $c coords title $x $y
2231    incr y $lineht
2232    $c coords vmax $x $y
2233    incr y $lineht
2234    $c coords colormap $x $y
2235    $c coords vmin $x [expr {$h - 2}]
2236}
2237
2238#
2239# EnterLegend --
2240#
2241itcl::body Rappture::VtkVolumeViewer::EnterLegend { x y } {
2242    SetLegendTip $x $y
2243}
2244
2245#
2246# MotionLegend --
2247#
2248itcl::body Rappture::VtkVolumeViewer::MotionLegend { x y } {
2249    Rappture::Tooltip::tooltip cancel
2250    set c $itk_component(view)
2251    SetLegendTip $x $y
2252}
2253
2254#
2255# LeaveLegend --
2256#
2257itcl::body Rappture::VtkVolumeViewer::LeaveLegend { } {
2258    Rappture::Tooltip::tooltip cancel
2259    .rappturetooltip configure -icon ""
2260}
2261
2262#
2263# SetLegendTip --
2264#
2265itcl::body Rappture::VtkVolumeViewer::SetLegendTip { x y } {
2266    set c $itk_component(view)
2267    set w [winfo width $c]
2268    set h [winfo height $c]
2269    set font "Arial 8"
2270    set lineht [font metrics $font -linespace]
2271
2272    set imgHeight [image height $_image(legend)]
2273    set coords [$c coords colormap]
2274    set imgX [expr $w - [image width $_image(legend)] - 2]
2275    set imgY [expr $y - 2 * ($lineht + 2)]
2276
2277    if { [info exists _fields($_title)] } {
2278        foreach { title units } $_fields($_title) break
2279        if { $units != "" } {
2280            set title [format "%s (%s)" $title $units]
2281        }
2282    } else {
2283        set title $_title
2284    }
2285    # Make a swatch of the selected color
2286    if { [catch { $_image(legend) get 10 $imgY } pixel] != 0 } {
2287        #puts stderr "out of range: $imgY"
2288        return
2289    }
2290    if { ![info exists _image(swatch)] } {
2291        set _image(swatch) [image create photo -width 24 -height 24]
2292    }
2293    set color [eval format "\#%02x%02x%02x" $pixel]
2294    $_image(swatch) put black  -to 0 0 23 23
2295    $_image(swatch) put $color -to 1 1 22 22
2296    .rappturetooltip configure -icon $_image(swatch)
2297
2298    # Compute the value of the point
2299    if { [info exists _limits($_curFldName)] } {
2300        foreach { vmin vmax } $_limits($_curFldName) break
2301        set t [expr 1.0 - (double($imgY) / double($imgHeight-1))]
2302        set value [expr $t * ($vmax - $vmin) + $vmin]
2303    } else {
2304        set value 0.0
2305    }
2306    set tipx [expr $x + 15]
2307    set tipy [expr $y - 5]
2308    Rappture::Tooltip::text $c "$title $value"
2309    Rappture::Tooltip::tooltip show $c +$tipx,+$tipy
2310}
2311
2312# ----------------------------------------------------------------------
2313# USAGE: Slice move x|y|z <newval>
2314#
2315# Called automatically when the user drags the slider to move the
2316# cut plane that slices 3D data.  Gets the current value from the
2317# slider and moves the cut plane to the appropriate point in the
2318# data set.
2319# ----------------------------------------------------------------------
2320itcl::body Rappture::VtkVolumeViewer::Slice {option args} {
2321    switch -- $option {
2322        "move" {
2323            set axis [lindex $args 0]
2324            set newval [lindex $args 1]
2325            if {[llength $args] != 2} {
2326                error "wrong # args: should be \"Slice move x|y|z newval\""
2327            }
2328            set newpos [expr {0.01*$newval}]
2329            SendCmd "$_cutplaneCmd slice $axis $newpos"
2330        }
2331        "tooltip" {
2332            set axis [lindex $args 0]
2333            set val [$itk_component(${axis}CutScale) get]
2334            return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
2335        }
2336        default {
2337            error "bad option \"$option\": should be axis, move, or tooltip"
2338        }
2339    }
2340}
2341
2342# ----------------------------------------------------------------------
2343# USAGE: _dropdown post
2344# USAGE: _dropdown unpost
2345# USAGE: _dropdown select
2346#
2347# Used internally to handle the dropdown list for this combobox.  The
2348# post/unpost options are invoked when the list is posted or unposted
2349# to manage the relief of the controlling button.  The select option
2350# is invoked whenever there is a selection from the list, to assign
2351# the value back to the gauge.
2352# ----------------------------------------------------------------------
2353itcl::body Rappture::VtkVolumeViewer::Combo {option} {
2354    set c $itk_component(view)
2355    switch -- $option {
2356        post {
2357            foreach { x1 y1 x2 y2 } [$c bbox title] break
2358            set x1 [expr [winfo width $itk_component(view)] - [winfo reqwidth $itk_component(fieldmenu)]]
2359            set x [expr $x1 + [winfo rootx $itk_component(view)]]
2360            set y [expr $y2 + [winfo rooty $itk_component(view)]]
2361            tk_popup $itk_component(fieldmenu) $x $y
2362        }
2363        activate {
2364            $c itemconfigure title -fill red
2365        }
2366        deactivate {
2367            $c itemconfigure title -fill $itk_option(-plotforeground)
2368        }
2369        invoke {
2370            $itk_component(field) value $_curFldLabel
2371            AdjustSetting -field
2372        }
2373        default {
2374            error "bad option \"$option\": should be post, unpost, select"
2375        }
2376    }
2377}
2378
2379itcl::body Rappture::VtkVolumeViewer::SetOrientation { side } {
2380    array set positions {
2381        front "1 0 0 0"
2382        back  "0 0 1 0"
2383        left  "0.707107 0 -0.707107 0"
2384        right "0.707107 0 0.707107 0"
2385        top   "0.707107 -0.707107 0 0"
2386        bottom "0.707107 0.707107 0 0"
2387    }
2388    foreach name { -qw -qx -qy -qz } value $positions($side) {
2389        set _view($name) $value
2390    }
2391    set q [ViewToQuaternion]
2392    $_arcball quaternion $q
2393    SendCmd "camera orient $q"
2394    SendCmd "camera reset"
2395    set _view(-xpan) 0
2396    set _view(-ypan) 0
2397    set _view(-zoom) 1.0
2398}
2399
2400#
2401# GetDatasetsWithComponent --
2402#
2403# Returns a list of all the datasets (known by the combination of
2404# their data object and component name) that match the given
2405# component name.  For example, this is used where we want to change
2406# the settings of volumes that have the current component.
2407#
2408itcl::body Rappture::VtkVolumeViewer::GetDatasetsWithComponent { cname } {
2409    if { ![info exists _volcomponents($cname)] } {
2410        return ""
2411    }
2412    return $_volcomponents($cname)
2413}
Note: See TracBrowser for help on using the repository browser.