source: branches/1.2/gui/scripts/vtkheightmapviewer.tcl @ 3652

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