source: branches/1.4/gui/scripts/vtkisosurfaceviewer.tcl @ 5349

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

merge r5347 from trunk

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