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

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

remove cruft

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