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

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

Only require VTK Tcl bindings package in scripts that actually use it directly.

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