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

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

add number of isolines control

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