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

Last change on this file since 4121 was 4121, checked in by gah, 10 years ago

feature: add background color controls to nanovisviewer and vtkvolumeviewer

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