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

Last change on this file since 4352 was 4352, checked in by gah, 7 years ago

bug fix: -isosurfacevisible sets all surfaces to visible

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