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

Last change on this file since 3814 was 3814, checked in by ldelgass, 11 years ago

Fixes for dataobj delete in VTK viewers:

  • Don't hide datasets from delete method since it isn't buffered and causes

flashes

  • Don't keep deleted dataobjs in _dlist: the commands are no longer valid even

though server objects remain. FIXME: should delete server objects or reuse
dataobj names for results, as we leak server datasets when user clears
datasets. However, we don't want to delete hidden sequence elts.

  • In vtkviewer: only make dataobjs with a raise setting visible
File size: 86.5 KB
Line 
1# -*- mode: tcl; indent-tabs-mode: nil -*-
2
3# ----------------------------------------------------------------------
4#  COMPONENT: vtkisolinesviewer - Vtk 3D contour object viewer
5#
6#  It connects to the Vtk server running on a rendering farm,
7#  transmits data, and displays the results.
8# ======================================================================
9#  AUTHOR:  Michael McLennan, Purdue University
10#  Copyright (c) 2004-2005  Purdue Research Foundation
11#
12#  See the file "license.terms" for information on usage and
13#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
14# ======================================================================
15package require Itk
16package require BLT
17#package require Img
18
19option add *VtkIsosurfaceViewer.width 4i widgetDefault
20option add *VtkIsosurfaceViewer*cursor crosshair widgetDefault
21option add *VtkIsosurfaceViewer.height 4i widgetDefault
22option add *VtkIsosurfaceViewer.foreground black widgetDefault
23option add *VtkIsosurfaceViewer.controlBackground gray widgetDefault
24option add *VtkIsosurfaceViewer.controlDarkBackground #999999 widgetDefault
25option add *VtkIsosurfaceViewer.plotBackground black widgetDefault
26option add *VtkIsosurfaceViewer.plotForeground white widgetDefault
27option add *VtkIsosurfaceViewer.font \
28    -*-helvetica-medium-r-normal-*-12-* widgetDefault
29
30# must use this name -- plugs into Rappture::resources::load
31proc VtkIsosurfaceViewer_init_resources {} {
32    Rappture::resources::register \
33        vtkvis_server Rappture::VtkIsosurfaceViewer::SetServerList
34}
35
36itcl::class Rappture::VtkIsosurfaceViewer {
37    inherit Rappture::VisViewer
38
39    itk_option define -plotforeground plotForeground Foreground ""
40    itk_option define -plotbackground plotBackground Background ""
41
42    constructor { hostlist args } {
43        Rappture::VisViewer::constructor $hostlist
44    } {
45        # defined below
46    }
47    destructor {
48        # defined below
49    }
50    public proc SetServerList { namelist } {
51        Rappture::VisViewer::SetServerList "vtkvis" $namelist
52    }
53    public method add {dataobj {settings ""}}
54    public method camera {option args}
55    public method delete {args}
56    public method disconnect {}
57    public method download {option args}
58    public method get {args}
59    public method isconnected {}
60    public method limits { colormap }
61    public method parameters {title args} {
62        # do nothing
63    }
64    public method scale {args}
65
66    protected method Connect {}
67    protected method CurrentDatasets {args}
68    protected method Disconnect {}
69    protected method DoResize {}
70    protected method DoRotate {}
71    protected method AdjustSetting {what {value ""}}
72    protected method InitSettings { args  }
73    protected method Pan {option x y}
74    protected method Pick {x y}
75    protected method Rebuild {}
76    protected method ReceiveDataset { args }
77    protected method ReceiveImage { args }
78    protected method ReceiveLegend { colormap title vmin vmax size }
79    protected method Rotate {option x y}
80    protected method Zoom {option}
81
82    # The following methods are only used by this class.
83    private method BuildAxisTab {}
84    private method BuildCameraTab {}
85    private method BuildColormap { name }
86    private method BuildCutplaneTab {}
87    private method BuildDownloadPopup { widget command }
88    private method BuildIsosurfaceTab {}
89    private method DrawLegend {}
90    private method Combo { option }
91    private method EnterLegend { x y }
92    private method EventuallyResize { w h }
93    private method EventuallyRotate { q }
94    private method EventuallyRequestLegend {}
95    private method EventuallySetCutplane { axis args }
96    private method GetImage { args }
97    private method GetVtkData { args }
98    private method IsValidObject { dataobj }
99    private method LeaveLegend {}
100    private method MotionLegend { x y }
101    private method PanCamera {}
102    private method RequestLegend {}
103    private method SetLegendTip { x y }
104    private method SetObjectStyle { dataobj comp }
105    private method Slice {option args}
106    private method SetCurrentColormap { color }
107    private method SetOrientation { side }
108    private method UpdateContourList {}
109
110    private variable _arcball ""
111
112    private variable _dlist ""     ;    # list of data objects
113    private variable _obj2datasets
114    private variable _obj2ovride   ;    # maps dataobj => style override
115    private variable _datasets     ;    # contains all the dataobj-component
116                                   ;    # datasets in the server
117    private variable _colormaps    ;    # contains all the colormaps
118                                   ;    # in the server.
119    # The name of the current colormap used.  The colormap is global to all
120    # heightmaps displayed.
121    private variable _currentColormap ""
122    private variable _currentNumContours -1
123    private variable _currentOpacity ""
124
125    private variable _dataset2style    ;# maps dataobj-component to transfunc
126
127    private variable _click        ;    # info used for rotate operations
128    private variable _limits       ;    # autoscale min/max for all axes
129    private variable _view         ;    # view params for 3D view
130    private variable _settings
131    private variable _style;            # Array of current component styles.
132    private variable _changed
133    private variable _initialStyle;     # Array of initial component styles.
134    private variable _reset 1;          # indicates if camera needs to be reset
135                                        # to starting position.
136
137    private variable _first ""     ;    # This is the topmost dataset.
138    private variable _start 0
139    private variable _title ""
140    private variable _isolines
141    private variable _contourList ""
142
143    common _downloadPopup;              # download options from popup
144    private common _hardcopy
145    private variable _width 0
146    private variable _height 0
147    private variable _resizePending 0
148    private variable _rotatePending 0
149    private variable _cutplanePending 0
150    private variable _legendPending 0
151    private variable _field      ""
152    private variable _colorMode "vmag"; #  Mode of colormap (vmag or scalar)
153    private variable _fieldNames {}
154    private variable _fields
155    private variable _curFldName ""
156    private variable _curFldLabel ""
157}
158
159itk::usual VtkIsosurfaceViewer {
160    keep -background -foreground -cursor -font
161    keep -plotbackground -plotforeground
162}
163
164# ----------------------------------------------------------------------
165# CONSTRUCTOR
166# ----------------------------------------------------------------------
167itcl::body Rappture::VtkIsosurfaceViewer::constructor {hostlist args} {
168    package require vtk
169    set _serverType "vtkvis"
170
171    # Rebuild event
172    $_dispatcher register !rebuild
173    $_dispatcher dispatch $this !rebuild "[itcl::code $this Rebuild]; list"
174
175    # Resize event
176    $_dispatcher register !resize
177    $_dispatcher dispatch $this !resize "[itcl::code $this DoResize]; list"
178
179    # Rotate event
180    $_dispatcher register !rotate
181    $_dispatcher dispatch $this !rotate "[itcl::code $this DoRotate]; list"
182
183    # Legend event
184    $_dispatcher register !legend
185    $_dispatcher dispatch $this !legend "[itcl::code $this RequestLegend]; list"
186
187    # X-Cutplane event
188    $_dispatcher register !xcutplane
189    $_dispatcher dispatch $this !xcutplane \
190        "[itcl::code $this AdjustSetting cutplaneXPosition]; list"
191
192    # Y-Cutplane event
193    $_dispatcher register !ycutplane
194    $_dispatcher dispatch $this !ycutplane \
195        "[itcl::code $this AdjustSetting cutplaneYPosition]; list"
196
197    # Z-Cutplane event
198    $_dispatcher register !zcutplane
199    $_dispatcher dispatch $this !zcutplane \
200        "[itcl::code $this AdjustSetting cutplaneZPosition]; list"
201
202    #
203    # Populate parser with commands handle incoming requests
204    #
205    $_parser alias image [itcl::code $this ReceiveImage]
206    $_parser alias dataset [itcl::code $this ReceiveDataset]
207    $_parser alias legend [itcl::code $this ReceiveLegend]
208
209    # Initialize the view to some default parameters.
210    array set _view {
211        qw              0.853553
212        qx              -0.353553
213        qy              0.353553
214        qz              0.146447
215        zoom            1.0
216        xpan            0
217        ypan            0
218        ortho           0
219    }
220    set _arcball [blt::arcball create 100 100]
221    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
222    $_arcball quaternion $q
223
224    array set _settings [subst {
225        background              black
226        colormap                BCGYR
227        colormapVisible         1
228        field                   "Default"
229        isolineColor            white
230        axesVisible             1
231        axisLabelsVisible       1
232        axisXGrid               0
233        axisYGrid               0
234        axisZGrid               0
235        cutplaneEdges           0
236        cutplaneLighting        1
237        cutplanePreinterp       0
238        cutplaneOpacity         100
239        cutplaneVisible         0
240        cutplaneWireframe       0
241        cutplaneXPosition       50
242        cutplaneXVisible        1
243        cutplaneYPosition       50
244        cutplaneYVisible        1
245        cutplaneZPosition       50
246        cutplaneZVisible        1
247        isosurfaceEdges         0
248        isosurfaceLighting      1
249        isosurfaceOpacity       60
250        saveIsosurfaceOpacity   60
251        isosurfaceOutline       0
252        isosurfaceVisible       1
253        isosurfaceWireframe     0
254        legendVisible           1
255        numContours             10
256    }]
257    array set _changed {
258        isosurfaceOpacity       0
259        colormap                0
260        numContours             0
261    }
262
263    itk_component add view {
264        canvas $itk_component(plotarea).view \
265            -highlightthickness 0 -borderwidth 0
266    } {
267        usual
268        ignore -highlightthickness -borderwidth  -background
269    }
270
271    itk_component add fieldmenu {
272        menu $itk_component(plotarea).menu -bg black -fg white -relief flat \
273            -tearoff no
274    } {
275        usual
276        ignore -background -foreground -relief -tearoff
277    }
278    set c $itk_component(view)
279    bind $c <Configure> [itcl::code $this EventuallyResize %w %h]
280    bind $c <4> [itcl::code $this Zoom in 0.25]
281    bind $c <5> [itcl::code $this Zoom out 0.25]
282    bind $c <KeyPress-Left>  [list %W xview scroll 10 units]
283    bind $c <KeyPress-Right> [list %W xview scroll -10 units]
284    bind $c <KeyPress-Up>    [list %W yview scroll 10 units]
285    bind $c <KeyPress-Down>  [list %W yview scroll -10 units]
286    bind $c <Enter> "focus %W"
287    bind $c <Control-F1> [itcl::code $this ToggleConsole]
288
289    # Fix the scrollregion in case we go off screen
290    $c configure -scrollregion [$c bbox all]
291
292    set _map(id) [$c create image 0 0 -anchor nw -image $_image(plot)]
293    set _map(cwidth) -1
294    set _map(cheight) -1
295    set _map(zoom) 1.0
296    set _map(original) ""
297
298    set f [$itk_component(main) component controls]
299    itk_component add reset {
300        button $f.reset -borderwidth 1 -padx 1 -pady 1 \
301            -highlightthickness 0 \
302            -image [Rappture::icon reset-view] \
303            -command [itcl::code $this Zoom reset]
304    } {
305        usual
306        ignore -highlightthickness
307    }
308    pack $itk_component(reset) -side top -padx 2 -pady 2
309    Rappture::Tooltip::for $itk_component(reset) \
310        "Reset the view to the default zoom level"
311
312    itk_component add zoomin {
313        button $f.zin -borderwidth 1 -padx 1 -pady 1 \
314            -highlightthickness 0 \
315            -image [Rappture::icon zoom-in] \
316            -command [itcl::code $this Zoom in]
317    } {
318        usual
319        ignore -highlightthickness
320    }
321    pack $itk_component(zoomin) -side top -padx 2 -pady 2
322    Rappture::Tooltip::for $itk_component(zoomin) "Zoom in"
323
324    itk_component add zoomout {
325        button $f.zout -borderwidth 1 -padx 1 -pady 1 \
326            -highlightthickness 0 \
327            -image [Rappture::icon zoom-out] \
328            -command [itcl::code $this Zoom out]
329    } {
330        usual
331        ignore -highlightthickness
332    }
333    pack $itk_component(zoomout) -side top -padx 2 -pady 2
334    Rappture::Tooltip::for $itk_component(zoomout) "Zoom out"
335
336    itk_component add contour {
337        Rappture::PushButton $f.contour \
338            -onimage [Rappture::icon volume-on] \
339            -offimage [Rappture::icon volume-off] \
340            -variable [itcl::scope _settings(isosurfaceVisible)] \
341            -command [itcl::code $this AdjustSetting isosurfaceVisible]
342    }
343    $itk_component(contour) select
344    Rappture::Tooltip::for $itk_component(contour) \
345        "Don't display the isosurface"
346    pack $itk_component(contour) -padx 2 -pady 2
347
348    itk_component add cutplane {
349        Rappture::PushButton $f.cutplane \
350            -onimage [Rappture::icon cutbutton] \
351            -offimage [Rappture::icon cutbutton] \
352            -variable [itcl::scope _settings(cutplaneVisible)] \
353            -command [itcl::code $this AdjustSetting cutplaneVisible]
354    }
355    Rappture::Tooltip::for $itk_component(cutplane) \
356        "Show/Hide cutplanes"
357    pack $itk_component(cutplane) -padx 2 -pady 2
358
359
360    if { [catch {
361        BuildIsosurfaceTab
362        BuildCutplaneTab
363        BuildAxisTab
364        BuildCameraTab
365    } errs] != 0 } {
366        puts stderr errs=$errs
367    }
368    # Legend
369
370    set _image(legend) [image create photo]
371    itk_component add legend {
372        canvas $itk_component(plotarea).legend -width 50 -highlightthickness 0
373    } {
374        usual
375        ignore -highlightthickness
376        rename -background -plotbackground plotBackground Background
377    }
378
379    # Hack around the Tk panewindow.  The problem is that the requested
380    # size of the 3d view isn't set until an image is retrieved from
381    # the server.  So the panewindow uses the tiny size.
382    set w 10000
383    pack forget $itk_component(view)
384    blt::table $itk_component(plotarea) \
385        0,0 $itk_component(view) -fill both -reqwidth $w
386    blt::table configure $itk_component(plotarea) c1 -resize none
387
388    # Bindings for rotation via mouse
389    bind $itk_component(view) <ButtonPress-1> \
390        [itcl::code $this Rotate click %x %y]
391    bind $itk_component(view) <B1-Motion> \
392        [itcl::code $this Rotate drag %x %y]
393    bind $itk_component(view) <ButtonRelease-1> \
394        [itcl::code $this Rotate release %x %y]
395
396    # Bindings for panning via mouse
397    bind $itk_component(view) <ButtonPress-2> \
398        [itcl::code $this Pan click %x %y]
399    bind $itk_component(view) <B2-Motion> \
400        [itcl::code $this Pan drag %x %y]
401    bind $itk_component(view) <ButtonRelease-2> \
402        [itcl::code $this Pan release %x %y]
403
404    #bind $itk_component(view) <ButtonRelease-3> \
405    #    [itcl::code $this Pick %x %y]
406
407    # Bindings for panning via keyboard
408    bind $itk_component(view) <KeyPress-Left> \
409        [itcl::code $this Pan set -10 0]
410    bind $itk_component(view) <KeyPress-Right> \
411        [itcl::code $this Pan set 10 0]
412    bind $itk_component(view) <KeyPress-Up> \
413        [itcl::code $this Pan set 0 -10]
414    bind $itk_component(view) <KeyPress-Down> \
415        [itcl::code $this Pan set 0 10]
416    bind $itk_component(view) <Shift-KeyPress-Left> \
417        [itcl::code $this Pan set -2 0]
418    bind $itk_component(view) <Shift-KeyPress-Right> \
419        [itcl::code $this Pan set 2 0]
420    bind $itk_component(view) <Shift-KeyPress-Up> \
421        [itcl::code $this Pan set 0 -2]
422    bind $itk_component(view) <Shift-KeyPress-Down> \
423        [itcl::code $this Pan set 0 2]
424
425    # Bindings for zoom via keyboard
426    bind $itk_component(view) <KeyPress-Prior> \
427        [itcl::code $this Zoom out]
428    bind $itk_component(view) <KeyPress-Next> \
429        [itcl::code $this Zoom in]
430
431    bind $itk_component(view) <Enter> "focus $itk_component(view)"
432
433    if {[string equal "x11" [tk windowingsystem]]} {
434        # Bindings for zoom via mouse
435        bind $itk_component(view) <4> [itcl::code $this Zoom out]
436        bind $itk_component(view) <5> [itcl::code $this Zoom in]
437    }
438
439    set _image(download) [image create photo]
440
441    eval itk_initialize $args
442    Connect
443    update
444}
445
446# ----------------------------------------------------------------------
447# DESTRUCTOR
448# ----------------------------------------------------------------------
449itcl::body Rappture::VtkIsosurfaceViewer::destructor {} {
450    Disconnect
451    image delete $_image(plot)
452    image delete $_image(download)
453    catch { blt::arcball destroy $_arcball }
454}
455
456itcl::body Rappture::VtkIsosurfaceViewer::DoResize {} {
457    if { $_width < 2 } {
458        set _width 500
459    }
460    if { $_height < 2 } {
461        set _height 500
462    }
463    set _start [clock clicks -milliseconds]
464    SendCmd "screen size $_width $_height"
465
466    EventuallyRequestLegend
467    set _resizePending 0
468}
469
470itcl::body Rappture::VtkIsosurfaceViewer::DoRotate {} {
471    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
472    SendCmd "camera orient $q"
473    set _rotatePending 0
474}
475
476itcl::body Rappture::VtkIsosurfaceViewer::EventuallyRequestLegend {} {
477    if { !$_legendPending } {
478        set _legendPending 1
479        $_dispatcher event -idle !legend
480    }
481}
482
483itcl::body Rappture::VtkIsosurfaceViewer::EventuallyResize { w h } {
484    set _width $w
485    set _height $h
486    $_arcball resize $w $h
487    if { !$_resizePending } {
488        set _resizePending 1
489        $_dispatcher event -after 400 !resize
490    }
491}
492
493set rotate_delay 100
494
495itcl::body Rappture::VtkIsosurfaceViewer::EventuallyRotate { q } {
496    foreach { _view(qw) _view(qx) _view(qy) _view(qz) } $q break
497    if { !$_rotatePending } {
498        set _rotatePending 1
499        global rotate_delay
500        $_dispatcher event -after $rotate_delay !rotate
501    }
502}
503
504itcl::body Rappture::VtkIsosurfaceViewer::EventuallySetCutplane { axis args } {
505    if { !$_cutplanePending } {
506        set _cutplanePending 1
507        $_dispatcher event -after 100 !${axis}cutplane
508    }
509}
510
511# ----------------------------------------------------------------------
512# USAGE: add <dataobj> ?<settings>?
513#
514# Clients use this to add a data object to the plot.  The optional
515# <settings> are used to configure the plot.  Allowed settings are
516# -color, -brightness, -width, -linestyle, and -raise.
517# ----------------------------------------------------------------------
518itcl::body Rappture::VtkIsosurfaceViewer::add {dataobj {settings ""}} {
519    if { ![$dataobj isvalid] } {
520        return;                         # Object doesn't contain valid data.
521    }
522    array set params {
523        -color auto
524        -width 1
525        -linestyle solid
526        -brightness 0
527        -raise 0
528        -description ""
529        -param ""
530        -type ""
531    }
532    array set params $settings
533    set params(-description) ""
534    set params(-param) ""
535    array set params $settings
536
537    if {$params(-color) == "auto" || $params(-color) == "autoreset"} {
538        # can't handle -autocolors yet
539        set params(-color) black
540    }
541    set pos [lsearch -exact $_dlist $dataobj]
542    if {$pos < 0} {
543        lappend _dlist $dataobj
544    }
545    set _obj2ovride($dataobj-color) $params(-color)
546    set _obj2ovride($dataobj-width) $params(-width)
547    set _obj2ovride($dataobj-raise) $params(-raise)
548    $_dispatcher event -idle !rebuild
549}
550
551
552# ----------------------------------------------------------------------
553# USAGE: delete ?<dataobj1> <dataobj2> ...?
554#
555#       Clients use this to delete a dataobj from the plot.  If no dataobjs
556#       are specified, then all dataobjs are deleted.  No data objects are
557#       deleted.  They are only removed from the display list.
558#
559# ----------------------------------------------------------------------
560itcl::body Rappture::VtkIsosurfaceViewer::delete {args} {
561    if { [llength $args] == 0} {
562        set args $_dlist
563    }
564    # Delete all specified dataobjs
565    set changed 0
566    foreach dataobj $args {
567        set pos [lsearch -exact $_dlist $dataobj]
568        if { $pos < 0 } {
569            continue;                   # Don't know anything about it.
570        }
571        # Remove it from the dataobj list.
572        set _dlist [lreplace $_dlist $pos $pos]
573        array unset _obj2ovride $dataobj-*
574        array unset _settings $dataobj-*
575        set changed 1
576    }
577    # If anything changed, then rebuild the plot
578    if { $changed } {
579        $_dispatcher event -idle !rebuild
580    }
581}
582
583# ----------------------------------------------------------------------
584# USAGE: get ?-objects?
585# USAGE: get ?-visible?
586# USAGE: get ?-image view?
587#
588# Clients use this to query the list of objects being plotted, in
589# order from bottom to top of this result.  The optional "-image"
590# flag can also request the internal images being shown.
591# ----------------------------------------------------------------------
592itcl::body Rappture::VtkIsosurfaceViewer::get {args} {
593    if {[llength $args] == 0} {
594        set args "-objects"
595    }
596
597    set op [lindex $args 0]
598    switch -- $op {
599        "-objects" {
600            # put the dataobj list in order according to -raise options
601            set dlist {}
602            foreach dataobj $_dlist {
603                if { ![IsValidObject $dataobj] } {
604                    continue
605                }
606                if {[info exists _obj2ovride($dataobj-raise)] &&
607                    $_obj2ovride($dataobj-raise)} {
608                    set dlist [linsert $dlist 0 $dataobj]
609                } else {
610                    lappend dlist $dataobj
611                }
612            }
613            return $dlist
614        }
615        "-visible" {
616            set dlist {}
617            foreach dataobj $_dlist {
618                if { ![IsValidObject $dataobj] } {
619                    continue
620                }
621                if { ![info exists _obj2ovride($dataobj-raise)] } {
622                    # No setting indicates that the object isn't visible.
623                    continue
624                }
625                # Otherwise use the -raise parameter to put the object to
626                # the front of the list.
627                if { $_obj2ovride($dataobj-raise) } {
628                    set dlist [linsert $dlist 0 $dataobj]
629                } else {
630                    lappend dlist $dataobj
631                }
632            }
633            return $dlist
634        }           
635        -image {
636            if {[llength $args] != 2} {
637                error "wrong # args: should be \"get -image view\""
638            }
639            switch -- [lindex $args end] {
640                view {
641                    return $_image(plot)
642                }
643                default {
644                    error "bad image name \"[lindex $args end]\": should be view"
645                }
646            }
647        }
648        default {
649            error "bad option \"$op\": should be -objects or -image"
650        }
651    }
652}
653
654# ----------------------------------------------------------------------
655# USAGE: scale ?<data1> <data2> ...?
656#
657# Sets the default limits for the overall plot according to the
658# limits of the data for all of the given <data> objects.  This
659# accounts for all objects--even those not showing on the screen.
660# Because of this, the limits are appropriate for all objects as
661# the user scans through data in the ResultSet viewer.
662# ----------------------------------------------------------------------
663itcl::body Rappture::VtkIsosurfaceViewer::scale { args } {
664    foreach dataobj $args {
665        if { ![$dataobj isvalid] } {
666            continue;                   # Object doesn't contain valid data.
667        }
668        foreach axis { x y z } {
669            set lim [$dataobj limits $axis]
670            if { ![info exists _limits($axis)] } {
671                set _limits($axis) $lim
672                continue
673            }
674            foreach {min max} $lim break
675            foreach {amin amax} $_limits($axis) break
676            if { $amin > $min } {
677                set amin $min
678            }
679            if { $amax < $max } {
680                set amax $max
681            }
682            set _limits($axis) [list $amin $amax]
683        }
684        foreach { fname lim } [$dataobj fieldlimits] {
685            if { ![info exists _limits($fname)] } {
686                set _limits($fname) $lim
687                continue
688            }
689            foreach {min max} $lim break
690            foreach {fmin fmax} $_limits($fname) break
691            if { $fmin > $min } {
692                set fmin $min
693            }
694            if { $fmax < $max } {
695                set fmax $max
696            }
697            set _limits($fname) [list $fmin $fmax]
698        }
699    }
700}
701
702# ----------------------------------------------------------------------
703# USAGE: download coming
704# USAGE: download controls <downloadCommand>
705# USAGE: download now
706#
707# Clients use this method to create a downloadable representation
708# of the plot.  Returns a list of the form {ext string}, where
709# "ext" is the file extension (indicating the type of data) and
710# "string" is the data itself.
711# ----------------------------------------------------------------------
712itcl::body Rappture::VtkIsosurfaceViewer::download {option args} {
713    switch $option {
714        coming {
715            if {[catch {
716                blt::winop snap $itk_component(plotarea) $_image(download)
717            }]} {
718                $_image(download) configure -width 1 -height 1
719                $_image(download) put #000000
720            }
721        }
722        controls {
723            set popup .vtkviewerdownload
724            if { ![winfo exists .vtkviewerdownload] } {
725                set inner [BuildDownloadPopup $popup [lindex $args 0]]
726            } else {
727                set inner [$popup component inner]
728            }
729            set _downloadPopup(image_controls) $inner.image_frame
730            set num [llength [get]]
731            set num [expr {($num == 1) ? "1 result" : "$num results"}]
732            set word [Rappture::filexfer::label downloadWord]
733            $inner.summary configure -text "$word $num in the following format:"
734            update idletasks            ;# Fix initial sizes
735            return $popup
736        }
737        now {
738            set popup .vtkviewerdownload
739            if {[winfo exists .vtkviewerdownload]} {
740                $popup deactivate
741            }
742            switch -- $_downloadPopup(format) {
743                "image" {
744                    return [$this GetImage [lindex $args 0]]
745                }
746                "vtk" {
747                    return [$this GetVtkData [lindex $args 0]]
748                }
749            }
750            return ""
751        }
752        default {
753            error "bad option \"$option\": should be coming, controls, now"
754        }
755    }
756}
757
758# ----------------------------------------------------------------------
759# USAGE: Connect ?<host:port>,<host:port>...?
760#
761# Clients use this method to establish a connection to a new
762# server, or to reestablish a connection to the previous server.
763# Any existing connection is automatically closed.
764# ----------------------------------------------------------------------
765itcl::body Rappture::VtkIsosurfaceViewer::Connect {} {
766    set _hosts [GetServerList "vtkvis"]
767    if { "" == $_hosts } {
768        return 0
769    }
770    set result [VisViewer::Connect $_hosts]
771    if { $result } {
772        if { $_reportClientInfo }  {
773            # Tell the server the viewer, hub, user and session.
774            # Do this immediately on connect before buffing any commands
775            global env
776
777            set info {}
778            set user "???"
779            if { [info exists env(USER)] } {
780                set user $env(USER)
781            }
782            set session "???"
783            if { [info exists env(SESSION)] } {
784                set session $env(SESSION)
785            }
786            lappend info "hub" [exec hostname]
787            lappend info "client" "vtkisosurfaceviewer"
788            lappend info "user" $user
789            lappend info "session" $session
790            SendCmd "clientinfo [list $info]"
791        }
792
793        set w [winfo width $itk_component(view)]
794        set h [winfo height $itk_component(view)]
795        EventuallyResize $w $h
796    }
797    return $result
798}
799
800#
801# isconnected --
802#
803#       Indicates if we are currently connected to the visualization server.
804#
805itcl::body Rappture::VtkIsosurfaceViewer::isconnected {} {
806    return [VisViewer::IsConnected]
807}
808
809#
810# disconnect --
811#
812itcl::body Rappture::VtkIsosurfaceViewer::disconnect {} {
813    Disconnect
814    set _reset 1
815}
816
817#
818# Disconnect --
819#
820#       Clients use this method to disconnect from the current rendering
821#       server.
822#
823itcl::body Rappture::VtkIsosurfaceViewer::Disconnect {} {
824    VisViewer::Disconnect
825
826    $_dispatcher cancel !rebuild
827    $_dispatcher cancel !resize
828    $_dispatcher cancel !rotate
829    $_dispatcher cancel !xcutplane
830    $_dispatcher cancel !ycutplane
831    $_dispatcher cancel !zcutplane
832    $_dispatcher cancel !legend
833    # disconnected -- no more data sitting on server
834    set _outbuf ""
835    array unset _datasets
836    array unset _data
837    array unset _colormaps
838    array unset _seeds
839    array unset _dataset2style
840    array unset _obj2datasets
841}
842
843# ----------------------------------------------------------------------
844# USAGE: ReceiveImage -bytes <size> -type <type> -token <token>
845#
846# Invoked automatically whenever the "image" command comes in from
847# the rendering server.  Indicates that binary image data with the
848# specified <size> will follow.
849# ----------------------------------------------------------------------
850itcl::body Rappture::VtkIsosurfaceViewer::ReceiveImage { args } {
851    array set info {
852        -token "???"
853        -bytes 0
854        -type image
855    }
856    array set info $args
857    set bytes [ReceiveBytes $info(-bytes)]
858    if { $info(-type) == "image" } {
859        if 0 {
860            set f [open "last.ppm" "w"]
861            puts $f $bytes
862            close $f
863        }
864        $_image(plot) configure -data $bytes
865        set time [clock seconds]
866        set date [clock format $time]
867        #puts stderr "$date: received image [image width $_image(plot)]x[image height $_image(plot)] image>"       
868        if { $_start > 0 } {
869            set finish [clock clicks -milliseconds]
870            #puts stderr "round trip time [expr $finish -$_start] milliseconds"
871            set _start 0
872        }
873    } elseif { $info(type) == "print" } {
874        set tag $this-print-$info(-token)
875        set _hardcopy($tag) $bytes
876    }
877    EventuallyRequestLegend
878}
879
880#
881# ReceiveDataset --
882#
883itcl::body Rappture::VtkIsosurfaceViewer::ReceiveDataset { args } {
884    if { ![isconnected] } {
885        return
886    }
887    set option [lindex $args 0]
888    switch -- $option {
889        "scalar" {
890            set option [lindex $args 1]
891            switch -- $option {
892                "world" {
893                    foreach { x y z value tag } [lrange $args 2 end] break
894                }
895                "pixel" {
896                    foreach { x y value tag } [lrange $args 2 end] break
897                }
898            }
899        }
900        "vector" {
901            set option [lindex $args 1]
902            switch -- $option {
903                "world" {
904                    foreach { x y z vx vy vz tag } [lrange $args 2 end] break
905                }
906                "pixel" {
907                    foreach { x y vx vy vz tag } [lrange $args 2 end] break
908                }
909            }
910        }
911        "names" {
912            foreach { name } [lindex $args 1] {
913                #puts stderr "Dataset: $name"
914            }
915        }
916        default {
917            error "unknown dataset option \"$option\" from server"
918        }
919    }
920}
921
922# ----------------------------------------------------------------------
923# USAGE: Rebuild
924#
925# Called automatically whenever something changes that affects the
926# data in the widget.  Clears any existing data and rebuilds the
927# widget to display new data.
928# ----------------------------------------------------------------------
929itcl::body Rappture::VtkIsosurfaceViewer::Rebuild {} {
930    set w [winfo width $itk_component(view)]
931    set h [winfo height $itk_component(view)]
932    if { $w < 2 || $h < 2 } {
933        $_dispatcher event -idle !rebuild
934        return
935    }
936
937    # Turn on buffering of commands to the server.  We don't want to
938    # be preempted by a server disconnect/reconnect (which automatically
939    # generates a new call to Rebuild).   
940    StartBufferingCommands
941
942    if { $_reset } {
943        set _width $w
944        set _height $h
945        $_arcball resize $w $h
946        DoResize
947        #
948        # Reset the camera and other view parameters
949        #
950        set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
951        $_arcball quaternion $q
952        if {$_view(ortho)} {
953            SendCmd "camera mode ortho"
954        } else {
955            SendCmd "camera mode persp"
956        }
957        DoRotate
958        PanCamera
959        set _first ""
960        InitSettings axisXGrid axisYGrid axisZGrid axisMode \
961            axesVisible axisLabelsVisible
962        foreach axis { x y z } {
963            SendCmd "axis lformat $axis %g"
964        }
965        StopBufferingCommands
966        SendCmd "imgflush"
967        StartBufferingCommands
968    }
969    set _first ""
970    SendCmd "dataset visible 0"
971    foreach dataobj [get -objects] {
972        if { [info exists _obj2ovride($dataobj-raise)] &&  $_first == "" } {
973            set _first $dataobj
974        }
975        set _obj2datasets($dataobj) ""
976        foreach comp [$dataobj components] {
977            set tag $dataobj-$comp
978            if { ![info exists _datasets($tag)] } {
979                set bytes [$dataobj vtkdata $comp]
980                if 0 {
981                    set f [open "/tmp/isosurface.vtk" "w"]
982                    puts $f $bytes
983                    close $f
984                }
985                set length [string length $bytes]
986                if { $_reportClientInfo }  {
987                    set info {}
988                    lappend info "tool_id"       [$dataobj hints toolId]
989                    lappend info "tool_name"     [$dataobj hints toolName]
990                    lappend info "tool_version"  [$dataobj hints toolRevision]
991                    lappend info "tool_title"    [$dataobj hints toolTitle]
992                    lappend info "dataset_label" [$dataobj hints label]
993                    lappend info "dataset_size"  $length
994                    lappend info "dataset_tag"   $tag
995                    SendCmd "clientinfo [list $info]"
996                }
997                append _outbuf "dataset add $tag data follows $length\n"
998                append _outbuf $bytes
999                set _datasets($tag) 1
1000                SetObjectStyle $dataobj $comp
1001            }
1002            lappend _obj2datasets($dataobj) $tag
1003            if { [info exists _obj2ovride($dataobj-raise)] } {
1004                # Setting dataset visible enables outline (if enabled)
1005                # and contour3d
1006                SendCmd "dataset visible 1 $tag"
1007            }
1008        }
1009    }
1010
1011    if { $_first != "" } {
1012        $itk_component(field) choices delete 0 end
1013        $itk_component(fieldmenu) delete 0 end
1014        array unset _fields
1015        set _curFldName ""
1016        foreach cname [$_first components] {
1017            foreach fname [$_first fieldnames $cname] {
1018                if { [info exists _fields($fname)] } {
1019                    continue
1020                }
1021                foreach { label units components } \
1022                    [$_first fieldinfo $fname] break
1023                $itk_component(field) choices insert end "$fname" "$label"
1024                $itk_component(fieldmenu) add radiobutton -label "$label" \
1025                    -value $label -variable [itcl::scope _curFldLabel] \
1026                    -selectcolor red \
1027                    -activebackground $itk_option(-plotbackground) \
1028                    -activeforeground $itk_option(-plotforeground) \
1029                    -font "Arial 8" \
1030                    -command [itcl::code $this Combo invoke]
1031                set _fields($fname) [list $label $units $components]
1032                if { $_curFldName == "" } {
1033                    set _curFldName $fname
1034                    set _curFldLabel $label
1035                }
1036            }
1037        }
1038        $itk_component(field) value $_curFldLabel
1039    }
1040    InitSettings cutplaneVisible
1041    if { $_reset } {
1042        # These are settings that rely on a dataset being loaded.
1043        InitSettings \
1044            isosurfaceLighting \
1045            field \
1046            isosurfaceEdges isosurfaceLighting isosurfaceOpacity \
1047            isosurfaceWireframe isosurfaceOutline \
1048            cutplaneXPosition cutplaneYPosition cutplaneZPosition \
1049            cutplaneXVisible cutplaneYVisible cutplaneZVisible \
1050            cutplanePreinterp numContours
1051
1052        Zoom reset
1053        foreach axis { x y z } {
1054            # Another problem fixed by a <view>. We looking into a data
1055            # object for the name of the axes. This should be global to
1056            # the viewer itself.
1057            set label [$_first hints ${axis}label]
1058            if { $label == "" } {
1059                set label [string toupper $axis]
1060            }
1061            # May be a space in the axis label.
1062            SendCmd [list axis name $axis $label]
1063        }
1064        if { [array size _fields] < 2 } {
1065            blt::table forget $itk_component(field) $itk_component(field_l)
1066        }
1067        set _reset 0
1068    }
1069
1070    # Actually write the commands to the server socket.  If it fails, we don't
1071    # care.  We're finished here.
1072    blt::busy hold $itk_component(hull)
1073    StopBufferingCommands;              # Turn off buffering and send commands.
1074    blt::busy release $itk_component(hull)
1075}
1076
1077# ----------------------------------------------------------------------
1078# USAGE: CurrentDatasets ?-all -visible? ?dataobjs?
1079#
1080# Returns a list of server IDs for the current datasets being displayed.  This
1081# is normally a single ID, but it might be a list of IDs if the current data
1082# object has multiple components.
1083# ----------------------------------------------------------------------
1084itcl::body Rappture::VtkIsosurfaceViewer::CurrentDatasets {args} {
1085    set flag [lindex $args 0]
1086    switch -- $flag {
1087        "-all" {
1088            if { [llength $args] > 1 } {
1089                error "CurrentDatasets: can't specify dataobj after \"-all\""
1090            }
1091            set dlist [get -objects]
1092        }
1093        "-visible" {
1094            if { [llength $args] > 1 } {
1095                set dlist {}
1096                set args [lrange $args 1 end]
1097                foreach dataobj $args {
1098                    if { [info exists _obj2ovride($dataobj-raise)] } {
1099                        lappend dlist $dataobj
1100                    }
1101                }
1102            } else {
1103                set dlist [get -visible]
1104            }
1105        }           
1106        default {
1107            set dlist $args
1108        }
1109    }
1110    set rlist ""
1111    foreach dataobj $dlist {
1112        foreach comp [$dataobj components] {
1113            set tag $dataobj-$comp
1114            if { [info exists _datasets($tag)] && $_datasets($tag) } {
1115                lappend rlist $tag
1116            }
1117        }
1118    }
1119    return $rlist
1120}
1121
1122# ----------------------------------------------------------------------
1123# USAGE: Zoom in
1124# USAGE: Zoom out
1125# USAGE: Zoom reset
1126#
1127# Called automatically when the user clicks on one of the zoom
1128# controls for this widget.  Changes the zoom for the current view.
1129# ----------------------------------------------------------------------
1130itcl::body Rappture::VtkIsosurfaceViewer::Zoom {option} {
1131    switch -- $option {
1132        "in" {
1133            set _view(zoom) [expr {$_view(zoom)*1.25}]
1134            SendCmd "camera zoom $_view(zoom)"
1135        }
1136        "out" {
1137            set _view(zoom) [expr {$_view(zoom)*0.8}]
1138            SendCmd "camera zoom $_view(zoom)"
1139        }
1140        "reset" {
1141            array set _view {
1142                qw     0.853553
1143                qx     -0.353553
1144                qy     0.353553
1145                qz     0.146447
1146                zoom   1.0
1147                xpan   0
1148                ypan   0
1149            }
1150            if { $_first != "" } {
1151                set location [$_first hints camera]
1152                if { $location != "" } {
1153                    array set _view $location
1154                }
1155            }
1156            set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1157            $_arcball quaternion $q
1158            DoRotate
1159            SendCmd "camera reset"
1160        }
1161    }
1162}
1163
1164itcl::body Rappture::VtkIsosurfaceViewer::PanCamera {} {
1165    set x $_view(xpan)
1166    set y $_view(ypan)
1167    SendCmd "camera pan $x $y"
1168}
1169
1170
1171# ----------------------------------------------------------------------
1172# USAGE: Rotate click <x> <y>
1173# USAGE: Rotate drag <x> <y>
1174# USAGE: Rotate release <x> <y>
1175#
1176# Called automatically when the user clicks/drags/releases in the
1177# plot area.  Moves the plot according to the user's actions.
1178# ----------------------------------------------------------------------
1179itcl::body Rappture::VtkIsosurfaceViewer::Rotate {option x y} {
1180    switch -- $option {
1181        "click" {
1182            $itk_component(view) configure -cursor fleur
1183            set _click(x) $x
1184            set _click(y) $y
1185        }
1186        "drag" {
1187            if {[array size _click] == 0} {
1188                Rotate click $x $y
1189            } else {
1190                set w [winfo width $itk_component(view)]
1191                set h [winfo height $itk_component(view)]
1192                if {$w <= 0 || $h <= 0} {
1193                    return
1194                }
1195
1196                if {[catch {
1197                    # this fails sometimes for no apparent reason
1198                    set dx [expr {double($x-$_click(x))/$w}]
1199                    set dy [expr {double($y-$_click(y))/$h}]
1200                }]} {
1201                    return
1202                }
1203                if { $dx == 0 && $dy == 0 } {
1204                    return
1205                }
1206                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1207                EventuallyRotate $q
1208                set _click(x) $x
1209                set _click(y) $y
1210            }
1211        }
1212        "release" {
1213            Rotate drag $x $y
1214            $itk_component(view) configure -cursor ""
1215            catch {unset _click}
1216        }
1217        default {
1218            error "bad option \"$option\": should be click, drag, release"
1219        }
1220    }
1221}
1222
1223itcl::body Rappture::VtkIsosurfaceViewer::Pick {x y} {
1224    foreach tag [CurrentDatasets -visible] {
1225        SendCmdNoSplash "dataset getscalar pixel $x $y $tag"
1226    }
1227}
1228
1229# ----------------------------------------------------------------------
1230# USAGE: $this Pan click x y
1231#        $this Pan drag x y
1232#        $this Pan release x y
1233#
1234# Called automatically when the user clicks on one of the zoom
1235# controls for this widget.  Changes the zoom for the current view.
1236# ----------------------------------------------------------------------
1237itcl::body Rappture::VtkIsosurfaceViewer::Pan {option x y} {
1238    switch -- $option {
1239        "set" {
1240            set w [winfo width $itk_component(view)]
1241            set h [winfo height $itk_component(view)]
1242            set x [expr $x / double($w)]
1243            set y [expr $y / double($h)]
1244            set _view(xpan) [expr $_view(xpan) + $x]
1245            set _view(ypan) [expr $_view(ypan) + $y]
1246            PanCamera
1247            return
1248        }
1249        "click" {
1250            set _click(x) $x
1251            set _click(y) $y
1252            $itk_component(view) configure -cursor hand1
1253        }
1254        "drag" {
1255            if { ![info exists _click(x)] } {
1256                set _click(x) $x
1257            }
1258            if { ![info exists _click(y)] } {
1259                set _click(y) $y
1260            }
1261            set w [winfo width $itk_component(view)]
1262            set h [winfo height $itk_component(view)]
1263            set dx [expr ($_click(x) - $x)/double($w)]
1264            set dy [expr ($_click(y) - $y)/double($h)]
1265            set _click(x) $x
1266            set _click(y) $y
1267            set _view(xpan) [expr $_view(xpan) - $dx]
1268            set _view(ypan) [expr $_view(ypan) - $dy]
1269            PanCamera
1270        }
1271        "release" {
1272            Pan drag $x $y
1273            $itk_component(view) configure -cursor ""
1274        }
1275        default {
1276            error "unknown option \"$option\": should set, click, drag, or release"
1277        }
1278    }
1279}
1280
1281# ----------------------------------------------------------------------
1282# USAGE: InitSettings <what> ?<value>?
1283#
1284# Used internally to update rendering settings whenever parameters
1285# change in the popup settings panel.  Sends the new settings off
1286# to the back end.
1287# ----------------------------------------------------------------------
1288itcl::body Rappture::VtkIsosurfaceViewer::InitSettings { args } {
1289    foreach spec $args {
1290        if { [info exists _settings($_first-$spec)] } {
1291            # Reset global setting with dataobj specific setting
1292            set _settings($spec) $_settings($_first-$spec)
1293        }
1294        AdjustSetting $spec
1295    }
1296}
1297
1298#
1299# AdjustSetting --
1300#
1301#       Changes/updates a specific setting in the widget.  There are
1302#       usually user-setable option.  Commands are sent to the render
1303#       server.
1304#
1305itcl::body Rappture::VtkIsosurfaceViewer::AdjustSetting {what {value ""}} {
1306    if { ![isconnected] } {
1307        return
1308    }
1309    switch -- $what {
1310        "background" {
1311            set bgcolor [$itk_component(background) value]
1312            array set fgcolors {
1313                "black" "white"
1314                "white" "black"
1315                "grey"  "black"
1316            }
1317            configure -plotbackground $bgcolor \
1318                -plotforeground $fgcolors($bgcolor)
1319            $itk_component(view) delete "legend"
1320            DrawLegend
1321        }
1322        "axesVisible" {
1323            set bool $_settings(axesVisible)
1324            SendCmd "axis visible all $bool"
1325        }
1326        "axisLabelsVisible" {
1327            set bool $_settings(axisLabelsVisible)
1328            SendCmd "axis labels all $bool"
1329        }
1330        "axisXGrid" - "axisYGrid" - "axisZGrid" {
1331            set axis [string tolower [string range $what 4 4]]
1332            set bool $_settings($what)
1333            SendCmd "axis grid $axis $bool"
1334        }
1335        "axisMode" {
1336            set mode [$itk_component(axisMode) value]
1337            set mode [$itk_component(axisMode) translate $mode]
1338            set _settings($what) $mode
1339            SendCmd "axis flymode $mode"
1340        }
1341        "cutplaneEdges" {
1342            set bool $_settings($what)
1343            SendCmd "cutplane edges $bool"
1344        }
1345        "cutplaneVisible" {
1346            set bool $_settings($what)
1347            SendCmd "cutplane visible $bool"
1348        }
1349        "cutplaneWireframe" {
1350            set bool $_settings($what)
1351            SendCmd "cutplane wireframe $bool"
1352        }
1353        "cutplaneLighting" {
1354            set bool $_settings($what)
1355            SendCmd "cutplane lighting $bool"
1356        }
1357        "cutplaneOpacity" {
1358            set val $_settings($what)
1359            set sval [expr { 0.01 * double($val) }]
1360            SendCmd "cutplane opacity $sval"
1361        }
1362        "cutplanePreinterp" {
1363            set bool $_settings($what)
1364            SendCmd "cutplane preinterp $bool"
1365        }
1366        "cutplaneXVisible" - "cutplaneYVisible" - "cutplaneZVisible" {
1367            set axis [string tolower [string range $what 8 8]]
1368            set bool $_settings($what)
1369            if { $bool } {
1370                $itk_component(${axis}position) configure -state normal \
1371                    -troughcolor white
1372            } else {
1373                $itk_component(${axis}position) configure -state disabled \
1374                    -troughcolor grey82
1375            }
1376            SendCmd "cutplane axis $axis $bool"
1377        }
1378        "cutplaneXPosition" - "cutplaneYPosition" - "cutplaneZPosition" {
1379            set axis [string tolower [string range $what 8 8]]
1380            set pos [expr $_settings($what) * 0.01]
1381            SendCmd "cutplane slice ${axis} ${pos}"
1382            set _cutplanePending 0
1383        }
1384        "colormap" {
1385            set _changed(colormap) 1
1386            StartBufferingCommands
1387            set color [$itk_component(colormap) value]
1388            set _settings(colormap) $color
1389            if { $color == "none" } {
1390                if { $_settings(colormapVisible) } {
1391                    SendCmd "contour3d colormode ccolor {}"
1392                    set _settings(colormapVisible) 0
1393                }
1394            } else {
1395                if { !$_settings(colormapVisible) } {
1396                    SendCmd "contour3d colormode $_colorMode $_curFldName"
1397                    set _settings(colormapVisible) 1
1398                }
1399                SetCurrentColormap $color
1400            }
1401            StopBufferingCommands
1402            EventuallyRequestLegend
1403        }
1404        "numContours" {
1405            set _settings(numContours) [$itk_component(numcontours) value]
1406            set _currentNumContours $_settings(numContours)
1407            UpdateContourList
1408            set _changed(numContours) 1
1409            SendCmd "contour3d contourlist [list $_contourList]"
1410            DrawLegend
1411        }
1412        "isosurfaceWireframe" {
1413            set bool $_settings(isosurfaceWireframe)
1414            SendCmd "contour3d wireframe $bool"
1415        }
1416        "isosurfaceVisible" {
1417            set bool $_settings(isosurfaceVisible)
1418            SendCmd "contour3d visible $bool"
1419            if { $bool } {
1420                Rappture::Tooltip::for $itk_component(contour) \
1421                    "Hide the isosurface"
1422            } else {
1423                Rappture::Tooltip::for $itk_component(contour) \
1424                    "Show the isosurface"
1425            }
1426            DrawLegend
1427        }
1428        "isosurfaceLighting" {
1429            set bool $_settings(isosurfaceLighting)
1430            SendCmd "contour3d lighting $bool"
1431        }
1432        "isosurfaceEdges" {
1433            set bool $_settings(isosurfaceEdges)
1434            SendCmd "contour3d edges $bool"
1435        }
1436        "isosurfaceOutline" {
1437            set bool $_settings(isosurfaceOutline)
1438            SendCmd "outline visible $bool"
1439        }
1440        "isolineColor" {
1441            set color [$itk_component(isolineColor) value]
1442            set _settings(isolineColor) $color
1443            DrawLegend
1444        }
1445        "isosurfaceOpacity" {
1446            set val $_settings(isosurfaceOpacity)
1447            set sval [expr { 0.01 * double($val) }]
1448            SendCmd "contour3d opacity $sval"
1449        }
1450        "field" {
1451            set label [$itk_component(field) value]
1452            set fname [$itk_component(field) translate $label]
1453            set _settings(field) $fname
1454            if { [info exists _fields($fname)] } {
1455                foreach { label units components } $_fields($fname) break
1456                if { $components > 1 } {
1457                    set _colorMode vmag
1458                } else {
1459                    set _colorMode scalar
1460                }
1461                set _curFldName $fname
1462                set _curFldLabel $label
1463            } else {
1464                puts stderr "unknown field \"$fname\""
1465                return
1466            }
1467            SendCmd "dataset scalar $_curFldName"
1468            SendCmd "dataset maprange explicit $_limits($_curFldName) $_curFldName"
1469            SendCmd "cutplane colormode $_colorMode $_curFldName"
1470            SendCmd "contour3d colormode $_colorMode $_curFldName"
1471            SendCmd "camera reset"
1472            UpdateContourList
1473            DrawLegend
1474        }
1475        "legendVisible" {
1476            if { !$_settings(legendVisible) } {
1477                $itk_component(view) delete legend
1478            }
1479            DrawLegend
1480        }
1481        default {
1482            error "don't know how to fix $what"
1483        }
1484    }
1485}
1486
1487
1488#
1489# RequestLegend --
1490#
1491#       Request a new legend from the server.  The size of the legend
1492#       is determined from the height of the canvas. 
1493#
1494# This should be called when
1495#       1.  A new current colormap is set.
1496#       2.  Window is resized.
1497#       3.  The limits of the data have changed.  (Just need a redraw).
1498#       4.  Number of isolines have changed. (Just need a redraw).
1499#       5.  Legend becomes visible (Just need a redraw).
1500#
1501itcl::body Rappture::VtkIsosurfaceViewer::RequestLegend {} {
1502    set _legendPending 0
1503    if { ![info exists _fields($_curFldName)] } {
1504        return
1505    }
1506    set fname $_curFldName
1507    set font "Arial 8"
1508    set lineht [font metrics $font -linespace]
1509    set c $itk_component(view)
1510    set w 12
1511    set h [expr {$_height - 2 * ($lineht + 2)}]
1512    if { $h < 1} {
1513        return
1514    }
1515    if { [string match "component*" $fname] } {
1516        set title ""
1517    } else {
1518        if { [info exists _fields($fname)] } {
1519            foreach { title units } $_fields($fname) break
1520            if { $units != "" } {
1521                set title [format "%s (%s)" $title $units]
1522            }
1523        } else {
1524            set title $fname
1525        }
1526    }
1527    # If there's a title too, substract one more line
1528    if { $title != "" } {
1529        incr h -$lineht
1530    }
1531    # Set the legend on the first heightmap dataset.
1532    if { $_currentColormap != ""  } {
1533        set cmap $_currentColormap
1534        SendCmdNoWait "legend $cmap scalar $_curFldName {} $w $h 0"
1535    }
1536}
1537
1538# ----------------------------------------------------------------------
1539# CONFIGURATION OPTION: -plotbackground
1540# ----------------------------------------------------------------------
1541itcl::configbody Rappture::VtkIsosurfaceViewer::plotbackground {
1542    if { [isconnected] } {
1543        set rgb [Color2RGB $itk_option(-plotbackground)]
1544        SendCmd "screen bgcolor $rgb"
1545    }
1546}
1547
1548# ----------------------------------------------------------------------
1549# CONFIGURATION OPTION: -plotforeground
1550# ----------------------------------------------------------------------
1551itcl::configbody Rappture::VtkIsosurfaceViewer::plotforeground {
1552    if { [isconnected] } {
1553        set rgb [Color2RGB $itk_option(-plotforeground)]
1554        SendCmd "axis color all $rgb"
1555        SendCmd "outline color $rgb"
1556        SendCmd "cutplane ccolor $rgb"
1557    }
1558}
1559
1560itcl::body Rappture::VtkIsosurfaceViewer::limits { dataobj } {
1561    foreach { limits(xmin) limits(xmax) } [$dataobj limits x] break
1562    foreach { limits(ymin) limits(ymax) } [$dataobj limits y] break
1563    foreach { limits(zmin) limits(zmax) } [$dataobj limits z] break
1564    foreach { limits(vmin) limits(vmax) } [$dataobj limits v] break
1565    return [array get limits]
1566}
1567
1568itcl::body Rappture::VtkIsosurfaceViewer::BuildIsosurfaceTab {} {
1569
1570    set fg [option get $itk_component(hull) font Font]
1571    #set bfg [option get $itk_component(hull) boldFont Font]
1572
1573    set inner [$itk_component(main) insert end \
1574        -title "Isosurface Settings" \
1575        -icon [Rappture::icon volume-on]]
1576    $inner configure -borderwidth 4
1577
1578    checkbutton $inner.contour \
1579        -text "Isosurfaces" \
1580        -variable [itcl::scope _settings(isosurfaceVisible)] \
1581        -command [itcl::code $this AdjustSetting isosurfaceVisible] \
1582        -font "Arial 9"
1583
1584    checkbutton $inner.wireframe \
1585        -text "Wireframe" \
1586        -variable [itcl::scope _settings(isosurfaceWireframe)] \
1587        -command [itcl::code $this AdjustSetting isosurfaceWireframe] \
1588        -font "Arial 9"
1589
1590    checkbutton $inner.lighting \
1591        -text "Enable Lighting" \
1592        -variable [itcl::scope _settings(isosurfaceLighting)] \
1593        -command [itcl::code $this AdjustSetting isosurfaceLighting] \
1594        -font "Arial 9"
1595
1596    checkbutton $inner.edges \
1597        -text "Edges" \
1598        -variable [itcl::scope _settings(isosurfaceEdges)] \
1599        -command [itcl::code $this AdjustSetting isosurfaceEdges] \
1600        -font "Arial 9"
1601
1602    checkbutton $inner.outline \
1603        -text "Outline" \
1604        -variable [itcl::scope _settings(isosurfaceOutline)] \
1605        -command [itcl::code $this AdjustSetting isosurfaceOutline] \
1606        -font "Arial 9"
1607
1608    checkbutton $inner.legend \
1609        -text "Legend" \
1610        -variable [itcl::scope _settings(legendVisible)] \
1611        -command [itcl::code $this AdjustSetting legendVisible] \
1612        -font "Arial 9"
1613
1614    label $inner.linecolor_l -text "Isolines" -font "Arial 9"
1615    itk_component add isolineColor {
1616        Rappture::Combobox $inner.linecolor -width 10 -editable no
1617    }
1618    $inner.linecolor choices insert end \
1619        "black"              "black"            \
1620        "blue"               "blue"             \
1621        "cyan"               "cyan"             \
1622        "green"              "green"            \
1623        "grey"               "grey"             \
1624        "magenta"            "magenta"          \
1625        "orange"             "orange"           \
1626        "red"                "red"              \
1627        "white"              "white"            \
1628        "none"               "none"
1629
1630    $itk_component(isolineColor) value "white"
1631    bind $inner.linecolor <<Value>> \
1632        [itcl::code $this AdjustSetting isolineColor]
1633
1634    label $inner.background_l -text "Background" -font "Arial 9"
1635    itk_component add background {
1636        Rappture::Combobox $inner.background -width 10 -editable no
1637    }
1638    $inner.background choices insert end \
1639        "black"              "black"            \
1640        "white"              "white"            \
1641        "grey"               "grey"             
1642
1643    $itk_component(background) value $_settings(background)
1644    bind $inner.background <<Value>> [itcl::code $this AdjustSetting background]
1645
1646    label $inner.opacity_l -text "Opacity" -font "Arial 9"
1647    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1648        -variable [itcl::scope _settings(isosurfaceOpacity)] \
1649        -width 10 \
1650        -showvalue off \
1651        -command [itcl::code $this AdjustSetting isosurfaceOpacity]
1652
1653    label $inner.scale_l -text "Scale" -font "Arial 9"
1654    ::scale $inner.scale -from 1 -to 100 -orient horizontal \
1655        -variable [itcl::scope _settings(contour-scale)] \
1656        -width 10 \
1657        -showvalue off \
1658        -command [itcl::code $this AdjustSetting contour-scale]
1659
1660    itk_component add field_l {
1661        label $inner.field_l -text "Field" -font "Arial 9"
1662    } {
1663        ignore -font
1664    }
1665    itk_component add field {
1666        Rappture::Combobox $inner.field -width 10 -editable no
1667    }
1668    bind $inner.field <<Value>> \
1669        [itcl::code $this AdjustSetting field]
1670
1671    label $inner.colormap_l -text "Colormap" -font "Arial 9"
1672    itk_component add colormap {
1673        Rappture::Combobox $inner.colormap -width 10 -editable no
1674    }
1675    $inner.colormap choices insert end \
1676        "BCGYR"              "BCGYR"            \
1677        "BGYOR"              "BGYOR"            \
1678        "blue"               "blue"             \
1679        "blue-to-brown"      "blue-to-brown"    \
1680        "blue-to-orange"     "blue-to-orange"   \
1681        "blue-to-grey"       "blue-to-grey"     \
1682        "green-to-magenta"   "green-to-magenta" \
1683        "greyscale"          "greyscale"        \
1684        "nanohub"            "nanohub"          \
1685        "rainbow"            "rainbow"          \
1686        "spectral"           "spectral"         \
1687        "ROYGB"              "ROYGB"            \
1688        "RYGCB"              "RYGCB"            \
1689        "brown-to-blue"      "brown-to-blue"    \
1690        "grey-to-blue"       "grey-to-blue"     \
1691        "orange-to-blue"     "orange-to-blue"   
1692
1693    $itk_component(colormap) value "BCGYR"
1694    bind $inner.colormap <<Value>> \
1695        [itcl::code $this AdjustSetting colormap]
1696
1697    label $inner.numcontours_l -text "Number of Isosurfaces" -font "Arial 9"
1698    itk_component add numcontours {
1699        Rappture::Spinint $inner.numcontours \
1700            -min 1 -max 50 -font "arial 9"
1701    }
1702    $itk_component(numcontours) value $_settings(numContours)
1703    bind $itk_component(numcontours) <<Value>> \
1704        [itcl::code $this AdjustSetting numContours]
1705
1706    blt::table $inner \
1707        0,0 $inner.field_l   -anchor w -pady 2  \
1708        0,1 $inner.field     -anchor w -pady 2  -fill x \
1709        1,0 $inner.colormap_l -anchor w -pady 2  \
1710        1,1 $inner.colormap   -anchor w -pady 2  -fill x \
1711        2,0 $inner.linecolor_l  -anchor w -pady 2  \
1712        2,1 $inner.linecolor    -anchor w -pady 2 -fill x  \
1713        3,0 $inner.background_l -anchor w -pady 2 \
1714        3,1 $inner.background -anchor w -pady 2  -fill x \
1715        4,0 $inner.numcontours_l -anchor w -pady 2 \
1716        4,1 $inner.numcontours -anchor w -pady 2 \
1717        5,0 $inner.wireframe -anchor w -pady 2 -cspan 2 \
1718        6,0 $inner.lighting  -anchor w -pady 2 -cspan 2 \
1719        7,0 $inner.edges     -anchor w -pady 2 -cspan 2 \
1720        8,0 $inner.outline   -anchor w -pady 2 -cspan 2 \
1721        9,0 $inner.legend    -anchor w -pady 2 \
1722        10,0 $inner.opacity_l -anchor w -pady 2 \
1723        10,1 $inner.opacity   -fill x   -pady 2 -fill x \
1724
1725    blt::table configure $inner r* c* -resize none
1726    blt::table configure $inner r11 c1 -resize expand
1727}
1728
1729itcl::body Rappture::VtkIsosurfaceViewer::BuildAxisTab {} {
1730
1731    set fg [option get $itk_component(hull) font Font]
1732    #set bfg [option get $itk_component(hull) boldFont Font]
1733
1734    set inner [$itk_component(main) insert end \
1735        -title "Axis Settings" \
1736        -icon [Rappture::icon axis2]]
1737    $inner configure -borderwidth 4
1738
1739    checkbutton $inner.visible \
1740        -text "Show Axes" \
1741        -variable [itcl::scope _settings(axesVisible)] \
1742        -command [itcl::code $this AdjustSetting axesVisible] \
1743        -font "Arial 9"
1744
1745    checkbutton $inner.labels \
1746        -text "Show Axis Labels" \
1747        -variable [itcl::scope _settings(axisLabelsVisible)] \
1748        -command [itcl::code $this AdjustSetting axisLabelsVisible] \
1749        -font "Arial 9"
1750
1751    checkbutton $inner.gridx \
1752        -text "Show X Grid" \
1753        -variable [itcl::scope _settings(axisXGrid)] \
1754        -command [itcl::code $this AdjustSetting axisXGrid] \
1755        -font "Arial 9"
1756    checkbutton $inner.gridy \
1757        -text "Show Y Grid" \
1758        -variable [itcl::scope _settings(axisYGrid)] \
1759        -command [itcl::code $this AdjustSetting axisYGrid] \
1760        -font "Arial 9"
1761    checkbutton $inner.gridz \
1762        -text "Show Z Grid" \
1763        -variable [itcl::scope _settings(axisZGrid)] \
1764        -command [itcl::code $this AdjustSetting axisZGrid] \
1765        -font "Arial 9"
1766
1767    label $inner.mode_l -text "Mode" -font "Arial 9"
1768
1769    itk_component add axisMode {
1770        Rappture::Combobox $inner.mode -width 10 -editable no
1771    }
1772    $inner.mode choices insert end \
1773        "static_triad"    "static" \
1774        "closest_triad"   "closest" \
1775        "furthest_triad"  "furthest" \
1776        "outer_edges"     "outer"         
1777    $itk_component(axisMode) value "static"
1778    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting axisMode]
1779
1780    blt::table $inner \
1781        0,0 $inner.visible -anchor w -cspan 2 \
1782        1,0 $inner.labels  -anchor w -cspan 2 \
1783        2,0 $inner.gridx   -anchor w -cspan 2 \
1784        3,0 $inner.gridy   -anchor w -cspan 2 \
1785        4,0 $inner.gridz   -anchor w -cspan 2 \
1786        5,0 $inner.mode_l  -anchor w -cspan 2 -padx { 2 0 } \
1787        6,0 $inner.mode    -fill x   -cspan 2
1788
1789    blt::table configure $inner r* c* -resize none
1790    blt::table configure $inner r7 c1 -resize expand
1791}
1792
1793
1794itcl::body Rappture::VtkIsosurfaceViewer::BuildCameraTab {} {
1795    set inner [$itk_component(main) insert end \
1796        -title "Camera Settings" \
1797        -icon [Rappture::icon camera]]
1798    $inner configure -borderwidth 4
1799
1800    label $inner.view_l -text "view" -font "Arial 9"
1801    set f [frame $inner.view]
1802    foreach side { front back left right top bottom } {
1803        button $f.$side  -image [Rappture::icon view$side] \
1804            -command [itcl::code $this SetOrientation $side]
1805        Rappture::Tooltip::for $f.$side "Change the view to $side"
1806        pack $f.$side -side left
1807    }
1808
1809    blt::table $inner \
1810        0,0 $inner.view_l -anchor e -pady 2 \
1811        0,1 $inner.view -anchor w -pady 2
1812
1813    set labels { qx qy qz qw xpan ypan zoom }
1814    set row 1
1815    foreach tag $labels {
1816        label $inner.${tag}label -text $tag -font "Arial 9"
1817        entry $inner.${tag} -font "Arial 9"  -bg white \
1818            -textvariable [itcl::scope _view($tag)]
1819        bind $inner.${tag} <KeyPress-Return> \
1820            [itcl::code $this camera set ${tag}]
1821        blt::table $inner \
1822            $row,0 $inner.${tag}label -anchor e -pady 2 \
1823            $row,1 $inner.${tag} -anchor w -pady 2
1824        blt::table configure $inner r$row -resize none
1825        incr row
1826    }
1827    checkbutton $inner.ortho \
1828        -text "Orthographic Projection" \
1829        -variable [itcl::scope _view(ortho)] \
1830        -command [itcl::code $this camera set ortho] \
1831        -font "Arial 9"
1832    blt::table $inner \
1833            $row,0 $inner.ortho -cspan 2 -anchor w -pady 2
1834    blt::table configure $inner r$row -resize none
1835    incr row
1836
1837    blt::table configure $inner c* r* -resize none
1838    blt::table configure $inner c2 -resize expand
1839    blt::table configure $inner r$row -resize expand
1840}
1841
1842itcl::body Rappture::VtkIsosurfaceViewer::BuildCutplaneTab {} {
1843
1844    set fg [option get $itk_component(hull) font Font]
1845   
1846    set inner [$itk_component(main) insert end \
1847        -title "Cutplane Settings" \
1848        -icon [Rappture::icon cutbutton]]
1849
1850    $inner configure -borderwidth 4
1851
1852    checkbutton $inner.visible \
1853        -text "Cutplanes" \
1854        -variable [itcl::scope _settings(cutplaneVisible)] \
1855        -command [itcl::code $this AdjustSetting cutplaneVisible] \
1856        -font "Arial 9"
1857
1858    checkbutton $inner.wireframe \
1859        -text "Wireframe" \
1860        -variable [itcl::scope _settings(cutplaneWireframe)] \
1861        -command [itcl::code $this AdjustSetting cutplaneWireframe] \
1862        -font "Arial 9"
1863
1864    checkbutton $inner.lighting \
1865        -text "Enable Lighting" \
1866        -variable [itcl::scope _settings(cutplaneLighting)] \
1867        -command [itcl::code $this AdjustSetting cutplaneLighting] \
1868        -font "Arial 9"
1869
1870    checkbutton $inner.edges \
1871        -text "Edges" \
1872        -variable [itcl::scope _settings(cutplaneEdges)] \
1873        -command [itcl::code $this AdjustSetting cutplaneEdges] \
1874        -font "Arial 9"
1875
1876    checkbutton $inner.preinterp \
1877        -text "Interpolate Scalars" \
1878        -variable [itcl::scope _settings(cutplanePreinterp)] \
1879        -command [itcl::code $this AdjustSetting cutplanePreinterp] \
1880        -font "Arial 9"
1881
1882    label $inner.opacity_l -text "Opacity" -font "Arial 9"
1883    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1884        -variable [itcl::scope _settings(cutplaneOpacity)] \
1885        -width 10 \
1886        -showvalue off \
1887        -command [itcl::code $this AdjustSetting cutplaneOpacity]
1888    $inner.opacity set $_settings(cutplaneOpacity)
1889
1890    # X-value slicer...
1891    itk_component add xbutton {
1892        Rappture::PushButton $inner.xbutton \
1893            -onimage [Rappture::icon x-cutplane-red] \
1894            -offimage [Rappture::icon x-cutplane-red] \
1895            -command [itcl::code $this AdjustSetting cutplaneXVisible] \
1896            -variable [itcl::scope _settings(cutplaneXVisible)] \
1897    }
1898    Rappture::Tooltip::for $itk_component(xbutton) \
1899        "Toggle the X-axis cutplane on/off"
1900    $itk_component(xbutton) select
1901    itk_component add xposition {
1902        ::scale $inner.xval -from 100 -to 0 \
1903            -width 10 -orient vertical -showvalue yes \
1904            -borderwidth 1 -highlightthickness 0 \
1905            -command [itcl::code $this EventuallySetCutplane x] \
1906            -variable [itcl::scope _settings(cutplaneXPosition)] \
1907            -foreground red2 -font "Arial 9 bold"
1908    } {
1909        usual
1910        ignore -borderwidth -highlightthickness -foreground -font -background
1911    }
1912    # Set the default cutplane value before disabling the scale.
1913    $itk_component(xposition) set 50
1914    $itk_component(xposition) configure -state disabled
1915    Rappture::Tooltip::for $itk_component(xposition) \
1916        "@[itcl::code $this Slice tooltip x]"
1917
1918    # Y-value slicer...
1919    itk_component add ybutton {
1920        Rappture::PushButton $inner.ybutton \
1921            -onimage [Rappture::icon y-cutplane-green] \
1922            -offimage [Rappture::icon y-cutplane-green] \
1923            -command [itcl::code $this AdjustSetting cutplaneYVisible] \
1924            -variable [itcl::scope _settings(cutplaneYVisible)] \
1925    }
1926    Rappture::Tooltip::for $itk_component(ybutton) \
1927        "Toggle the Y-axis cutplane on/off"
1928    $itk_component(ybutton) select
1929
1930    itk_component add yposition {
1931        ::scale $inner.yval -from 100 -to 0 \
1932            -width 10 -orient vertical -showvalue yes \
1933            -borderwidth 1 -highlightthickness 0 \
1934            -command [itcl::code $this EventuallySetCutplane y] \
1935            -variable [itcl::scope _settings(cutplaneYPosition)] \
1936            -foreground green3 -font "Arial 9 bold"
1937    } {
1938        usual
1939        ignore -borderwidth -highlightthickness -foreground -font
1940    }
1941    Rappture::Tooltip::for $itk_component(yposition) \
1942        "@[itcl::code $this Slice tooltip y]"
1943    # Set the default cutplane value before disabling the scale.
1944    $itk_component(yposition) set 50
1945    $itk_component(yposition) configure -state disabled
1946
1947    # Z-value slicer...
1948    itk_component add zbutton {
1949        Rappture::PushButton $inner.zbutton \
1950            -onimage [Rappture::icon z-cutplane-blue] \
1951            -offimage [Rappture::icon z-cutplane-blue] \
1952            -command [itcl::code $this AdjustSetting cutplaneZVisible] \
1953            -variable [itcl::scope _settings(cutplaneZVisible)] \
1954    } {
1955        usual
1956        ignore -foreground
1957    }
1958    Rappture::Tooltip::for $itk_component(zbutton) \
1959        "Toggle the Z-axis cutplane on/off"
1960    $itk_component(zbutton) select
1961
1962    itk_component add zposition {
1963        ::scale $inner.zval -from 100 -to 0 \
1964            -width 10 -orient vertical -showvalue yes \
1965            -borderwidth 1 -highlightthickness 0 \
1966            -command [itcl::code $this EventuallySetCutplane z] \
1967            -variable [itcl::scope _settings(cutplaneZPosition)] \
1968            -foreground blue3 -font "Arial 9 bold"
1969    } {
1970        usual
1971        ignore -borderwidth -highlightthickness -foreground -font
1972    }
1973    $itk_component(zposition) set 50
1974    $itk_component(zposition) configure -state disabled
1975    Rappture::Tooltip::for $itk_component(zposition) \
1976        "@[itcl::code $this Slice tooltip z]"
1977
1978    blt::table $inner \
1979        0,0 $inner.visible              -anchor w -pady 2 -cspan 3 \
1980        1,0 $inner.lighting             -anchor w -pady 2 -cspan 3 \
1981        2,0 $inner.wireframe            -anchor w -pady 2 -cspan 3 \
1982        3,0 $inner.edges                -anchor w -pady 2 -cspan 3 \
1983        4,0 $inner.preinterp            -anchor w -pady 2 -cspan 3 \
1984        5,0 $inner.opacity_l            -anchor w -pady 2 -cspan 1 \
1985        5,1 $inner.opacity              -fill x   -pady 2 -cspan 3 \
1986        6,0 $inner.xbutton              -anchor w -padx 2 -pady 2 \
1987        7,0 $inner.ybutton              -anchor w -padx 2 -pady 2 \
1988        8,0 $inner.zbutton              -anchor w -padx 2 -pady 2 \
1989        6,1 $inner.xval                 -fill y -rspan 4 \
1990        6,2 $inner.yval                 -fill y -rspan 4 \
1991        6,3 $inner.zval                 -fill y -rspan 4 \
1992
1993
1994    blt::table configure $inner r* c* -resize none
1995    blt::table configure $inner r9 c4 -resize expand
1996}
1997
1998
1999
2000#
2001#  camera --
2002#
2003itcl::body Rappture::VtkIsosurfaceViewer::camera {option args} {
2004    switch -- $option {
2005        "show" {
2006            puts [array get _view]
2007        }
2008        "set" {
2009            set who [lindex $args 0]
2010            set x $_view($who)
2011            set code [catch { string is double $x } result]
2012            if { $code != 0 || !$result } {
2013                return
2014            }
2015            switch -- $who {
2016                "ortho" {
2017                    if {$_view(ortho)} {
2018                        SendCmd "camera mode ortho"
2019                    } else {
2020                        SendCmd "camera mode persp"
2021                    }
2022                }
2023                "xpan" - "ypan" {
2024                    PanCamera
2025                }
2026                "qx" - "qy" - "qz" - "qw" {
2027                    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
2028                    $_arcball quaternion $q
2029                    EventuallyRotate $q
2030                }
2031                "zoom" {
2032                    SendCmd "camera zoom $_view(zoom)"
2033                }
2034             }
2035        }
2036    }
2037}
2038
2039itcl::body Rappture::VtkIsosurfaceViewer::GetVtkData { args } {
2040    set bytes ""
2041    foreach dataobj [get] {
2042        foreach cname [$dataobj components] {
2043            set tag $dataobj-$cname
2044            set contents [$dataobj vtkdata $cname]
2045            append bytes "$contents\n"
2046        }
2047    }
2048    return [list .vtk $bytes]
2049}
2050
2051itcl::body Rappture::VtkIsosurfaceViewer::GetImage { args } {
2052    if { [image width $_image(download)] > 0 &&
2053         [image height $_image(download)] > 0 } {
2054        set bytes [$_image(download) data -format "jpeg -quality 100"]
2055        set bytes [Rappture::encoding::decode -as b64 $bytes]
2056        return [list .jpg $bytes]
2057    }
2058    return ""
2059}
2060
2061itcl::body Rappture::VtkIsosurfaceViewer::BuildDownloadPopup { popup command } {
2062    Rappture::Balloon $popup \
2063        -title "[Rappture::filexfer::label downloadWord] as..."
2064    set inner [$popup component inner]
2065    label $inner.summary -text "" -anchor w
2066    radiobutton $inner.vtk_button -text "VTK data file" \
2067        -variable [itcl::scope _downloadPopup(format)] \
2068        -font "Arial 9 " \
2069        -value vtk 
2070    Rappture::Tooltip::for $inner.vtk_button "Save as VTK data file."
2071    radiobutton $inner.image_button -text "Image File" \
2072        -variable [itcl::scope _downloadPopup(format)] \
2073        -font "Arial 9 " \
2074        -value image
2075    Rappture::Tooltip::for $inner.image_button \
2076        "Save as digital image."
2077
2078    button $inner.ok -text "Save" \
2079        -highlightthickness 0 -pady 2 -padx 3 \
2080        -command $command \
2081        -compound left \
2082        -image [Rappture::icon download]
2083
2084    button $inner.cancel -text "Cancel" \
2085        -highlightthickness 0 -pady 2 -padx 3 \
2086        -command [list $popup deactivate] \
2087        -compound left \
2088        -image [Rappture::icon cancel]
2089
2090    blt::table $inner \
2091        0,0 $inner.summary -cspan 2  \
2092        1,0 $inner.vtk_button -anchor w -cspan 2 -padx { 4 0 } \
2093        2,0 $inner.image_button -anchor w -cspan 2 -padx { 4 0 } \
2094        4,1 $inner.cancel -width .9i -fill y \
2095        4,0 $inner.ok -padx 2 -width .9i -fill y
2096    blt::table configure $inner r3 -height 4
2097    blt::table configure $inner r4 -pady 4
2098    raise $inner.image_button
2099    $inner.vtk_button invoke
2100    return $inner
2101}
2102
2103itcl::body Rappture::VtkIsosurfaceViewer::SetObjectStyle { dataobj comp } {
2104    # Parse style string.
2105    set tag $dataobj-$comp
2106    array set style {
2107        -color BCGYR
2108        -edges 0
2109        -edgecolor black
2110        -linewidth 1.0
2111        -opacity 0.6
2112        -wireframe 0
2113        -lighting 1
2114        -outline 0
2115        -levels 10
2116    }
2117    array set style [$dataobj style $comp]
2118    if { $dataobj != $_first } {
2119        set style(-opacity) 1
2120    }
2121    if { $_currentColormap == "" } {
2122        set stylelist [$dataobj style $comp]
2123        if { $stylelist != "" } {
2124            array set style $stylelist
2125            set stylelist [array get style]
2126            SetCurrentColormap $stylelist
2127        }
2128        $itk_component(colormap) value $style(-color)
2129    }
2130    SendCmd "cutplane add $tag"
2131    SendCmd "cutplane edges 0 $tag"
2132    SendCmd "cutplane wireframe 0 $tag"
2133    SendCmd "cutplane lighting 1 $tag"
2134    SendCmd "cutplane linewidth 1 $tag"
2135
2136    foreach axis { x y z } {
2137        SendCmd "cutplane slice $axis 0.5 $tag"
2138        SendCmd "cutplane axis $axis 0 $tag"
2139    }
2140    # This is too complicated.  We want to set the colormap, number of
2141    # isolines and opacity for the dataset.  They can be the default values,
2142    # the style hints loaded with the dataset, or set by user controls.  As
2143    # datasets get loaded, they first use the defaults that are overidden
2144    # by the style hints.  If the user changes the global controls, then that
2145    # overrides everything else.  I don't know what it means when global
2146    # controls are specified as style hints by each dataset.  It complicates
2147    # the code to handle aberrant cases.
2148
2149    if { $_changed(isosurfaceOpacity) } {
2150        set style(-opacity) $_settings(isosurfaceOpacity)
2151    }
2152    if { $_changed(numContours) } {
2153        set style(-levels) $_settings(numContours)
2154    }
2155    if { $_changed(colormap) } {
2156        set style(-color) $_settings(colormap)
2157    }
2158    if { $_currentColormap == "" } {
2159        $itk_component(colormap) value $style(-color)
2160    }
2161    set _currentOpacity $style(-opacity)
2162    if { $_currentNumContours != $style(-levels) } {
2163        set _currentNumContours $style(-levels)
2164        set _settings(numContours) $_currentNumContours
2165        $itk_component(numcontours) value $_currentNumContours
2166        UpdateContourList
2167        DrawLegend
2168    }
2169    SendCmd [list contour3d add contourlist $_contourList $tag]
2170    SendCmd "contour3d edges $style(-edges) $tag"
2171    SendCmd "outline add $tag"
2172    SendCmd "outline color [Color2RGB $itk_option(-plotforeground)] $tag"
2173    SendCmd "outline visible $style(-outline) $tag"
2174    set _settings(isosurfaceOutline) $style(-outline)
2175    set _settings(isosurfaceEdges) $style(-edges)
2176    #SendCmd "contour3d color [Color2RGB $settings(-color)] $tag"
2177    SendCmd "contour3d lighting $style(-lighting) $tag"
2178    set _settings(isosurfaceLighting) $style(-lighting)
2179    SendCmd "contour3d linecolor [Color2RGB $style(-edgecolor)] $tag"
2180    SendCmd "contour3d linewidth $style(-linewidth) $tag"
2181    SendCmd "contour3d opacity $_currentOpacity $tag"
2182    set _settings(isosurfaceOpacity) $style(-opacity)
2183    SetCurrentColormap $style(-color)
2184    SendCmd "contour3d wireframe $style(-wireframe) $tag"
2185    set _settings(isosurfaceWireframe) $style(-wireframe)
2186    set _settings(isosurfaceOpacity) [expr $style(-opacity) * 100.0]
2187}
2188
2189itcl::body Rappture::VtkIsosurfaceViewer::IsValidObject { dataobj } {
2190    if {[catch {$dataobj isa Rappture::Field} valid] != 0 || !$valid} {
2191        return 0
2192    }
2193    return 1
2194}
2195
2196#
2197# EnterLegend --
2198#
2199itcl::body Rappture::VtkIsosurfaceViewer::EnterLegend { x y } {
2200    SetLegendTip $x $y
2201}
2202
2203#
2204# MotionLegend --
2205#
2206itcl::body Rappture::VtkIsosurfaceViewer::MotionLegend { x y } {
2207    Rappture::Tooltip::tooltip cancel
2208    set c $itk_component(view)
2209    set cw [winfo width $c]
2210    set ch [winfo height $c]
2211    if { $x >= 0 && $x < $cw && $y >= 0 && $y < $ch } {
2212        SetLegendTip $x $y
2213    }
2214}
2215
2216#
2217# LeaveLegend --
2218#
2219itcl::body Rappture::VtkIsosurfaceViewer::LeaveLegend { } {
2220    Rappture::Tooltip::tooltip cancel
2221    .rappturetooltip configure -icon ""
2222}
2223
2224#
2225# SetLegendTip --
2226#
2227itcl::body Rappture::VtkIsosurfaceViewer::SetLegendTip { x y } {
2228    set fname $_curFldName
2229    set c $itk_component(view)
2230    set w [winfo width $c]
2231    set h [winfo height $c]
2232
2233    set font "Arial 8"
2234    set lineht [font metrics $font -linespace]
2235   
2236    set ih [image height $_image(legend)]
2237    set iy [expr $y - ($lineht + 2)]
2238
2239    if { [string match "component*" $fname] } {
2240        set title ""
2241    } else {
2242        if { [info exists _fields($fname)] } {
2243            foreach { title units } $_fields($fname) break
2244            if { $units != "" } {
2245                set title [format "%s (%s)" $title $units]
2246            }
2247        } else {
2248            set title $fname
2249        }
2250    }
2251    # If there's a legend title, increase the offset by the line height.
2252    if { $title != "" } {
2253        incr iy -$lineht
2254    }
2255    # Make a swatch of the selected color
2256    if { [catch { $_image(legend) get 10 $iy } pixel] != 0 } {
2257        return
2258    }
2259    if { ![info exists _image(swatch)] } {
2260        set _image(swatch) [image create photo -width 24 -height 24]
2261    }
2262    set color [eval format "\#%02x%02x%02x" $pixel]
2263    $_image(swatch) put black  -to 0 0 23 23
2264    $_image(swatch) put $color -to 1 1 22 22
2265    .rappturetooltip configure -icon $_image(swatch)
2266
2267    # Compute the value of the point
2268    if { [info exists _limits($_curFldName)] } {
2269        foreach { vmin vmax } $_limits($_curFldName) break
2270        set t [expr 1.0 - (double($iy) / double($ih-1))]
2271        set value [expr $t * ($vmax - $vmin) + $vmin]
2272    } else {
2273        set value 0.0
2274    }
2275    set tx [expr $x + 15]
2276    set ty [expr $y - 5]
2277    if { [info exists _isolines($y)] } {
2278        Rappture::Tooltip::text $c [format "$title %g (isosurface)" $_isolines($y)]
2279    } else {
2280        Rappture::Tooltip::text $c [format "$title %g" $value]
2281    }
2282    Rappture::Tooltip::tooltip show $c +$tx,+$ty   
2283}
2284
2285
2286# ----------------------------------------------------------------------
2287# USAGE: Slice move x|y|z <newval>
2288#
2289# Called automatically when the user drags the slider to move the
2290# cut plane that slices 3D data.  Gets the current value from the
2291# slider and moves the cut plane to the appropriate point in the
2292# data set.
2293# ----------------------------------------------------------------------
2294itcl::body Rappture::VtkIsosurfaceViewer::Slice {option args} {
2295    switch -- $option {
2296        "move" {
2297            set axis [lindex $args 0]
2298            set a [string toupper $axis]
2299            set oldval $_settings(cutplane${a}Position)
2300            set newval [lindex $args 1]
2301            if {[llength $args] != 2} {
2302                error "wrong # args: should be \"Slice move x|y|z newval\""
2303            }
2304            set newpos [expr {0.01*$newval}]
2305            SendCmd "cutplane slice $axis $newpos"
2306        }
2307        "tooltip" {
2308            set axis [lindex $args 0]
2309            set val [$itk_component(${axis}position) get]
2310            return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
2311        }
2312        default {
2313            error "bad option \"$option\": should be axis, move, or tooltip"
2314        }
2315    }
2316}
2317
2318#
2319# ReceiveLegend --
2320#
2321#       Invoked automatically whenever the "legend" command comes in from
2322#       the rendering server.  Indicates that binary image data with the
2323#       specified <size> will follow.
2324#
2325itcl::body Rappture::VtkIsosurfaceViewer::ReceiveLegend { colormap title min max size } {
2326    #puts stderr "ReceiveLegend colormap=$colormap title=$title range=$min,$max size=$size"
2327    set _title $title
2328    regsub {\(mag\)} $title "" _title
2329    if { [IsConnected] } {
2330        set bytes [ReceiveBytes $size]
2331        if { ![info exists _image(legend)] } {
2332            set _image(legend) [image create photo]
2333        }
2334        $_image(legend) configure -data $bytes
2335        #puts stderr "read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
2336        if { [catch {DrawLegend} errs] != 0 } {
2337            global errorInfo
2338            puts stderr "errs=$errs errorInfo=$errorInfo"
2339        }
2340    }
2341}
2342
2343#
2344# DrawLegend --
2345#
2346#       Draws the legend in the own canvas on the right side of the plot area.
2347#
2348itcl::body Rappture::VtkIsosurfaceViewer::DrawLegend {} {
2349    set fname $_curFldName
2350    set c $itk_component(view)
2351    set w [winfo width $c]
2352    set h [winfo height $c]
2353    set font "Arial 8"
2354    set lineht [font metrics $font -linespace]
2355   
2356    if { [string match "component*" $fname] } {
2357        set title ""
2358    } else {
2359        if { [info exists _fields($fname)] } {
2360            foreach { title units } $_fields($fname) break
2361            if { $units != "" } {
2362                set title [format "%s (%s)" $title $units]
2363            }
2364        } else {
2365            set title $fname
2366        }
2367    }
2368    set x [expr $w - 2]
2369    if { !$_settings(legendVisible) } {
2370        $c delete legend
2371        return
2372    }
2373    if { [$c find withtag "legend"] == "" } {
2374        set y 2
2375        # If there's a legend title, create a text item for the title.
2376        $c create text $x $y \
2377                -anchor ne \
2378                -fill $itk_option(-plotforeground) -tags "title legend" \
2379                -font $font
2380            incr y $lineht
2381        $c create text $x $y \
2382            -anchor ne \
2383            -fill $itk_option(-plotforeground) -tags "vmax legend" \
2384            -font $font
2385        incr y $lineht
2386        $c create image $x $y \
2387            -anchor ne \
2388            -image $_image(legend) -tags "colormap legend"
2389        $c create rectangle $x $y 1 1 \
2390            -fill "" -outline "" -tags "sensor legend"
2391        $c create text $x [expr {$h-2}] \
2392            -anchor se \
2393            -fill $itk_option(-plotforeground) -tags "vmin legend" \
2394            -font $font
2395        $c bind sensor <Enter> [itcl::code $this EnterLegend %x %y]
2396        $c bind sensor <Leave> [itcl::code $this LeaveLegend]
2397        $c bind sensor <Motion> [itcl::code $this MotionLegend %x %y]
2398    }
2399    $c delete isoline
2400    set x2 $x
2401    set iw [image width $_image(legend)]
2402    set ih [image height $_image(legend)]
2403    set x1 [expr $x2 - ($iw*12)/10]
2404    set color $_settings(isolineColor)
2405    # Draw the isolines on the legend.
2406    array unset _isolines
2407    if { $color != "none"  && [info exists _limits($_curFldName)] &&
2408         $_settings(numContours) > 0 } {
2409
2410        foreach { vmin vmax } $_limits($_curFldName) break
2411        set range [expr double($vmax - $vmin)]
2412        if { $range <= 0.0 } {
2413            set range 1.0;              # Min is greater or equal to max.
2414        }
2415        set tags "isoline legend"
2416        set offset [expr 2 + $lineht]
2417        if { $title != "" } {
2418            incr offset $lineht
2419        }
2420        foreach value $_contourList {
2421            set norm [expr 1.0 - (($value - $vmin) / $range)]
2422            set y1 [expr int(round(($norm * $ih) + $offset))]
2423            for { set off 0 } { $off < 3 } { incr off } {
2424                set _isolines([expr $y1 + $off]) $value
2425                set _isolines([expr $y1 - $off]) $value
2426            }
2427            $c create line $x1 $y1 $x2 $y1 -fill $color -tags $tags
2428        }
2429    }
2430
2431    $c bind title <ButtonPress> [itcl::code $this Combo post]
2432    $c bind title <Enter> [itcl::code $this Combo activate]
2433    $c bind title <Leave> [itcl::code $this Combo deactivate]
2434    # Reset the item coordinates according the current size of the plot.
2435    $c itemconfigure title -text $title
2436    if { [info exists _limits($_curFldName)] } {
2437        foreach { vmin vmax } $_limits($_curFldName) break
2438        $c itemconfigure vmin -text [format %g $vmin]
2439        $c itemconfigure vmax -text [format %g $vmax]
2440    }
2441    set y 2
2442    # If there's a legend title, move the title to the correct position
2443    if { $title != "" } {
2444        $c itemconfigure title -text $title
2445        $c coords title $x $y
2446        incr y $lineht
2447        $c raise title
2448    }
2449    $c coords vmax $x $y
2450    incr y $lineht
2451    $c coords colormap $x $y
2452    $c coords sensor [expr $x - $iw] $y $x [expr $y + $ih]
2453    $c raise sensor
2454    $c coords vmin $x [expr {$h - 2}]
2455}
2456
2457# ----------------------------------------------------------------------
2458# USAGE: _dropdown post
2459# USAGE: _dropdown unpost
2460# USAGE: _dropdown select
2461#
2462# Used internally to handle the dropdown list for this combobox.  The
2463# post/unpost options are invoked when the list is posted or unposted
2464# to manage the relief of the controlling button.  The select option
2465# is invoked whenever there is a selection from the list, to assign
2466# the value back to the gauge.
2467# ----------------------------------------------------------------------
2468itcl::body Rappture::VtkIsosurfaceViewer::Combo {option} {
2469    set c $itk_component(view)
2470    switch -- $option {
2471        post {
2472            foreach { x1 y1 x2 y2 } [$c bbox title] break
2473            set cw [winfo width $itk_component(view)]
2474            set mw [winfo reqwidth $itk_component(fieldmenu)]
2475            set x1 [expr $cw - $mw]
2476            set x [expr $x1 + [winfo rootx $itk_component(view)]]
2477            set y [expr $y2 + [winfo rooty $itk_component(view)]]
2478            tk_popup $itk_component(fieldmenu) $x $y
2479        }
2480        activate {
2481            $c itemconfigure title -fill red
2482        }
2483        deactivate {
2484            $c itemconfigure title -fill $itk_option(-plotforeground)
2485        }
2486        invoke {
2487            $itk_component(field) value $_curFldLabel
2488            AdjustSetting field
2489        }
2490        default {
2491            error "bad option \"$option\": should be post, unpost, select"
2492        }
2493    }
2494}
2495
2496#
2497# SetCurrentColormap --
2498#
2499itcl::body Rappture::VtkIsosurfaceViewer::SetCurrentColormap { name } {
2500    # Keep track of the colormaps that we build.
2501    if { ![info exists _colormaps($name)] } {
2502        BuildColormap $name
2503        set _colormaps($name) 1
2504    }
2505    set _currentColormap $name
2506    SendCmd "contour3d colormap $_currentColormap"
2507}
2508
2509#
2510# BuildColormap --
2511#
2512#       Build the designated colormap on the server.
2513#
2514itcl::body Rappture::VtkIsosurfaceViewer::BuildColormap { name } {
2515    set cmap [ColorsToColormap $name]
2516    if { [llength $cmap] == 0 } {
2517        set cmap "0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0"
2518    }
2519    set wmap "0.0 1.0 1.0 1.0"
2520    SendCmd "colormap add $name { $cmap } { $wmap }"
2521}
2522
2523itcl::body Rappture::VtkIsosurfaceViewer::SetOrientation { side } {
2524    array set positions {
2525        front "1 0 0 0"
2526        back  "0 0 1 0"
2527        left  "0.707107 0 -0.707107 0"
2528        right "0.707107 0 0.707107 0"
2529        top   "0.707107 -0.707107 0 0"
2530        bottom "0.707107 0.707107 0 0"
2531    }
2532    foreach name { qw qx qy qz } value $positions($side) {
2533        set _view($name) $value
2534    }
2535    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
2536    $_arcball quaternion $q
2537    SendCmd "camera orient $q"
2538    SendCmd "camera reset"
2539    set _view(xpan) 0
2540    set _view(ypan) 0
2541    set _view(zoom) 1.0
2542}
2543
2544itcl::body Rappture::VtkIsosurfaceViewer::UpdateContourList {} {
2545    if { ![info exists _limits($_curFldName)] } {
2546        return
2547    }
2548    foreach { vmin vmax } $_limits($_curFldName) break
2549    set v [blt::vector create \#auto]
2550    $v seq $vmin $vmax [expr $_currentNumContours+2]
2551    $v delete end 0
2552    set _contourList [$v range 0 end]
2553    blt::vector destroy $v
2554}
Note: See TracBrowser for help on using the repository browser.