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

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

add axis exp 0 0 0 1

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