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

Last change on this file since 4094 was 4094, checked in by ldelgass, 10 years ago

Apply current isolines/colormap visibilty to newly added datasets in viewer for
heightmaps/contours.

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