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

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

Move ColorsToColormap? into base VisViewer? class

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