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

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

whitespace

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