source: branches/1.4/gui/scripts/vtkheightmapviewer.tcl @ 5183

Last change on this file since 5183 was 5183, checked in by ldelgass, 9 years ago

s/wmap/amap/

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