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

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

Need to set camera mode _before_ resetting camera to properly initialize
image camera mode in heightmap viewer.

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