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

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

fixes for new stats file

File size: 80.1 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        if 1 {
913            # Tell the server the name of the tool, the version, and dataset
914            # that we are rendering.  Have to do it here because we don't know
915            # what data objects are using the renderer until be get here.
916            global env
917
918            set info {}
919            set user "???"
920            if { [info exists env(USER)] } {
921                set user $env(USER)
922            }
923            set session "???"
924            if { [info exists env(SESSION)] } {
925                set session $env(SESSION)
926            }
927            lappend info "hub" [exec hostname]
928            lappend info "client" "vtkheightmapviewer"
929            lappend info "user" $user
930            lappend info "session" $session
931            SendCmd "clientinfo [list $info]"
932        }
933        InitSettings isHeightmap background
934        #
935        # Reset the camera and other view parameters
936        #
937        SendCmd "axis color all [Color2RGB $itk_option(-plotforeground)]"
938        SendCmd "axis lrot z 90"
939        set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
940        $_arcball quaternion $q
941        if {$_settings(isHeightmap) } {
942            SendCmd "camera reset"
943            if { $_view(ortho)} {
944                SendCmd "camera mode ortho"
945            } else {
946                SendCmd "camera mode persp"
947            }
948        }           
949        DoRotate
950        PanCamera
951    }
952    set _first ""
953
954    #SendCmd "imgflush"
955
956    set _first ""
957    # Start off with no datasets are visible.
958    SendCmd "dataset visible 0"
959    set scale [GetHeightmapScale]
960    foreach dataobj [get -objects] {
961        if { [info exists _obj2ovride($dataobj-raise)] &&  $_first == "" } {
962            set _first $dataobj
963        }
964        scale $dataobj
965        set _obj2datasets($dataobj) ""
966        foreach comp [$dataobj components] {
967            set tag $dataobj-$comp
968            if { ![info exists _datasets($tag)] } {
969                set bytes [$dataobj vtkdata $comp]
970                if 0 {
971                    set f [open /tmp/vtkheightmap.vtk "w"]
972                    puts $f $bytes
973                    close $f
974                }
975                set length [string length $bytes]
976                if 1 {
977                    set info {}
978                    lappend info "tool_id"       [$dataobj hints toolId]
979                    lappend info "tool_name"     [$dataobj hints toolName]
980                    lappend info "tool_version"  [$dataobj hints toolRevision]
981                    lappend info "tool_title"    [$dataobj hints toolTitle]
982                    lappend info "dataset_label" [$dataobj hints label]
983                    lappend info "dataset_size"  $length
984                    SendCmd [list "clientinfo" $info]
985                }
986                append _outbuf "dataset add $tag data follows $length\n"
987                append _outbuf $bytes
988                set _datasets($tag) 1
989                SetObjectStyle $dataobj $comp
990            }
991            lappend _obj2datasets($dataobj) $tag
992            if { [info exists _obj2ovride($dataobj-raise)] } {
993                SendCmd "heightmap visible 1 $tag"
994            }
995            if { ![info exists _comp2scale($tag)] ||
996                 $_comp2scale($tag) != $scale } {
997                SendCmd "heightmap heightscale $scale $tag"
998                set _comp2scale($tag) $scale
999            }
1000        }
1001    }
1002    if { $_first != "" && $_reset } {
1003        set _fieldNames [$_first hints fieldnames]
1004        set _fieldUnits [$_first hints fieldunits]
1005        set _fieldLabels [$_first hints fieldlabels]
1006        $itk_component(field) choices delete 0 end
1007        $itk_component(fieldmenu) delete 0 end
1008        array unset _fields
1009        foreach name $_fieldNames title $_fieldLabels units $_fieldUnits {
1010            SendCmd "dataset maprange explicit $_limits(v) $name"
1011            if { $title == "" } {
1012                set title $name
1013            }
1014            $itk_component(field) choices insert end "$name" "$title"
1015            $itk_component(fieldmenu) add radiobutton -label "$title" \
1016                -value $title -variable [itcl::scope _curFldName] \
1017                -selectcolor red \
1018                -activebackground $itk_option(-plotbackground) \
1019                -activeforeground $itk_option(-plotforeground) \
1020                -font "Arial 8" \
1021                -command [itcl::code $this Combo invoke]
1022            set _fields($name) [list $title $units]
1023            set _curFldName $name
1024        }
1025        if { [array size _fields] == 1 } {
1026            set _curFldName $_fieldLabels
1027            if { $_curFldName == "" } {
1028                puts stderr "no default name from field"
1029                set _curFldName "Default"
1030            }
1031        }
1032        $itk_component(field) value $_curFldName
1033    }
1034    InitSettings stretchToFit
1035
1036    if { $_reset } {
1037        SendCmd "axis tickpos outside"
1038        foreach axis { x y z } {
1039            SendCmd "axis lformat $axis %g"
1040        }
1041        foreach axis { x y z } {
1042            set label [$_first hints ${axis}label]
1043            if { $label == "" } {
1044                if {$axis == "z"} {
1045                    if { $_curFldName == "component" } {
1046                        set label [string toupper $axis]
1047                    } else {
1048                        set label [lindex $_fields($_curFldName) 0]
1049                    }
1050                } else {
1051                    set label [string toupper $axis]
1052                }
1053            }
1054            # May be a space in the axis label.
1055            SendCmd [list axis name $axis $label]
1056
1057            if {$axis == "z" && [$_first hints ${axis}units] == ""} {
1058                set units [lindex $_fields($_curFldName) 1]
1059            } else {
1060                set units [$_first hints ${axis}units]
1061            }
1062            if { $units != "" } {
1063                # May be a space in the axis units.
1064                SendCmd [list axis units $axis $units]
1065            }
1066        }
1067        #
1068        # Reset the camera and other view parameters
1069        #
1070        SendCmd "axis color all [Color2RGB $itk_option(-plotforeground)]"
1071        ResetAxes
1072        set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1073        $_arcball quaternion $q
1074        if {$_settings(isHeightmap) } {
1075            SendCmd "camera reset"
1076            if { $_view(ortho)} {
1077                SendCmd "camera mode ortho"
1078            } else {
1079                SendCmd "camera mode persp"
1080            }
1081        }
1082        DoRotate
1083        PanCamera
1084        InitSettings axisXGrid axisYGrid axisZGrid \
1085            axisVisible axisLabels
1086        InitSettings heightmapOpacity \
1087            heightmapScale lighting \
1088            colormap field outline \
1089            edges heightmapOpacity wireframe
1090        set _reset 0
1091    }
1092    global readyForNextFrame
1093    set readyForNextFrame 0;            # Don't advance to the next frame
1094    set _buffering 0;                   # Turn off buffering.
1095
1096    # Actually write the commands to the server socket.  If it fails, we don't
1097    # care.  We're finished here.
1098    blt::busy hold $itk_component(hull)
1099    sendto $_outbuf;                       
1100    blt::busy release $itk_component(hull)
1101    set _outbuf "";                        # Clear the buffer.               
1102}
1103
1104# ----------------------------------------------------------------------
1105# USAGE: CurrentDatasets ?-all -visible? ?dataobjs?
1106#
1107# Returns a list of server IDs for the current datasets being displayed.  This
1108# is normally a single ID, but it might be a list of IDs if the current data
1109# object has multiple components.
1110# ----------------------------------------------------------------------
1111itcl::body Rappture::VtkHeightmapViewer::CurrentDatasets {args} {
1112    set flag [lindex $args 0]
1113    switch -- $flag {
1114        "-all" {
1115            if { [llength $args] > 1 } {
1116                error "CurrentDatasets: can't specify dataobj after \"-all\""
1117            }
1118            set dlist [get -objects]
1119        }
1120        "-visible" {
1121            if { [llength $args] > 1 } {
1122                set dlist {}
1123                set args [lrange $args 1 end]
1124                foreach dataobj $args {
1125                    if { [info exists _obj2ovride($dataobj-raise)] } {
1126                        lappend dlist $dataobj
1127                    }
1128                }
1129            } else {
1130                set dlist [get -visible]
1131            }
1132        }           
1133        default {
1134            set dlist $args
1135        }
1136    }
1137    set rlist ""
1138    foreach dataobj $dlist {
1139        foreach comp [$dataobj components] {
1140            set tag $dataobj-$comp
1141            if { [info exists _datasets($tag)] && $_datasets($tag) } {
1142                lappend rlist $tag
1143            }
1144        }
1145    }
1146    return $rlist
1147}
1148
1149# ----------------------------------------------------------------------
1150# USAGE: Zoom in
1151# USAGE: Zoom out
1152# USAGE: Zoom reset
1153#
1154# Called automatically when the user clicks on one of the zoom
1155# controls for this widget.  Changes the zoom for the current view.
1156# ----------------------------------------------------------------------
1157itcl::body Rappture::VtkHeightmapViewer::Zoom {option} {
1158    switch -- $option {
1159        "in" {
1160            set _view(zoom) [expr {$_view(zoom)*1.25}]
1161            SendCmd "camera zoom $_view(zoom)"
1162        }
1163        "out" {
1164            set _view(zoom) [expr {$_view(zoom)*0.8}]
1165            SendCmd "camera zoom $_view(zoom)"
1166        }
1167        "reset" {
1168            array set _view {
1169                qw      0.36
1170                qx      0.25
1171                qy      0.50
1172                qz      0.70
1173                zoom    1.0
1174                xpan    0
1175                ypan    0
1176            }
1177            SendCmd "camera reset all"
1178            if { $_first != "" } {
1179                set location [$_first hints camera]
1180                if { $location != "" } {
1181                    array set _view $location
1182                }
1183            }
1184            set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1185            $_arcball quaternion $q
1186            DoRotate
1187        }
1188    }
1189}
1190
1191itcl::body Rappture::VtkHeightmapViewer::PanCamera {} {
1192    set x $_view(xpan)
1193    set y $_view(ypan)
1194    SendCmd "camera pan $x $y"
1195}
1196
1197
1198# ----------------------------------------------------------------------
1199# USAGE: Rotate click <x> <y>
1200# USAGE: Rotate drag <x> <y>
1201# USAGE: Rotate release <x> <y>
1202#
1203# Called automatically when the user clicks/drags/releases in the
1204# plot area.  Moves the plot according to the user's actions.
1205# ----------------------------------------------------------------------
1206itcl::body Rappture::VtkHeightmapViewer::Rotate {option x y} {
1207    switch -- $option {
1208        "click" {
1209            $itk_component(view) configure -cursor fleur
1210            set _click(x) $x
1211            set _click(y) $y
1212        }
1213        "drag" {
1214            if {[array size _click] == 0} {
1215                Rotate click $x $y
1216            } else {
1217                set w [winfo width $itk_component(view)]
1218                set h [winfo height $itk_component(view)]
1219                if {$w <= 0 || $h <= 0} {
1220                    return
1221                }
1222
1223                if {[catch {
1224                    # this fails sometimes for no apparent reason
1225                    set dx [expr {double($x-$_click(x))/$w}]
1226                    set dy [expr {double($y-$_click(y))/$h}]
1227                }]} {
1228                    return
1229                }
1230                if { $dx == 0 && $dy == 0 } {
1231                    return
1232                }
1233                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1234                EventuallyRotate $q
1235                set _click(x) $x
1236                set _click(y) $y
1237            }
1238        }
1239        "release" {
1240            Rotate drag $x $y
1241            $itk_component(view) configure -cursor ""
1242            catch {unset _click}
1243        }
1244        default {
1245            error "bad option \"$option\": should be click, drag, release"
1246        }
1247    }
1248}
1249
1250itcl::body Rappture::VtkHeightmapViewer::Pick {x y} {
1251    foreach tag [CurrentDatasets -visible] {
1252        SendCmd "dataset getscalar pixel $x $y $tag"
1253    }
1254}
1255
1256# ----------------------------------------------------------------------
1257# USAGE: $this Pan click x y
1258#        $this Pan drag x y
1259#        $this Pan release x y
1260#
1261# Called automatically when the user clicks on one of the zoom
1262# controls for this widget.  Changes the zoom for the current view.
1263# ----------------------------------------------------------------------
1264itcl::body Rappture::VtkHeightmapViewer::Pan {option x y} {
1265    switch -- $option {
1266        "set" {
1267            set w [winfo width $itk_component(view)]
1268            set h [winfo height $itk_component(view)]
1269            set x [expr $x / double($w)]
1270            set y [expr $y / double($h)]
1271            set _view(xpan) [expr $_view(xpan) + $x]
1272            set _view(ypan) [expr $_view(ypan) + $y]
1273            PanCamera
1274            return
1275        }
1276        "click" {
1277            set _click(x) $x
1278            set _click(y) $y
1279            $itk_component(view) configure -cursor hand1
1280        }
1281        "drag" {
1282            if { ![info exists _click(x)] } {
1283                set _click(x) $x
1284            }
1285            if { ![info exists _click(y)] } {
1286                set _click(y) $y
1287            }
1288            set w [winfo width $itk_component(view)]
1289            set h [winfo height $itk_component(view)]
1290            set dx [expr ($_click(x) - $x)/double($w)]
1291            set dy [expr ($_click(y) - $y)/double($h)]
1292            set _click(x) $x
1293            set _click(y) $y
1294            set _view(xpan) [expr $_view(xpan) - $dx]
1295            set _view(ypan) [expr $_view(ypan) - $dy]
1296            PanCamera
1297        }
1298        "release" {
1299            Pan drag $x $y
1300            $itk_component(view) configure -cursor ""
1301        }
1302        default {
1303            error "unknown option \"$option\": should set, click, drag, or release"
1304        }
1305    }
1306}
1307
1308# ----------------------------------------------------------------------
1309# USAGE: InitSettings <what> ?<value>?
1310#
1311# Used internally to update rendering settings whenever parameters
1312# change in the popup settings panel.  Sends the new settings off
1313# to the back end.
1314# ----------------------------------------------------------------------
1315itcl::body Rappture::VtkHeightmapViewer::InitSettings { args } {
1316    foreach spec $args {
1317        if { [info exists _settings($_first-$spec)] } {
1318            # Reset global setting with dataobj specific setting
1319            set _settings($spec) $_settings($_first-$spec)
1320        }
1321        AdjustSetting $spec
1322    }
1323}
1324
1325#
1326# AdjustSetting --
1327#
1328#       Changes/updates a specific setting in the widget.  There are
1329#       usually user-setable option.  Commands are sent to the render
1330#       server.
1331#
1332itcl::body Rappture::VtkHeightmapViewer::AdjustSetting {what {value ""}} {
1333    if { $_beforeConnect } {
1334        return
1335    }
1336    switch -- $what {
1337        "heightmapOpacity" {
1338            set val $_settings(heightmapOpacity)
1339            set sval [expr { 0.01 * double($val) }]
1340            foreach dataset [CurrentDatasets -all] {
1341                SendCmd "heightmap opacity $sval $dataset"
1342            }
1343        }
1344        "wireframe" {
1345            set bool $_settings(wireframe)
1346            foreach dataset [CurrentDatasets -all] {
1347                SendCmd "heightmap wireframe $bool $dataset"
1348            }
1349        }
1350        "colormapVisible" {
1351            set bool $_settings(colormapVisible)
1352            foreach dataset [CurrentDatasets -all] {
1353                SendCmd "heightmap surface $bool $dataset"
1354            }
1355        }
1356        "isolinesVisible" {
1357            set bool $_settings(isolinesVisible)
1358            foreach dataset [CurrentDatasets -all] {
1359                SendCmd "heightmap isolines $bool $dataset"
1360            }
1361        }
1362        "lighting" {
1363            if { $_settings(isHeightmap) } {
1364                set bool $_settings(lighting)
1365                SendCmd "heightmap lighting $bool"
1366            } else {
1367                SendCmd "heightmap lighting 0"
1368            }
1369        }
1370        "edges" {
1371            set bool $_settings(edges)
1372            foreach dataset [CurrentDatasets -all] {
1373                SendCmd "heightmap edges $bool $dataset"
1374            }
1375        }
1376        "axisVisible" {
1377            set bool $_settings(axisVisible)
1378            SendCmd "axis visible all $bool"
1379        }
1380        "axisLabels" {
1381            set bool $_settings(axisLabels)
1382            SendCmd "axis labels all $bool"
1383        }
1384        "axisXGrid" - "axisYGrid" - "axisZGrid" {
1385            set axis [string tolower [string range $what 4 4]]
1386            set bool $_settings($what)
1387            SendCmd "axis grid $axis $bool"
1388        }
1389        "axisFlymode" {
1390            set mode [$itk_component(axisflymode) value]
1391            set mode [$itk_component(axisflymode) translate $mode]
1392            set _settings($what) $mode
1393            SendCmd "axis flymode $mode"
1394        }
1395        "axisMinorTicks" {
1396            set bool $_settings(axisMinorTicks)
1397            foreach axis { x y z } {
1398                SendCmd "axis minticks ${axis} $bool"
1399            }
1400        }
1401        "isolines" {
1402            set n $_settings($what)
1403            EventuallyContour $n
1404        }
1405        "isolinesVisible" {
1406            set bool $_settings($what)
1407            foreach dataset [CurrentDatasets -all] {
1408                SendCmd "heightmap isolines $bool $dataset"
1409            }
1410        }
1411        "colormapVisible" {
1412            set bool $_settings($what)
1413            foreach dataset [CurrentDatasets -all] {
1414                SendCmd "heightmap surface $bool $dataset"
1415            }
1416        }
1417        "background" {
1418            set bgcolor [$itk_component(background) value]
1419            array set fgcolors {
1420                "black" "white"
1421                "white" "black"
1422                "grey"  "black"
1423            }
1424            configure -plotbackground $bgcolor \
1425                -plotforeground $fgcolors($bgcolor)
1426            $itk_component(view) delete "legend"
1427            DrawLegend $_curFldName
1428        }
1429        "isolineColor" {
1430            set color [$itk_component(isolinecolor) value]
1431            if { $color == "none" } {
1432                if { $_settings(isolinesVisible) } {
1433                    SendCmd "heightmap isolines 0"
1434                    set _settings(isolinesVisible) 0
1435                }
1436            } else {
1437                if { !$_settings(isolinesVisible) } {
1438                    SendCmd "heightmap isolines 1"
1439                    set _settings(isolinesVisible) 1
1440                }
1441                SendCmd "heightmap isolinecolor [Color2RGB $color]"
1442            }
1443            DrawLegend $_curFldName
1444        }
1445        "colormap" {
1446            set color [$itk_component(colormap) value]
1447            set _settings(colormap) $color
1448            if { $color == "none" } {
1449                if { $_settings(colormapVisible) } {
1450                    SendCmd "heightmap surface 0"
1451                    set _settings(colormapVisible) 0
1452                }
1453            } else {
1454                if { !$_settings(colormapVisible) } {
1455                    SendCmd "heightmap surface 1"
1456                    set _settings(colormapVisible) 1
1457                }
1458                ResetColormap $color
1459                SendCmd "heightmap colormap $_currentColormap"
1460            }
1461            SendCmdNoWait "heightmap colormode scalar $_curFldName"
1462            SendCmdNoWait "dataset scalar $_curFldName"
1463            EventuallyRequestLegend
1464        }
1465        "heightmapOpacity" {
1466            set val $_settings(heightmapOpacity)
1467            set sval [expr { 0.01 * double($val) }]
1468            foreach dataset [CurrentDatasets -all] {
1469                SendCmd "heightmap opacity $sval $dataset"
1470            }
1471        }
1472        "heightmapScale" {
1473            if { $_settings(isHeightmap) } {
1474                set scale [GetHeightmapScale]
1475                foreach dataset [CurrentDatasets -all] {
1476                    SendCmd "heightmap heightscale $scale $dataset"
1477                    set _comp2scale($dataset) $scale
1478                }
1479                ResetAxes
1480            }
1481        }
1482        "lighting" {
1483            if { $_settings(isHeightmap) } {
1484                set bool $_settings(lighting)
1485                SendCmd "heightmap lighting $bool"
1486            } else {
1487                SendCmd "heightmap lighting 0"
1488            }
1489        }
1490        "field" {
1491            set new   [$itk_component(field) value]
1492            set value [$itk_component(field) translate $new]
1493            set _settings(field) $value
1494            if { [info exists _fields($new)] } {
1495                set _colorMode scalar
1496                set _curFldName $new
1497            } else {
1498                puts stderr "unknown field \"$new\""
1499                return
1500            }
1501            EventuallyRequestLegend
1502        }
1503        "stretchToFit" {
1504            set bool $_settings(stretchToFit)
1505            if { $bool } {
1506                set heightScale [GetHeightmapScale]
1507                if {$heightScale == 0} {
1508                    SendCmd "camera aspect window"
1509                } else {
1510                    SendCmd "camera aspect square"
1511                }
1512            } else {
1513                SendCmd "camera aspect native"
1514            }
1515        }
1516        "outline" {
1517            set bool $_settings(outline)
1518            SendCmd "dataset outline $bool"
1519        }
1520        "isHeightmap" {
1521            set bool $_settings(isHeightmap)
1522            if { $bool } {
1523                $itk_component(lighting) configure -state normal
1524            } else {
1525                $itk_component(lighting) configure -state disabled
1526            }
1527            set _settings(lighting) $bool
1528            # Fix heightmap scale: 0 for contours, 1 for heightmaps.
1529            if { $bool } {
1530                set _settings(heightmapScale) 50
1531            } else {
1532                set _settings(heightmapScale) 50
1533            }
1534            SendCmd "heightmap lighting $bool"
1535            set scale [GetHeightmapScale]
1536            foreach dataset [CurrentDatasets -all] {
1537                SendCmd "heightmap heightscale $scale $dataset"
1538                set _comp2scale($dataset) $scale
1539            }
1540            if {$_settings(stretchToFit)} {
1541                if {$scale == 0} {
1542                    SendCmd "camera aspect window"
1543                } else {
1544                    SendCmd "camera aspect square"
1545                }
1546            }
1547            ResetAxes
1548            # Fix the mouse bindings for rotation/panning and the
1549            # camera mode. Ideally we'd create a bindtag for these.
1550            set c $itk_component(view)
1551            if { $bool } {
1552                # Bindings for rotation via mouse
1553                bind $c <ButtonPress-1> \
1554                    [itcl::code $this Rotate click %x %y]
1555                bind $c <B1-Motion> \
1556                    [itcl::code $this Rotate drag %x %y]
1557                bind $c <ButtonRelease-1> \
1558                    [itcl::code $this Rotate release %x %y]
1559                set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1560                $_arcball quaternion $q
1561                if {$_view(ortho)} {
1562                    SendCmd "camera mode ortho"
1563                } else {
1564                    SendCmd "camera mode persp"
1565                }
1566                SendCmd "camera orient $q"
1567            } else {
1568                set _settings(heightmapScale) 0
1569                bind $c <ButtonPress-1> {}
1570                bind $c <B1-Motion> {}
1571                bind $c <ButtonRelease-1> {}
1572                SendCmd "camera mode image"
1573            }
1574        }
1575        "legendVisible" {
1576            if { !$_settings(legendVisible) } {
1577                $itk_component(view) delete legend
1578            }
1579            DrawLegend $_curFldName
1580        }
1581        default {
1582            error "don't know how to fix $what"
1583        }
1584    }
1585}
1586
1587#
1588# RequestLegend --
1589#
1590#       Request a new legend from the server.  The size of the legend
1591#       is determined from the height of the canvas. 
1592#
1593# This should be called when
1594#       1.  A new current colormap is set.
1595#       2.  Window is resized.
1596#       3.  The limits of the data have changed.  (Just need a redraw).
1597#       4.  Number of isolines have changed. (Just need a redraw).
1598#       5.  Legend becomes visible (Just need a redraw).
1599#
1600itcl::body Rappture::VtkHeightmapViewer::RequestLegend {} {
1601    set _legendPending 0
1602    set font "Arial 8"
1603    set lineht [font metrics $font -linespace]
1604    set c $itk_component(view)
1605    set w 12
1606    set h [expr {$_height - 2 * ($lineht + 2)}]
1607    if { $h < 1} {
1608        return
1609    }
1610    if { [info exists _fields($_curFldName)] } {
1611        set title [lindex $_fields($_curFldName) 0]
1612        if { $title != "component" } {
1613            set h [expr $h - ($lineht + 2)]
1614        }
1615    } else {
1616        return
1617    }
1618    # Set the legend on the first heightmap dataset.
1619    if { $_currentColormap != ""  } {
1620        set cmap $_currentColormap
1621        SendCmdNoWait "legend $cmap scalar $_curFldName {} $w $h 0"
1622        SendCmdNoWait "heightmap colormode scalar $_curFldName"
1623        SendCmdNoWait "dataset scalar $_curFldName"
1624    }
1625}
1626
1627#
1628# ResetAxes --
1629#
1630#       Set axis z bounds and range
1631#
1632itcl::body Rappture::VtkHeightmapViewer::ResetAxes {} {
1633    if { ![info exists _limits(v)] || ![info exists _fields($_curFldName)]} {
1634        SendCmd "dataset maprange all"
1635        SendCmd "axis autorange z on"
1636        SendCmd "axis autobounds z on"
1637        return
1638    }
1639    foreach { vmin vmax } $_limits(v) break
1640    foreach { xmin xmax } $_limits(x) break
1641    foreach { ymin ymax } $_limits(y) break
1642    set dataRange   [expr $vmax - $vmin]
1643    set boundsRange [expr $xmax - $xmin]
1644    set r [expr $ymax - $ymin]
1645    if {$r > $boundsRange} {
1646        set boundsRange $r
1647    }
1648    if {$dataRange < 1.0e-10} {
1649        set dataScale 1.0
1650    } else {
1651        set dataScale [expr $boundsRange / $dataRange]
1652    }
1653    set heightScale [GetHeightmapScale]
1654    set bMin [expr $heightScale * $dataScale * $vmin]
1655    set bMax [expr $heightScale * $dataScale * $vmax]
1656    set fieldName [lindex $_fields($_curFldName) 0]
1657    SendCmd "dataset maprange explicit $_limits(v) $fieldName"
1658    SendCmd "axis bounds z $bMin $bMax"
1659    SendCmd "axis range z $_limits(v)"
1660}
1661
1662#
1663# SetCurrentColormap --
1664#
1665itcl::body Rappture::VtkHeightmapViewer::SetCurrentColormap { stylelist } {
1666    array set style {
1667        -color BCGYR
1668        -levels 10
1669        -opacity 1.0
1670    }
1671    array set style $stylelist
1672
1673    set name "$style(-color):$style(-levels):$style(-opacity)"
1674    if { ![info exists _colormaps($name)] } {
1675        set stylelist [array get style]
1676        BuildColormap $name $stylelist
1677        set _colormaps($name) $stylelist
1678    }
1679    set _currentColormap $name
1680}
1681
1682
1683#
1684# BuildColormap --
1685#
1686itcl::body Rappture::VtkHeightmapViewer::BuildColormap { name stylelist } {
1687    array set style $stylelist
1688    set cmap [ColorsToColormap $style(-color)]
1689    if { [llength $cmap] == 0 } {
1690        set cmap "0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0"
1691    }
1692    if { ![info exists _settings(heightmapOpacity)] } {
1693        set _settings(heightmapOpacity) $style(-opacity)
1694    }
1695    set max $_settings(heightmapOpacity)
1696
1697    set wmap "0.0 1.0 1.0 1.0"
1698    SendCmd "colormap add $name { $cmap } { $wmap }"
1699}
1700
1701# ----------------------------------------------------------------------
1702# CONFIGURATION OPTION: -mode
1703# ----------------------------------------------------------------------
1704itcl::configbody Rappture::VtkHeightmapViewer::mode {
1705    switch -- $itk_option(-mode) {
1706        "heightmap" {
1707            set _settings(isHeightmap) 1
1708        }
1709        "contour" {
1710            set _settings(isHeightmap) 0
1711        }
1712        default {
1713            error "unknown mode settings \"$itk_option(-mode)\""
1714        }
1715    }
1716    AdjustSetting isHeightmap
1717}
1718
1719# ----------------------------------------------------------------------
1720# CONFIGURATION OPTION: -plotbackground
1721# ----------------------------------------------------------------------
1722itcl::configbody Rappture::VtkHeightmapViewer::plotbackground {
1723    if { [isconnected] } {
1724        set rgb [Color2RGB $itk_option(-plotbackground)]
1725        SendCmd "screen bgcolor $rgb"
1726        $itk_component(view) configure -background $itk_option(-plotbackground)
1727    }
1728}
1729
1730# ----------------------------------------------------------------------
1731# CONFIGURATION OPTION: -plotforeground
1732# ----------------------------------------------------------------------
1733itcl::configbody Rappture::VtkHeightmapViewer::plotforeground {
1734    if { [isconnected] } {
1735        set rgb [Color2RGB $itk_option(-plotforeground)]
1736        SendCmd "dataset color $rgb"
1737        SendCmd "axis color all $rgb"
1738    }
1739}
1740
1741itcl::body Rappture::VtkHeightmapViewer::limits { dataobj } {
1742    lappend limits x [$dataobj limits x]
1743    lappend limits y [$dataobj limits y]
1744    lappend limits v [$dataobj limits v]
1745    return $limits
1746}
1747
1748itcl::body Rappture::VtkHeightmapViewer::BuildContourTab {} {
1749
1750    set fg [option get $itk_component(hull) font Font]
1751    #set bfg [option get $itk_component(hull) boldFont Font]
1752
1753    set inner [$itk_component(main) insert end \
1754        -title "Contour Settings" \
1755        -icon [Rappture::icon volume-on]]
1756    $inner configure -borderwidth 4
1757
1758    checkbutton $inner.legend \
1759        -text "Legend" \
1760        -variable [itcl::scope _settings(legendVisible)] \
1761        -command [itcl::code $this AdjustSetting legendVisible] \
1762        -font "Arial 9"
1763
1764    checkbutton $inner.wireframe \
1765        -text "Wireframe" \
1766        -variable [itcl::scope _settings(wireframe)] \
1767        -command [itcl::code $this AdjustSetting wireframe] \
1768        -font "Arial 9"
1769
1770    itk_component add lighting {
1771        checkbutton $inner.lighting \
1772            -text "Enable Lighting" \
1773            -variable [itcl::scope _settings(lighting)] \
1774            -command [itcl::code $this AdjustSetting lighting] \
1775            -font "Arial 9"
1776    } {
1777        ignore -font
1778    }
1779
1780    checkbutton $inner.edges \
1781        -text "Edges" \
1782        -variable [itcl::scope _settings(edges)] \
1783        -command [itcl::code $this AdjustSetting edges] \
1784        -font "Arial 9"
1785
1786    checkbutton $inner.outline \
1787        -text "Outline" \
1788        -variable [itcl::scope _settings(outline)] \
1789        -command [itcl::code $this AdjustSetting outline] \
1790        -font "Arial 9"
1791
1792    checkbutton $inner.stretch \
1793        -text "Stretch to fit" \
1794        -variable [itcl::scope _settings(stretchToFit)] \
1795        -command [itcl::code $this AdjustSetting stretchToFit] \
1796        -font "Arial 9"
1797
1798    label $inner.field_l -text "Field" -font "Arial 9"
1799    itk_component add field {
1800        Rappture::Combobox $inner.field -width 10 -editable no
1801    }
1802    bind $inner.field <<Value>> \
1803        [itcl::code $this AdjustSetting field]
1804
1805    label $inner.colormap_l -text "Colormap" -font "Arial 9"
1806    itk_component add colormap {
1807        Rappture::Combobox $inner.colormap -width 10 -editable no
1808    }
1809    $inner.colormap choices insert end \
1810        "BCGYR"              "BCGYR"            \
1811        "BGYOR"              "BGYOR"            \
1812        "blue"               "blue"             \
1813        "blue-to-brown"      "blue-to-brown"    \
1814        "blue-to-orange"     "blue-to-orange"   \
1815        "blue-to-grey"       "blue-to-grey"     \
1816        "green-to-magenta"   "green-to-magenta" \
1817        "greyscale"          "greyscale"        \
1818        "nanohub"            "nanohub"          \
1819        "rainbow"            "rainbow"          \
1820        "spectral"           "spectral"         \
1821        "ROYGB"              "ROYGB"            \
1822        "RYGCB"              "RYGCB"            \
1823        "brown-to-blue"      "brown-to-blue"    \
1824        "grey-to-blue"       "grey-to-blue"     \
1825        "orange-to-blue"     "orange-to-blue"   \
1826        "none"               "none"
1827
1828    $itk_component(colormap) value "BCGYR"
1829    bind $inner.colormap <<Value>> \
1830        [itcl::code $this AdjustSetting colormap]
1831
1832    label $inner.isolinecolor_l -text "Isolines" -font "Arial 9"
1833    itk_component add isolinecolor {
1834        Rappture::Combobox $inner.isolinecolor -width 10 -editable no
1835    }
1836    $inner.isolinecolor choices insert end \
1837        "black"              "black"            \
1838        "blue"               "blue"             \
1839        "cyan"               "cyan"             \
1840        "green"              "green"            \
1841        "grey"               "grey"             \
1842        "magenta"            "magenta"          \
1843        "orange"             "orange"           \
1844        "red"                "red"              \
1845        "white"              "white"            \
1846        "none"               "none"
1847
1848    $itk_component(isolinecolor) value "black"
1849    bind $inner.isolinecolor <<Value>> \
1850        [itcl::code $this AdjustSetting isolineColor]
1851
1852    label $inner.background_l -text "Background" -font "Arial 9"
1853    itk_component add background {
1854        Rappture::Combobox $inner.background -width 10 -editable no
1855    }
1856    $inner.background choices insert end \
1857        "black"              "black"            \
1858        "white"              "white"            \
1859        "grey"               "grey"             
1860
1861    $itk_component(background) value "white"
1862    bind $inner.background <<Value>> [itcl::code $this AdjustSetting background]
1863
1864    label $inner.opacity_l -text "Opacity" -font "Arial 9"
1865    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1866        -variable [itcl::scope _settings(heightmapOpacity)] \
1867        -width 10 \
1868        -showvalue off \
1869        -command [itcl::code $this AdjustSetting heightmapOpacity]
1870
1871    label $inner.scale_l -text "Scale" -font "Arial 9"
1872    ::scale $inner.scale -from 0 -to 100 -orient horizontal \
1873        -variable [itcl::scope _settings(heightmapScale)] \
1874        -width 10 \
1875        -showvalue off \
1876        -command [itcl::code $this AdjustSetting heightmapScale]
1877
1878    blt::table $inner \
1879        0,0 $inner.colormap_l -anchor w -pady 2  \
1880        0,1 $inner.colormap   -anchor w -pady 2 -fill x  \
1881        1,0 $inner.isolinecolor_l  -anchor w -pady 2  \
1882        1,1 $inner.isolinecolor    -anchor w -pady 2 -fill x  \
1883        2,0 $inner.background_l -anchor w -pady 2 \
1884        2,1 $inner.background -anchor w -pady 2  -fill x \
1885        4,0 $inner.legend     -anchor w -pady 2 -cspan 2 \
1886        5,0 $inner.wireframe  -anchor w -pady 2 -cspan 2\
1887        6,0 $inner.lighting   -anchor w -pady 2 -cspan 2 \
1888        7,0 $inner.edges      -anchor w -pady 2 -cspan 2 \
1889        8,0 $inner.legend     -anchor w -pady 2 -cspan 2 \
1890        9,0 $inner.stretch    -anchor w -pady 2 -cspan 2 \
1891        10,0 $inner.outline    -anchor w -pady 2 -cspan 2 \
1892        11,0 $inner.opacity_l -anchor w -pady 2 \
1893        11,1 $inner.opacity   -fill x   -pady 2 \
1894        12,0 $inner.scale_l   -anchor w -pady 2 -cspan 2 \
1895        12,1 $inner.scale     -fill x   -pady 2 -cspan 2 \
1896
1897    if { [array size _fields] > 1 } {
1898        blt::table $inner \
1899            3,0 $inner.field_l   -anchor w -pady 2 \
1900            3,1 $inner.field     -anchor w -pady 2 -fill x
1901    }
1902    blt::table configure $inner r* c* -resize none
1903    blt::table configure $inner r13 c1 -resize expand
1904}
1905
1906itcl::body Rappture::VtkHeightmapViewer::BuildAxisTab {} {
1907
1908    set fg [option get $itk_component(hull) font Font]
1909    #set bfg [option get $itk_component(hull) boldFont Font]
1910
1911    set inner [$itk_component(main) insert end \
1912        -title "Axis Settings" \
1913        -icon [Rappture::icon axis1]]
1914    $inner configure -borderwidth 4
1915
1916    checkbutton $inner.visible \
1917        -text "Axes" \
1918        -variable [itcl::scope _settings(axisVisible)] \
1919        -command [itcl::code $this AdjustSetting axisVisible] \
1920        -font "Arial 9"
1921    checkbutton $inner.labels \
1922        -text "Axis Labels" \
1923        -variable [itcl::scope _settings(axisLabels)] \
1924        -command [itcl::code $this AdjustSetting axisLabels] \
1925        -font "Arial 9"
1926    label $inner.grid_l -text "Grid" -font "Arial 9"
1927    checkbutton $inner.xgrid \
1928        -text "X" \
1929        -variable [itcl::scope _settings(axisXGrid)] \
1930        -command [itcl::code $this AdjustSetting axisXGrid] \
1931        -font "Arial 9"
1932    checkbutton $inner.ygrid \
1933        -text "Y" \
1934        -variable [itcl::scope _settings(axisYGrid)] \
1935        -command [itcl::code $this AdjustSetting axisYGrid] \
1936        -font "Arial 9"
1937    checkbutton $inner.zgrid \
1938        -text "Z" \
1939        -variable [itcl::scope _settings(axisZGrid)] \
1940        -command [itcl::code $this AdjustSetting axisZGrid] \
1941        -font "Arial 9"
1942    checkbutton $inner.minorticks \
1943        -text "Minor Ticks" \
1944        -variable [itcl::scope _settings(axisMinorTicks)] \
1945        -command [itcl::code $this AdjustSetting axisMinorTicks] \
1946        -font "Arial 9"
1947
1948
1949    label $inner.mode_l -text "Mode" -font "Arial 9"
1950
1951    itk_component add axisflymode {
1952        Rappture::Combobox $inner.mode -width 10 -editable no
1953    }
1954    $inner.mode choices insert end \
1955        "static_triad"    "static" \
1956        "closest_triad"   "closest" \
1957        "furthest_triad"  "furthest" \
1958        "outer_edges"     "outer"         
1959    $itk_component(axisflymode) value "static"
1960    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting axisFlymode]
1961
1962    blt::table $inner \
1963        0,0 $inner.visible -anchor w -cspan 4 \
1964        1,0 $inner.labels  -anchor w -cspan 4 \
1965        2,0 $inner.minorticks  -anchor w -cspan 4 \
1966        4,0 $inner.grid_l  -anchor w \
1967        4,1 $inner.xgrid   -anchor w \
1968        4,2 $inner.ygrid   -anchor w \
1969        4,3 $inner.zgrid   -anchor w \
1970        5,0 $inner.mode_l  -anchor w -padx { 2 0 } \
1971        5,1 $inner.mode    -fill x -cspan 3
1972
1973    blt::table configure $inner r* c* -resize none
1974    blt::table configure $inner r7 c6 -resize expand
1975    blt::table configure $inner r3 -height 0.125i
1976}
1977
1978
1979itcl::body Rappture::VtkHeightmapViewer::BuildCameraTab {} {
1980    set inner [$itk_component(main) insert end \
1981        -title "Camera Settings" \
1982        -icon [Rappture::icon camera]]
1983    $inner configure -borderwidth 4
1984
1985    set labels { qx qy qz qw xpan ypan zoom }
1986    set row 0
1987    foreach tag $labels {
1988        label $inner.${tag}label -text $tag -font "Arial 9"
1989        entry $inner.${tag} -font "Arial 9"  -bg white \
1990            -textvariable [itcl::scope _view($tag)]
1991        bind $inner.${tag} <KeyPress-Return> \
1992            [itcl::code $this camera set ${tag}]
1993        blt::table $inner \
1994            $row,0 $inner.${tag}label -anchor e -pady 2 \
1995            $row,1 $inner.${tag} -anchor w -pady 2
1996        blt::table configure $inner r$row -resize none
1997        incr row
1998    }
1999    checkbutton $inner.ortho \
2000        -text "Orthographic Projection" \
2001        -variable [itcl::scope _view(ortho)] \
2002        -command [itcl::code $this camera set ortho] \
2003        -font "Arial 9"
2004    blt::table $inner \
2005            $row,0 $inner.ortho -columnspan 2 -anchor w -pady 2
2006    blt::table configure $inner r$row -resize none
2007    incr row
2008
2009    blt::table configure $inner c0 c1 -resize none
2010    blt::table configure $inner c2 -resize expand
2011    blt::table configure $inner r$row -resize expand
2012}
2013
2014#
2015#  camera --
2016#
2017itcl::body Rappture::VtkHeightmapViewer::camera {option args} {
2018    switch -- $option {
2019        "show" {
2020            puts [array get _view]
2021        }
2022        "set" {
2023            set who [lindex $args 0]
2024            set x $_view($who)
2025            set code [catch { string is double $x } result]
2026            if { $code != 0 || !$result } {
2027                return
2028            }
2029            switch -- $who {
2030                "ortho" {
2031                    if {$_view(ortho)} {
2032                        SendCmd "camera mode ortho"
2033                    } else {
2034                        SendCmd "camera mode persp"
2035                    }
2036                }
2037                "xpan" - "ypan" {
2038                    PanCamera
2039                }
2040                "qx" - "qy" - "qz" - "qw" {
2041                    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
2042                    $_arcball quaternion $q
2043                    EventuallyRotate $q
2044                }
2045                "zoom" {
2046                    SendCmd "camera zoom $_view(zoom)"
2047                }
2048            }
2049        }
2050    }
2051}
2052
2053itcl::body Rappture::VtkHeightmapViewer::GetVtkData { args } {
2054    set bytes ""
2055    foreach dataobj [get] {
2056        foreach comp [$dataobj components] {
2057            set tag $dataobj-$comp
2058            set contents [ConvertToVtkData $dataobj $comp]
2059            #set contents [$dataobj vtkdata $comp]
2060            append bytes "$contents\n\n"
2061        }
2062    }
2063    return [list .vtk $bytes]
2064}
2065
2066itcl::body Rappture::VtkHeightmapViewer::GetImage { args } {
2067    if { [image width $_image(download)] > 0 &&
2068         [image height $_image(download)] > 0 } {
2069        set bytes [$_image(download) data -format "jpeg -quality 100"]
2070        set bytes [Rappture::encoding::decode -as b64 $bytes]
2071        return [list .jpg $bytes]
2072    }
2073    return ""
2074}
2075
2076itcl::body Rappture::VtkHeightmapViewer::BuildDownloadPopup { popup command } {
2077    Rappture::Balloon $popup \
2078        -title "[Rappture::filexfer::label downloadWord] as..."
2079    set inner [$popup component inner]
2080    label $inner.summary -text "" -anchor w
2081    radiobutton $inner.vtk_button -text "VTK data file" \
2082        -variable [itcl::scope _downloadPopup(format)] \
2083        -font "Arial 9 " \
2084        -value vtk 
2085    Rappture::Tooltip::for $inner.vtk_button "Save as VTK data file."
2086    radiobutton $inner.image_button -text "Image File" \
2087        -variable [itcl::scope _downloadPopup(format)] \
2088        -font "Arial 9 " \
2089        -value image
2090    Rappture::Tooltip::for $inner.image_button \
2091        "Save as digital image."
2092
2093    button $inner.ok -text "Save" \
2094        -highlightthickness 0 -pady 2 -padx 3 \
2095        -command $command \
2096        -compound left \
2097        -image [Rappture::icon download]
2098
2099    button $inner.cancel -text "Cancel" \
2100        -highlightthickness 0 -pady 2 -padx 3 \
2101        -command [list $popup deactivate] \
2102        -compound left \
2103        -image [Rappture::icon cancel]
2104
2105    blt::table $inner \
2106        0,0 $inner.summary -cspan 2  \
2107        1,0 $inner.vtk_button -anchor w -cspan 2 -padx { 4 0 } \
2108        2,0 $inner.image_button -anchor w -cspan 2 -padx { 4 0 } \
2109        4,1 $inner.cancel -width .9i -fill y \
2110        4,0 $inner.ok -padx 2 -width .9i -fill y
2111    blt::table configure $inner r3 -height 4
2112    blt::table configure $inner r4 -pady 4
2113    raise $inner.image_button
2114    $inner.vtk_button invoke
2115    return $inner
2116}
2117
2118itcl::body Rappture::VtkHeightmapViewer::SetObjectStyle { dataobj comp } {
2119    # Parse style string.
2120    set tag $dataobj-$comp
2121    array set style {
2122        -color BCGYR
2123        -edges 0
2124        -edgecolor black
2125        -lighting 1
2126        -linewidth 1.0
2127        -levels 10
2128        -visible 1
2129    }
2130    if { $_currentColormap == "" } {
2131        set stylelist [$dataobj style $comp]
2132        if { $stylelist != "" } {
2133            array set style $stylelist
2134            set stylelist [array get style]
2135            SetCurrentColormap $stylelist
2136        }
2137        $itk_component(colormap) value $style(-color)
2138    }
2139    set _numContours $style(-levels)
2140    set scale [GetHeightmapScale]
2141    SendCmd "heightmap add numcontours $_numContours $scale $tag"
2142    set _comp2scale($tag) $_settings(heightmapScale)
2143    SendCmd "heightmap edges $_settings(edges) $tag"
2144    SendCmd "heightmap wireframe $_settings(wireframe) $tag"
2145    SendCmd "heightmap colormap $_currentColormap $tag"
2146}
2147
2148itcl::body Rappture::VtkHeightmapViewer::IsValidObject { dataobj } {
2149    if {[catch {$dataobj isa Rappture::Field} valid] != 0 || !$valid} {
2150        return 0
2151    }
2152    return 1
2153}
2154
2155# ----------------------------------------------------------------------
2156# USAGE: ReceiveLegend <colormap> <title> <min> <max> <size>
2157#
2158# Invoked automatically whenever the "legend" command comes in from
2159# the rendering server.  Indicates that binary image data with the
2160# specified <size> will follow.
2161# ----------------------------------------------------------------------
2162itcl::body Rappture::VtkHeightmapViewer::ReceiveLegend { colormap title min max size } {
2163    #puts stderr "ReceiveLegend colormap=$colormap title=$title range=$min,$max size=$size"
2164    set _title $title
2165    regsub {\(mag\)} $title "" _title
2166    if { [isconnected] } {
2167        set bytes [ReceiveBytes $size]
2168        if { ![info exists _image(legend)] } {
2169            set _image(legend) [image create photo]
2170        }
2171        $_image(legend) configure -data $bytes
2172        #puts stderr "read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
2173        if { [catch {DrawLegend $_title} errs] != 0 } {
2174            global errorInfo
2175            puts stderr "errs=$errs errorInfo=$errorInfo"
2176        }
2177    }
2178}
2179
2180#
2181# DrawLegend --
2182#
2183#       Draws the legend in it's own canvas which resides to the right
2184#       of the contour plot area.
2185#
2186itcl::body Rappture::VtkHeightmapViewer::DrawLegend { name } {
2187    set c $itk_component(view)
2188    set w [winfo width $c]
2189    set h [winfo height $c]
2190    set font "Arial 8"
2191    set lineht [font metrics $font -linespace]
2192   
2193    if { $name == "component" } {
2194        set title ""
2195    } else {
2196        if { [info exists _fields($name)] } {
2197            foreach { title units } $_fields($name) break
2198            if { $units != "" } {
2199                set title [format "%s (%s)" $title $units]
2200            }
2201        } else {
2202            set title $name
2203        }
2204    }
2205    set x [expr $w - 2]
2206    if { !$_settings(legendVisible) } {
2207        $c delete legend
2208        return
2209    }
2210    if { [$c find withtag "legend"] == "" } {
2211        set y 2
2212        # If there's a legend title, create a text item for the title.
2213        if { $title != "" } {
2214            $c create text $x $y \
2215                -anchor ne \
2216                -fill $itk_option(-plotforeground) -tags "title legend" \
2217                -font $font
2218            incr y $lineht
2219        }
2220        $c create text $x $y \
2221            -anchor ne \
2222            -fill $itk_option(-plotforeground) -tags "vmax legend" \
2223            -font $font
2224        incr y $lineht
2225        $c create image $x $y \
2226            -anchor ne \
2227            -image $_image(legend) -tags "colormap legend"
2228        $c create text $x [expr {$h-2}] \
2229            -anchor se \
2230            -fill $itk_option(-plotforeground) -tags "vmin legend" \
2231            -font $font
2232        #$c bind colormap <Enter> [itcl::code $this EnterLegend %x %y]
2233        $c bind colormap <Leave> [itcl::code $this LeaveLegend]
2234        $c bind colormap <Motion> [itcl::code $this MotionLegend %x %y]
2235    }
2236    $c delete isoline
2237    set x2 $x
2238    set iw [image width $_image(legend)]
2239    set ih [image height $_image(legend)]
2240    set x1 [expr $x2 - ($iw*12)/10]
2241    set color [$itk_component(isolinecolor) value]
2242    # Draw the isolines on the legend.
2243    if { $color != "none"  && $_numContours > 0 } {
2244        set pixels [blt::vector create \#auto]
2245        set values [blt::vector create \#auto]
2246        set range [image height $_image(legend)]
2247        # Order of pixels is max to min (max is at top of legend).
2248        $pixels seq $ih 0 $_numContours
2249        set offset [expr 2 + $lineht]
2250        # If there's a legend title, increase the offset by the line height.
2251        if { $title != "" } {
2252            incr offset $lineht
2253        }
2254        $pixels expr {round($pixels + $offset)}
2255        # Order of values is min to max.
2256        foreach { vmin vmax } $_limits(v) break
2257        $values seq $vmin $vmax $_numContours
2258        set tags "isoline legend"
2259        foreach pos [$pixels range 0 end] value [$values range end 0] {
2260            set y1 [expr int($pos)]
2261            set id [$c create line $x1 $y1 $x2 $y1 -fill $color -tags $tags]
2262            $c bind $id <Enter> [itcl::code $this EnterIsoline %x %y $value]
2263            $c bind $id <Leave> [itcl::code $this LeaveIsoline]
2264        }
2265        blt::vector destroy $pixels $values
2266    }
2267
2268    $c bind title <ButtonPress> [itcl::code $this Combo post]
2269    $c bind title <Enter> [itcl::code $this Combo activate]
2270    $c bind title <Leave> [itcl::code $this Combo deactivate]
2271    # Reset the item coordinates according the current size of the plot.
2272    $c itemconfigure title -text $title
2273    if { [info exists _limits(v)] } {
2274        foreach { vmin vmax } $_limits(v) break
2275        $c itemconfigure vmin -text [format %g $vmin]
2276        $c itemconfigure vmax -text [format %g $vmax]
2277    }
2278    set y 2
2279    # If there's a legend title, move the title to the correct position
2280    if { $title != "" } {
2281        $c coords title $x $y
2282        incr y $lineht
2283    }
2284    $c coords vmax $x $y
2285    incr y $lineht
2286    $c coords colormap $x $y
2287    $c coords vmin $x [expr {$h - 2}]
2288}
2289
2290#
2291# EnterIsoline --
2292#
2293itcl::body Rappture::VtkHeightmapViewer::EnterIsoline { x y value } {
2294    SetIsolineTip $x $y $value
2295}
2296
2297#
2298# LeaveIsoline --
2299#
2300itcl::body Rappture::VtkHeightmapViewer::LeaveIsoline { } {
2301    Rappture::Tooltip::tooltip cancel
2302    .rappturetooltip configure -icon ""
2303}
2304
2305#
2306# SetIsolineTip --
2307#
2308itcl::body Rappture::VtkHeightmapViewer::SetIsolineTip { x y value } {
2309    set c $itk_component(view)
2310    set w [winfo width $c]
2311    set h [winfo height $c]
2312    set font "Arial 8"
2313    set lineht [font metrics $font -linespace]
2314   
2315    if { [info exists _fields($_title)] } {
2316        foreach { title units } $_fields($_title) break
2317        if { $units != "" } {
2318            set title [format "%s (%s)" $title $units]
2319        }
2320    } else {
2321        set title $_title
2322    }
2323    set imgHeight [image height $_image(legend)]
2324    set coords [$c coords colormap]
2325    set imgX [expr $w - [image width $_image(legend)] - 2]
2326    set imgY [expr $y - 2 * ($lineht + 2)]
2327
2328    .rappturetooltip configure -icon ""
2329
2330    # Compute the value of the point
2331    set tipx [expr $x + 15]
2332    set tipy [expr $y - 5]
2333    Rappture::Tooltip::text $c "Isoline $value"
2334    Rappture::Tooltip::tooltip show $c +$tipx,+$tipy   
2335}
2336
2337
2338#
2339# EnterLegend --
2340#
2341itcl::body Rappture::VtkHeightmapViewer::EnterLegend { x y } {
2342    SetLegendTip $x $y
2343}
2344
2345#
2346# MotionLegend --
2347#
2348itcl::body Rappture::VtkHeightmapViewer::MotionLegend { x y } {
2349    Rappture::Tooltip::tooltip cancel
2350    set c $itk_component(view)
2351    SetLegendTip $x $y
2352}
2353
2354#
2355# LeaveLegend --
2356#
2357itcl::body Rappture::VtkHeightmapViewer::LeaveLegend { } {
2358    Rappture::Tooltip::tooltip cancel
2359    .rappturetooltip configure -icon ""
2360}
2361
2362#
2363# SetLegendTip --
2364#
2365itcl::body Rappture::VtkHeightmapViewer::SetLegendTip { x y } {
2366    set c $itk_component(view)
2367    set w [winfo width $c]
2368    set h [winfo height $c]
2369    set font "Arial 8"
2370    set lineht [font metrics $font -linespace]
2371   
2372    set imgHeight [image height $_image(legend)]
2373    set coords [$c coords colormap]
2374    set imgX [expr $w - [image width $_image(legend)] - 2]
2375    set imgY [expr $y - 2 * ($lineht + 2)]
2376
2377    if { [info exists _fields($_title)] } {
2378        foreach { title units } $_fields($_title) break
2379        if { $units != "" } {
2380            set title [format "%s (%s)" $title $units]
2381        }
2382    } else {
2383        set title $_title
2384    }
2385    # Make a swatch of the selected color
2386    if { [catch { $_image(legend) get 10 $imgY } pixel] != 0 } {
2387        #puts stderr "out of range: $imgY"
2388        return
2389    }
2390    if { ![info exists _image(swatch)] } {
2391        set _image(swatch) [image create photo -width 24 -height 24]
2392    }
2393    set color [eval format "\#%02x%02x%02x" $pixel]
2394    $_image(swatch) put black  -to 0 0 23 23
2395    $_image(swatch) put $color -to 1 1 22 22
2396    .rappturetooltip configure -icon $_image(swatch)
2397
2398    # Compute the value of the point
2399    if { [info exists _limits(v)] } {
2400        foreach { vmin vmax } $_limits(v) break
2401        set t [expr 1.0 - (double($imgY) / double($imgHeight-1))]
2402        set value [expr $t * ($vmax - $vmin) + $vmin]
2403    } else {
2404        set value 0.0
2405    }
2406    set tipx [expr $x + 15]
2407    set tipy [expr $y - 5]
2408    Rappture::Tooltip::text $c "$title $value"
2409    Rappture::Tooltip::tooltip show $c +$tipx,+$tipy   
2410}
2411
2412# ----------------------------------------------------------------------
2413# USAGE: _dropdown post
2414# USAGE: _dropdown unpost
2415# USAGE: _dropdown select
2416#
2417# Used internally to handle the dropdown list for this combobox.  The
2418# post/unpost options are invoked when the list is posted or unposted
2419# to manage the relief of the controlling button.  The select option
2420# is invoked whenever there is a selection from the list, to assign
2421# the value back to the gauge.
2422# ----------------------------------------------------------------------
2423itcl::body Rappture::VtkHeightmapViewer::Combo {option} {
2424    set c $itk_component(view)
2425    switch -- $option {
2426        post {
2427            foreach { x1 y1 x2 y2 } [$c bbox title] break
2428            set x1 [expr [winfo width $itk_component(view)] - [winfo reqwidth $itk_component(fieldmenu)]]
2429            set x [expr $x1 + [winfo rootx $itk_component(view)]]
2430            set y [expr $y2 + [winfo rooty $itk_component(view)]]
2431            tk_popup $itk_component(fieldmenu) $x $y
2432        }
2433        activate {
2434            $c itemconfigure title -fill red
2435        }
2436        deactivate {
2437            $c itemconfigure title -fill $itk_option(-plotforeground)
2438        }
2439        invoke {
2440            $itk_component(field) value $_curFldName
2441            AdjustSetting field
2442        }
2443        default {
2444            error "bad option \"$option\": should be post, unpost, select"
2445        }
2446    }
2447}
2448
2449itcl::body Rappture::VtkHeightmapViewer::GetHeightmapScale {} {
2450    if {  $_settings(isHeightmap) } {
2451        set val $_settings(heightmapScale)
2452        set sval [expr { $val >= 50 ? double($val)/50.0 : 1.0/(2.0-(double($val)/50.0)) }]
2453        return $sval
2454    }
2455    set sval 0
2456}
2457
2458itcl::body Rappture::VtkHeightmapViewer::ResetColormap { color } {
2459    array set style {
2460        -color BCGYR
2461        -levels 10
2462        -opacity 1.0
2463    }
2464    if { [info exists _colormap($_currentColormap)] } {
2465        array set style $_colormap($_currentColormap)
2466    }
2467    set style(-color) $color
2468    SetCurrentColormap [array get style]
2469}
2470
Note: See TracBrowser for help on using the repository browser.