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

Last change on this file since 3447 was 3447, checked in by ldelgass, 12 years ago

Fix outline with sequence of contours

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