source: trunk/gui/scripts/vtkheightmapviewer.tcl @ 3459

Last change on this file since 3459 was 3459, checked in by ldelgass, 11 years ago

Fix error on setting axis units (found in contour example: Mesh-grid-hybrid)

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