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

Last change on this file since 5767 was 5767, checked in by ldelgass, 9 years ago

remove unused variable

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