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

Last change on this file since 4122 was 4122, checked in by gah, 11 years ago

feature: add background color controls to nanovisviewer and vtkvolumeviewer

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