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

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

merge r4642 from trunk

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