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

Last change on this file since 4735 was 4735, checked in by ldelgass, 6 years ago

Try to keep style names more consistent.

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