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

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

add check to automatically set -stretchtofit when x and y axis scales differ greatly

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