source: branches/1.7/gui/scripts/vtkheightmapviewer.tcl @ 6306

Last change on this file since 6306 was 6306, checked in by ldelgass, 8 years ago

merge fixes from trunk

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