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

Last change on this file since 3394 was 3394, checked in by gah, 10 years ago

fix up stats reporting in servers

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