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

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

Remove unused variable reference

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