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

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

Rename isosurfaceoutline setting to outline

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