source: branches/1.6/gui/scripts/vtkisosurfaceviewer.tcl @ 6213

Last change on this file since 6213 was 6213, checked in by ldelgass, 8 years ago

Merge cleanups from trunk (partial hand merge of r6182, not including custom
range support in glyph viewer)

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