source: branches/1.3/gui/scripts/vtkheightmapviewer.tcl @ 4399

Last change on this file since 4399 was 4399, checked in by gah, 10 years ago

fix builder path, update isosurfaceviewer

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