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

Last change on this file since 3813 was 3813, checked in by ldelgass, 11 years ago

Fix bug in 'add' method of viewer widgets: list search for existing dataobj
entry was wrong (list and pattern transposed), causing potential duplicate
entries in dataobj list.

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