source: trunk/gui/scripts/vtksurfaceviewer.tcl @ 4669

Last change on this file since 4669 was 4669, checked in by ldelgass, 10 years ago

Add build info to clientinfo command

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