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

Last change on this file since 5156 was 5156, checked in by ldelgass, 9 years ago

connection reset fixes

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