source: branches/blt4_trunk/gui/scripts/vtkvolumeviewer.tcl @ 6414

Last change on this file since 6414 was 6414, checked in by ldelgass, 8 years ago

merge from trunk

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