source: trunk/gui/scripts/vtkvolumeviewer.tcl @ 5772

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

Remove code with no effect

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