source: branches/1.3/gui/scripts/vtkisosurfaceviewer.tcl @ 4475

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

merge from trunk

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