source: branches/1.7/gui/scripts/vtkvolumeviewer.tcl @ 6238

Last change on this file since 6238 was 6238, checked in by ldelgass, 6 years ago

merge r6235:6236 from trunk (streamlines scaling)

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