source: trunk/gui/scripts/vtkisosurfaceviewer.tcl @ 5157

Last change on this file since 5157 was 5157, checked in by ldelgass, 5 years ago

Surface viewer fixes (based on changes from isosurface viewer)

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