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

Last change on this file since 3638 was 3638, checked in by gah, 11 years ago

fix ruby getstring for binary strings

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