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

Last change on this file since 3429 was 3429, checked in by gah, 12 years ago

fix for sequence of contours

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