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

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

Add support for discrete (step function) colormaps in heightmap viewer.

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