source: branches/1.3/gui/scripts/vtkisosurfaceviewer.tcl @ 4470

Last change on this file since 4470 was 4470, checked in by ldelgass, 10 years ago

remove debugging print

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