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

Last change on this file since 3592 was 3592, checked in by ldelgass, 12 years ago

Report clientinfo first thing after connecting to visualization server.

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