source: branches/1.7/gui/scripts/vtkisosurfaceviewer.tcl @ 6306

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

merge fixes from trunk

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