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

Last change on this file since 4288 was 4257, checked in by ldelgass, 11 years ago

Add flag for allowing volume viewer to use multiple component fields

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