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

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

fix: use volume visible instead of dataset visible in vtkvolumeviewer

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