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

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

add octave/MATLAB version of example

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