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

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

Fix reporting of tool info to render servers

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 parameters {title args} {
60        # do nothing
61    }
62    public method scale {args}
63
64    protected method Connect {}
65    protected method CurrentDatasets {args}
66    protected method Disconnect {}
67    protected method DoResize {}
68    protected method DoRotate {}
69    protected method AdjustSetting {what {value ""}}
70    protected method InitSettings { args  }
71    protected method Pan {option x y}
72    protected method Pick {x y}
73    protected method Rebuild {}
74    protected method ReceiveDataset { args }
75    protected method ReceiveImage { args }
76    protected method ReceiveLegend { colormap title vmin vmax size }
77    protected method Rotate {option x y}
78    protected method Zoom {option}
79
80    # The following methods are only used by this class.
81    private method BuildAxisTab {}
82    private method BuildCameraTab {}
83    private method BuildColormap { name }
84    private method BuildDownloadPopup { widget command }
85    private method BuildSurfaceTab {}
86    private method Combo { option }
87    private method DrawLegend {}
88    private method EnterLegend { x y }
89    private method EventuallyResize { w h }
90    private method EventuallyRotate { q }
91    private method EventuallyRequestLegend {}
92    private method GetImage { args }
93    private method GetVtkData { args }
94    private method IsValidObject { dataobj }
95    private method LeaveLegend {}
96    private method MotionLegend { x y }
97    private method PanCamera {}
98    private method RequestLegend {}
99    private method SetLegendTip { x y }
100    private method SetObjectStyle { dataobj comp }
101    private method SetCurrentColormap { color }
102    private method SetOrientation { side }
103    private method UpdateContourList {}
104
105    private variable _arcball ""
106
107    private variable _dlist ""     ;    # list of data objects
108    private variable _obj2datasets
109    private variable _obj2ovride   ;    # maps dataobj => style override
110    private variable _datasets     ;    # contains all the dataobj-component
111                                   ;    # datasets in the server
112    private variable _colormaps    ;    # contains all the colormaps
113                                   ;    # in the server.
114    # The name of the current colormap used.  The colormap is global to all
115    # heightmaps displayed.
116    private variable _currentColormap ""
117    private variable _currentNumContours -1
118
119    private variable _dataset2style    ;# maps dataobj-component to transfunc
120
121    private variable _click        ;    # info used for rotate operations
122    private variable _limits       ;    # autoscale min/max for all axes
123    private variable _view         ;    # view params for 3D view
124    private variable _settings
125    private variable _style;            # Array of current component styles.
126    private variable _changed
127    private variable _initialStyle;     # Array of initial component styles.
128    private variable _reset 1;          # indicates if camera needs to be reset
129                                        # to starting position.
130
131    private variable _first ""     ;    # This is the topmost dataset.
132    private variable _start 0
133    private variable _title ""
134    private variable _isolines
135    private variable _contourList ""
136
137    common _downloadPopup;              # download options from popup
138    private common _hardcopy
139    private variable _width 0
140    private variable _height 0
141    private variable _resizePending 0
142    private variable _rotatePending 0
143    private variable _legendPending 0
144    private variable _field      ""
145    private variable _colorMode "scalar";       #  Mode of colormap (vmag or scalar)
146    private variable _fieldNames {}
147    private variable _fields
148    private variable _curFldName ""
149    private variable _curFldLabel ""
150}
151
152itk::usual VtkSurfaceViewer {
153    keep -background -foreground -cursor -font
154    keep -plotbackground -plotforeground
155}
156
157# ----------------------------------------------------------------------
158# CONSTRUCTOR
159# ----------------------------------------------------------------------
160itcl::body Rappture::VtkSurfaceViewer::constructor {hostlist args} {
161    package require vtk
162    set _serverType "vtkvis"
163
164    # Rebuild event
165    $_dispatcher register !rebuild
166    $_dispatcher dispatch $this !rebuild "[itcl::code $this Rebuild]; list"
167
168    # Resize event
169    $_dispatcher register !resize
170    $_dispatcher dispatch $this !resize "[itcl::code $this DoResize]; list"
171
172    # Rotate event
173    $_dispatcher register !rotate
174    $_dispatcher dispatch $this !rotate "[itcl::code $this DoRotate]; list"
175
176    # Legend event
177    $_dispatcher register !legend
178    $_dispatcher dispatch $this !legend "[itcl::code $this RequestLegend]; list"
179
180    #
181    # Populate parser with commands handle incoming requests
182    #
183    $_parser alias image [itcl::code $this ReceiveImage]
184    $_parser alias dataset [itcl::code $this ReceiveDataset]
185    $_parser alias legend [itcl::code $this ReceiveLegend]
186
187    # Initialize the view to some default parameters.
188    array set _view {
189        qw              0.853553
190        qx              -0.353553
191        qy              0.353553
192        qz              0.146447
193        zoom            1.0
194        xpan            0
195        ypan            0
196        ortho           0
197    }
198    set _arcball [blt::arcball create 100 100]
199    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
200    $_arcball quaternion $q
201
202    array set _settings {
203        -axesvisible                1
204        -axislabels                 1
205        -axisminorticks             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        -xgrid                      0
221        -ygrid                      0
222        -zgrid                      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 -axislabels -axisminorticks
912        #SendCmd "axis lformat all %g"
913        StopBufferingCommands
914        SendCmd "imgflush"
915        StartBufferingCommands
916    }
917    set _first ""
918    SendCmd "dataset visible 0"
919    foreach dataobj [get -objects] {
920        if { [info exists _obj2ovride($dataobj-raise)] &&  $_first == "" } {
921            set _first $dataobj
922        }
923        set _obj2datasets($dataobj) ""
924        foreach comp [$dataobj components] {
925            set tag $dataobj-$comp
926            if { ![info exists _datasets($tag)] } {
927                set bytes [$dataobj vtkdata $comp]
928                if 0 {
929                    set f [open "/tmp/surface.vtk" "w"]
930                    puts $f $bytes
931                    close $f
932                }
933                set length [string length $bytes]
934                if { $_reportClientInfo }  {
935                    set info {}
936                    lappend info "tool_id"       [$dataobj hints toolid]
937                    lappend info "tool_name"     [$dataobj hints toolname]
938                    lappend info "tool_title"    [$dataobj hints tooltitle]
939                    lappend info "tool_command"  [$dataobj hints toolcommand]
940                    lappend info "tool_revision" [$dataobj hints toolrevision]
941                    lappend info "dataset_label" [$dataobj hints label]
942                    lappend info "dataset_size"  $length
943                    lappend info "dataset_tag"   $tag
944                    SendCmd "clientinfo [list $info]"
945                }
946                append _outbuf "dataset add $tag data follows $length\n"
947                append _outbuf $bytes
948                set _datasets($tag) 1
949                SetObjectStyle $dataobj $comp
950            }
951            lappend _obj2datasets($dataobj) $tag
952            if { [info exists _obj2ovride($dataobj-raise)] } {
953                # Setting dataset visible enables outline
954                # and contour2d
955                SendCmd "dataset visible 1 $tag"
956            }
957        }
958    }
959
960    if { $_first != "" } {
961        $itk_component(field) choices delete 0 end
962        $itk_component(fieldmenu) delete 0 end
963        array unset _fields
964        set _curFldName ""
965        foreach cname [$_first components] {
966            foreach fname [$_first fieldnames $cname] {
967                if { [info exists _fields($fname)] } {
968                    continue
969                }
970                foreach { label units components } \
971                    [$_first fieldinfo $fname] break
972                $itk_component(field) choices insert end "$fname" "$label"
973                $itk_component(fieldmenu) add radiobutton -label "$label" \
974                    -value $label -variable [itcl::scope _curFldLabel] \
975                    -selectcolor red \
976                    -activebackground $itk_option(-plotbackground) \
977                    -activeforeground $itk_option(-plotforeground) \
978                    -font "Arial 8" \
979                    -command [itcl::code $this Combo invoke]
980                set _fields($fname) [list $label $units $components]
981                if { $_curFldName == "" } {
982                    set _curFldName $fname
983                    set _curFldLabel $label
984                }
985            }
986        }
987        $itk_component(field) value $_curFldLabel
988    }
989    InitSettings -isolinesvisible -surfacevisible -outline
990    if { $_reset } {
991        # These are settings that rely on a dataset being loaded.
992        InitSettings \
993            -surfacelighting \
994            -field \
995            -surfaceedges -surfacelighting -surfaceopacity \
996            -surfacewireframe \
997            -numcontours
998
999        Zoom reset
1000        foreach axis { x y z } {
1001            # Another problem fixed by a <view>. We looking into a data
1002            # object for the name of the axes. This should be global to
1003            # the viewer itself.
1004            set label [$_first hints ${axis}label]
1005            if { $label == "" } {
1006                set label [string toupper $axis]
1007            }
1008            # May be a space in the axis label.
1009            SendCmd [list axis name $axis $label]
1010        }
1011        if { [array size _fields] < 2 } {
1012            catch {blt::table forget $itk_component(field) $itk_component(field_l)}
1013        }
1014        set _reset 0
1015    }
1016
1017    # Actually write the commands to the server socket.  If it fails, we don't
1018    # care.  We're finished here.
1019    blt::busy hold $itk_component(hull)
1020    StopBufferingCommands;              # Turn off buffering and send commands.
1021    blt::busy release $itk_component(hull)
1022}
1023
1024# ----------------------------------------------------------------------
1025# USAGE: CurrentDatasets ?-all -visible? ?dataobjs?
1026#
1027# Returns a list of server IDs for the current datasets being displayed.  This
1028# is normally a single ID, but it might be a list of IDs if the current data
1029# object has multiple components.
1030# ----------------------------------------------------------------------
1031itcl::body Rappture::VtkSurfaceViewer::CurrentDatasets {args} {
1032    set flag [lindex $args 0]
1033    switch -- $flag {
1034        "-all" {
1035            if { [llength $args] > 1 } {
1036                error "CurrentDatasets: can't specify dataobj after \"-all\""
1037            }
1038            set dlist [get -objects]
1039        }
1040        "-visible" {
1041            if { [llength $args] > 1 } {
1042                set dlist {}
1043                set args [lrange $args 1 end]
1044                foreach dataobj $args {
1045                    if { [info exists _obj2ovride($dataobj-raise)] } {
1046                        lappend dlist $dataobj
1047                    }
1048                }
1049            } else {
1050                set dlist [get -visible]
1051            }
1052        }           
1053        default {
1054            set dlist $args
1055        }
1056    }
1057    set rlist ""
1058    foreach dataobj $dlist {
1059        foreach comp [$dataobj components] {
1060            set tag $dataobj-$comp
1061            if { [info exists _datasets($tag)] && $_datasets($tag) } {
1062                lappend rlist $tag
1063            }
1064        }
1065    }
1066    return $rlist
1067}
1068
1069# ----------------------------------------------------------------------
1070# USAGE: Zoom in
1071# USAGE: Zoom out
1072# USAGE: Zoom reset
1073#
1074# Called automatically when the user clicks on one of the zoom
1075# controls for this widget.  Changes the zoom for the current view.
1076# ----------------------------------------------------------------------
1077itcl::body Rappture::VtkSurfaceViewer::Zoom {option} {
1078    switch -- $option {
1079        "in" {
1080            set _view(zoom) [expr {$_view(zoom)*1.25}]
1081            SendCmd "camera zoom $_view(zoom)"
1082        }
1083        "out" {
1084            set _view(zoom) [expr {$_view(zoom)*0.8}]
1085            SendCmd "camera zoom $_view(zoom)"
1086        }
1087        "reset" {
1088            array set _view {
1089                qw     0.853553
1090                qx     -0.353553
1091                qy     0.353553
1092                qz     0.146447
1093                zoom   1.0
1094                xpan   0
1095                ypan   0
1096            }
1097            if { $_first != "" } {
1098                set location [$_first hints camera]
1099                if { $location != "" } {
1100                    array set _view $location
1101                }
1102            }
1103            set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1104            $_arcball quaternion $q
1105            DoRotate
1106            SendCmd "camera reset"
1107        }
1108    }
1109}
1110
1111itcl::body Rappture::VtkSurfaceViewer::PanCamera {} {
1112    set x $_view(xpan)
1113    set y $_view(ypan)
1114    SendCmd "camera pan $x $y"
1115}
1116
1117
1118# ----------------------------------------------------------------------
1119# USAGE: Rotate click <x> <y>
1120# USAGE: Rotate drag <x> <y>
1121# USAGE: Rotate release <x> <y>
1122#
1123# Called automatically when the user clicks/drags/releases in the
1124# plot area.  Moves the plot according to the user's actions.
1125# ----------------------------------------------------------------------
1126itcl::body Rappture::VtkSurfaceViewer::Rotate {option x y} {
1127    switch -- $option {
1128        "click" {
1129            $itk_component(view) configure -cursor fleur
1130            set _click(x) $x
1131            set _click(y) $y
1132        }
1133        "drag" {
1134            if {[array size _click] == 0} {
1135                Rotate click $x $y
1136            } else {
1137                set w [winfo width $itk_component(view)]
1138                set h [winfo height $itk_component(view)]
1139                if {$w <= 0 || $h <= 0} {
1140                    return
1141                }
1142
1143                if {[catch {
1144                    # this fails sometimes for no apparent reason
1145                    set dx [expr {double($x-$_click(x))/$w}]
1146                    set dy [expr {double($y-$_click(y))/$h}]
1147                }]} {
1148                    return
1149                }
1150                if { $dx == 0 && $dy == 0 } {
1151                    return
1152                }
1153                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1154                EventuallyRotate $q
1155                set _click(x) $x
1156                set _click(y) $y
1157            }
1158        }
1159        "release" {
1160            Rotate drag $x $y
1161            $itk_component(view) configure -cursor ""
1162            catch {unset _click}
1163        }
1164        default {
1165            error "bad option \"$option\": should be click, drag, release"
1166        }
1167    }
1168}
1169
1170itcl::body Rappture::VtkSurfaceViewer::Pick {x y} {
1171    foreach tag [CurrentDatasets -visible] {
1172        SendCmdNoSplash "dataset getscalar pixel $x $y $tag"
1173    }
1174}
1175
1176# ----------------------------------------------------------------------
1177# USAGE: $this Pan click x y
1178#        $this Pan drag x y
1179#        $this Pan release x y
1180#
1181# Called automatically when the user clicks on one of the zoom
1182# controls for this widget.  Changes the zoom for the current view.
1183# ----------------------------------------------------------------------
1184itcl::body Rappture::VtkSurfaceViewer::Pan {option x y} {
1185    switch -- $option {
1186        "set" {
1187            set w [winfo width $itk_component(view)]
1188            set h [winfo height $itk_component(view)]
1189            set x [expr $x / double($w)]
1190            set y [expr $y / double($h)]
1191            set _view(xpan) [expr $_view(xpan) + $x]
1192            set _view(ypan) [expr $_view(ypan) + $y]
1193            PanCamera
1194            return
1195        }
1196        "click" {
1197            set _click(x) $x
1198            set _click(y) $y
1199            $itk_component(view) configure -cursor hand1
1200        }
1201        "drag" {
1202            if { ![info exists _click(x)] } {
1203                set _click(x) $x
1204            }
1205            if { ![info exists _click(y)] } {
1206                set _click(y) $y
1207            }
1208            set w [winfo width $itk_component(view)]
1209            set h [winfo height $itk_component(view)]
1210            set dx [expr ($_click(x) - $x)/double($w)]
1211            set dy [expr ($_click(y) - $y)/double($h)]
1212            set _click(x) $x
1213            set _click(y) $y
1214            set _view(xpan) [expr $_view(xpan) - $dx]
1215            set _view(ypan) [expr $_view(ypan) - $dy]
1216            PanCamera
1217        }
1218        "release" {
1219            Pan drag $x $y
1220            $itk_component(view) configure -cursor ""
1221        }
1222        default {
1223            error "unknown option \"$option\": should set, click, drag, or release"
1224        }
1225    }
1226}
1227
1228# ----------------------------------------------------------------------
1229# USAGE: InitSettings <what> ?<value>?
1230#
1231# Used internally to update rendering settings whenever parameters
1232# change in the popup settings panel.  Sends the new settings off
1233# to the back end.
1234# ----------------------------------------------------------------------
1235itcl::body Rappture::VtkSurfaceViewer::InitSettings { args } {
1236    foreach spec $args {
1237        if { [info exists _settings($_first-$spec)] } {
1238            # Reset global setting with dataobj specific setting
1239            set _settings($spec) $_settings($_first-$spec)
1240        }
1241        AdjustSetting $spec
1242    }
1243}
1244
1245#
1246# AdjustSetting --
1247#
1248#       Changes/updates a specific setting in the widget.  There are
1249#       usually user-setable option.  Commands are sent to the render
1250#       server.
1251#
1252itcl::body Rappture::VtkSurfaceViewer::AdjustSetting {what {value ""}} {
1253    if { ![isconnected] } {
1254        return
1255    }
1256    switch -- $what {
1257        "-background" {
1258            set bgcolor [$itk_component(background) value]
1259            array set fgcolors {
1260                "black" "white"
1261                "white" "black"
1262                "grey"  "black"
1263            }
1264            configure -plotbackground $bgcolor \
1265                -plotforeground $fgcolors($bgcolor)
1266            $itk_component(view) delete "legend"
1267            DrawLegend
1268        }
1269        "-axesvisible" {
1270            set bool $_settings($what)
1271            SendCmd "axis visible all $bool"
1272        }
1273        "-axislabels" {
1274            set bool $_settings($what)
1275            SendCmd "axis labels all $bool"
1276        }
1277        "-axisminorticks" {
1278            set bool $_settings($what)
1279            SendCmd "axis minticks all $bool"
1280        }
1281        "-xaxisgrid" - "-yaxisgrid" - "-zaxisgrid" {
1282            set axis [string tolower [string range $what 1 1]]
1283            set bool $_settings($what)
1284            SendCmd "axis grid $axis $bool"
1285        }
1286        "-axismode" {
1287            set mode [$itk_component(axisMode) value]
1288            set mode [$itk_component(axisMode) translate $mode]
1289            set _settings($what) $mode
1290            SendCmd "axis flymode $mode"
1291        }
1292        "-colormap" {
1293            set _changed($what) 1
1294            StartBufferingCommands
1295            set color [$itk_component(colormap) value]
1296            set _settings($what) $color
1297            if { $color == "none" } {
1298                if { $_settings(-colormapvisible) } {
1299                    SendCmd "contour2d colormode constant {}"
1300                    SendCmd "polydata colormode constant {}"
1301                    set _settings(-colormapvisible) 0
1302                }
1303            } else {
1304                if { !$_settings(-colormapvisible) } {
1305                    #SendCmd "contour2d colormode $_colorMode $_curFldName"
1306                    SendCmd "polydata colormode $_colorMode $_curFldName"
1307                    set _settings(-colormapvisible) 1
1308                }
1309                SetCurrentColormap $color
1310                if {$_settings(-colormapdiscrete)} {
1311                    set numColors [expr $_settings(-numcontours) + 1]
1312                    SendCmd "colormap res $numColors $color"
1313                }
1314            }
1315            StopBufferingCommands
1316            EventuallyRequestLegend
1317        }
1318        "-colormapdiscrete" {
1319            set bool $_settings($what)
1320            set numColors [expr $_settings(-numcontours) + 1]
1321            StartBufferingCommands
1322            if {$bool} {
1323                SendCmd "colormap res $numColors"
1324                # Discrete colormap requires preinterp on
1325                SendCmd "polydata preinterp on"
1326            } else {
1327                SendCmd "colormap res default"
1328                # FIXME: add setting for preinterp (default on)
1329                SendCmd "polydata preinterp on"
1330            }
1331            StopBufferingCommands
1332            EventuallyRequestLegend
1333        }
1334        "-numcontours" {
1335            set _settings($what) [$itk_component(numcontours) value]
1336            set _currentNumContours $_settings($what)
1337            UpdateContourList
1338            set _changed($what) 1
1339            SendCmd "contour2d contourlist [list $_contourList]"
1340            if {$_settings(-colormapdiscrete)} {
1341                set numColors [expr $_settings($what) + 1]
1342                SendCmd "colormap res $numColors"
1343                EventuallyRequestLegend
1344            } else {
1345                DrawLegend
1346            }
1347        }
1348        "-surfacewireframe" {
1349            set bool $_settings($what)
1350            SendCmd "polydata wireframe $bool"
1351        }
1352        "-isolinesvisible" {
1353            set bool $_settings($what)
1354            SendCmd "contour2d visible $bool"
1355            DrawLegend
1356        }
1357        "-surfacevisible" {
1358            set bool $_settings($what)
1359            SendCmd "polydata visible $bool"
1360            if { $bool } {
1361                Rappture::Tooltip::for $itk_component(surface) \
1362                    "Hide the surface"
1363            } else {
1364                Rappture::Tooltip::for $itk_component(surface) \
1365                    "Show the surface"
1366            }
1367            DrawLegend
1368        }
1369        "-surfacelighting" {
1370            set bool $_settings($what)
1371            SendCmd "polydata lighting $bool"
1372        }
1373        "-surfaceedges" {
1374            set bool $_settings($what)
1375            SendCmd "polydata edges $bool"
1376        }
1377        "-outline" {
1378            set bool $_settings($what)
1379            SendCmd "outline visible $bool"
1380        }
1381        "-isolinecolor" {
1382            set color [$itk_component(isolineColor) value]
1383            set _settings($what) $color
1384            SendCmd "contour2d linecolor [Color2RGB $color]"
1385            DrawLegend
1386        }
1387        "-surfaceopacity" {
1388            set val $_settings($what)
1389            set sval [expr { 0.01 * double($val) }]
1390            SendCmd "polydata opacity $sval"
1391        }
1392        "-field" {
1393            set label [$itk_component(field) value]
1394            set fname [$itk_component(field) translate $label]
1395            set _settings($what) $fname
1396            if { [info exists _fields($fname)] } {
1397                foreach { label units components } $_fields($fname) break
1398                if { $components > 1 } {
1399                    set _colorMode vmag
1400                } else {
1401                    set _colorMode scalar
1402                }
1403                set _curFldName $fname
1404                set _curFldLabel $label
1405            } else {
1406                puts stderr "unknown field \"$fname\""
1407                return
1408            }
1409            SendCmd "dataset scalar $_curFldName"
1410            if { ![info exists _limits($_curFldName)] } {
1411                SendCmd "dataset maprange all"
1412            } else {
1413                SendCmd "dataset maprange explicit $_limits($_curFldName) $_curFldName"
1414            }
1415            #SendCmd "contour2d colormode $_colorMode $_curFldName"
1416            SendCmd "polydata colormode $_colorMode $_curFldName"
1417            SendCmd "camera reset"
1418            UpdateContourList
1419            DrawLegend
1420        }
1421        "-legendvisible" {
1422            if { !$_settings($what) } {
1423                $itk_component(view) delete legend
1424            }
1425            DrawLegend
1426        }
1427        default {
1428            error "don't know how to fix $what"
1429        }
1430    }
1431}
1432
1433
1434#
1435# RequestLegend --
1436#
1437#       Request a new legend from the server.  The size of the legend
1438#       is determined from the height of the canvas. 
1439#
1440# This should be called when
1441#       1.  A new current colormap is set.
1442#       2.  Window is resized.
1443#       3.  The limits of the data have changed.  (Just need a redraw).
1444#       4.  Number of isolines have changed. (Just need a redraw).
1445#       5.  Legend becomes visible (Just need a redraw).
1446#
1447itcl::body Rappture::VtkSurfaceViewer::RequestLegend {} {
1448    set _legendPending 0
1449    if { ![info exists _fields($_curFldName)] } {
1450        return
1451    }
1452    set fname $_curFldName
1453    set font "Arial 8"
1454    set lineht [font metrics $font -linespace]
1455    set w 12
1456    set h [expr {$_height - 2 * ($lineht + 2)}]
1457    if { $h < 1 } {
1458        return
1459    }
1460    if { [string match "component*" $fname] } {
1461        set title ""
1462    } else {
1463        if { [info exists _fields($fname)] } {
1464            foreach { title units } $_fields($fname) break
1465            if { $units != "" } {
1466                set title [format "%s (%s)" $title $units]
1467            }
1468        } else {
1469            set title $fname
1470        }
1471    }
1472    # If there's a title too, subtract one more line
1473    if { $title != "" } {
1474        incr h -$lineht
1475    }
1476    # Set the legend on the first heightmap dataset.
1477    if { $_currentColormap != ""  } {
1478        set cmap $_currentColormap
1479        SendCmdNoWait "legend $cmap scalar $_curFldName {} $w $h 0"
1480    }
1481}
1482
1483# ----------------------------------------------------------------------
1484# CONFIGURATION OPTION: -plotbackground
1485# ----------------------------------------------------------------------
1486itcl::configbody Rappture::VtkSurfaceViewer::plotbackground {
1487    if { [isconnected] } {
1488        set rgb [Color2RGB $itk_option(-plotbackground)]
1489        SendCmd "screen bgcolor $rgb"
1490    }
1491}
1492
1493# ----------------------------------------------------------------------
1494# CONFIGURATION OPTION: -plotforeground
1495# ----------------------------------------------------------------------
1496itcl::configbody Rappture::VtkSurfaceViewer::plotforeground {
1497    if { [isconnected] } {
1498        set rgb [Color2RGB $itk_option(-plotforeground)]
1499        SendCmd "axis color all $rgb"
1500        SendCmd "outline color $rgb"
1501    }
1502}
1503
1504itcl::body Rappture::VtkSurfaceViewer::BuildSurfaceTab {} {
1505
1506    set fg [option get $itk_component(hull) font Font]
1507    #set bfg [option get $itk_component(hull) boldFont Font]
1508
1509    set inner [$itk_component(main) insert end \
1510        -title "Surface Settings" \
1511        -icon [Rappture::icon volume-on]]
1512    $inner configure -borderwidth 4
1513
1514    checkbutton $inner.surface \
1515        -text "Surface" \
1516        -variable [itcl::scope _settings(-surfacevisible)] \
1517        -command [itcl::code $this AdjustSetting -surfacevisible] \
1518        -font "Arial 9"
1519
1520    checkbutton $inner.isolines \
1521        -text "Isolines" \
1522        -variable [itcl::scope _settings(-isolinesvisible)] \
1523        -command [itcl::code $this AdjustSetting -isolinesvisible] \
1524        -font "Arial 9"
1525
1526    checkbutton $inner.colormapDiscrete \
1527        -text "Discrete Colormap" \
1528        -variable [itcl::scope _settings(-colormapdiscrete)] \
1529        -command [itcl::code $this AdjustSetting -colormapdiscrete] \
1530        -font "Arial 9"
1531
1532    checkbutton $inner.wireframe \
1533        -text "Wireframe" \
1534        -variable [itcl::scope _settings(-surfacewireframe)] \
1535        -command [itcl::code $this AdjustSetting -surfacewireframe] \
1536        -font "Arial 9"
1537
1538    checkbutton $inner.lighting \
1539        -text "Enable Lighting" \
1540        -variable [itcl::scope _settings(-surfacelighting)] \
1541        -command [itcl::code $this AdjustSetting -surfacelighting] \
1542        -font "Arial 9"
1543
1544    checkbutton $inner.edges \
1545        -text "Edges" \
1546        -variable [itcl::scope _settings(-surfaceedges)] \
1547        -command [itcl::code $this AdjustSetting -surfaceedges] \
1548        -font "Arial 9"
1549
1550    checkbutton $inner.outline \
1551        -text "Outline" \
1552        -variable [itcl::scope _settings(-outline)] \
1553        -command [itcl::code $this AdjustSetting -outline] \
1554        -font "Arial 9"
1555
1556    checkbutton $inner.legend \
1557        -text "Legend" \
1558        -variable [itcl::scope _settings(-legendvisible)] \
1559        -command [itcl::code $this AdjustSetting -legendvisible] \
1560        -font "Arial 9"
1561
1562    label $inner.linecolor_l -text "Isolines" -font "Arial 9"
1563    itk_component add isolineColor {
1564        Rappture::Combobox $inner.linecolor -width 10 -editable 0
1565    }
1566    $inner.linecolor choices insert end \
1567        "black"              "black"            \
1568        "blue"               "blue"             \
1569        "cyan"               "cyan"             \
1570        "green"              "green"            \
1571        "grey"               "grey"             \
1572        "magenta"            "magenta"          \
1573        "orange"             "orange"           \
1574        "red"                "red"              \
1575        "white"              "white"            \
1576        "none"               "none"
1577
1578    $itk_component(isolineColor) value "white"
1579    bind $inner.linecolor <<Value>> \
1580        [itcl::code $this AdjustSetting -isolinecolor]
1581
1582    label $inner.background_l -text "Background" -font "Arial 9"
1583    itk_component add background {
1584        Rappture::Combobox $inner.background -width 10 -editable 0
1585    }
1586    $inner.background choices insert end \
1587        "black"              "black"            \
1588        "white"              "white"            \
1589        "grey"               "grey"             
1590
1591    $itk_component(background) value $_settings(-background)
1592    bind $inner.background <<Value>> \
1593        [itcl::code $this AdjustSetting -background]
1594
1595    label $inner.opacity_l -text "Opacity" -font "Arial 9"
1596    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1597        -variable [itcl::scope _settings(-surfaceopacity)] \
1598        -width 10 \
1599        -showvalue off \
1600        -command [itcl::code $this AdjustSetting -surfaceopacity]
1601
1602    itk_component add field_l {
1603        label $inner.field_l -text "Field" -font "Arial 9"
1604    } {
1605        ignore -font
1606    }
1607    itk_component add field {
1608        Rappture::Combobox $inner.field -width 10 -editable 0
1609    }
1610    bind $inner.field <<Value>> \
1611        [itcl::code $this AdjustSetting -field]
1612
1613    label $inner.colormap_l -text "Colormap" -font "Arial 9"
1614    itk_component add colormap {
1615        Rappture::Combobox $inner.colormap -width 10 -editable 0
1616    }
1617    $inner.colormap choices insert end [GetColormapList]
1618
1619    $itk_component(colormap) value "BCGYR"
1620    bind $inner.colormap <<Value>> \
1621        [itcl::code $this AdjustSetting -colormap]
1622
1623    label $inner.numcontours_l -text "Number of Isolines" -font "Arial 9"
1624    itk_component add numcontours {
1625        Rappture::Spinint $inner.numcontours \
1626            -min 0 -max 50 -font "arial 9"
1627    }
1628    $itk_component(numcontours) value $_settings(-numcontours)
1629    bind $itk_component(numcontours) <<Value>> \
1630        [itcl::code $this AdjustSetting -numcontours]
1631
1632    blt::table $inner \
1633        0,0 $inner.field_l   -anchor w -pady 2  \
1634        0,1 $inner.field     -anchor w -pady 2  -fill x \
1635        1,0 $inner.colormap_l -anchor w -pady 2  \
1636        1,1 $inner.colormap   -anchor w -pady 2  -fill x \
1637        2,0 $inner.linecolor_l  -anchor w -pady 2  \
1638        2,1 $inner.linecolor    -anchor w -pady 2 -fill x  \
1639        3,0 $inner.background_l -anchor w -pady 2 \
1640        3,1 $inner.background -anchor w -pady 2  -fill x \
1641        4,0 $inner.numcontours_l -anchor w -pady 2 \
1642        4,1 $inner.numcontours -anchor w -pady 2 \
1643        5,0 $inner.colormapDiscrete -anchor w -pady 2 -cspan 2 \
1644        6,0 $inner.isolines  -anchor w -pady 2 -cspan 2 \
1645        7,0 $inner.wireframe -anchor w -pady 2 -cspan 2 \
1646        8,0 $inner.lighting  -anchor w -pady 2 -cspan 2 \
1647        9,0 $inner.edges     -anchor w -pady 2 -cspan 2 \
1648        10,0 $inner.outline   -anchor w -pady 2 -cspan 2 \
1649        11,0 $inner.legend    -anchor w -pady 2 \
1650        12,0 $inner.opacity_l -anchor w -pady 2 \
1651        12,1 $inner.opacity   -fill x   -pady 2 -fill x \
1652
1653    blt::table configure $inner r* c* -resize none
1654    blt::table configure $inner r13 c1 -resize expand
1655}
1656
1657itcl::body Rappture::VtkSurfaceViewer::BuildAxisTab {} {
1658
1659    set fg [option get $itk_component(hull) font Font]
1660    #set bfg [option get $itk_component(hull) boldFont Font]
1661
1662    set inner [$itk_component(main) insert end \
1663        -title "Axis Settings" \
1664        -icon [Rappture::icon axis2]]
1665    $inner configure -borderwidth 4
1666
1667    checkbutton $inner.visible \
1668        -text "Axes" \
1669        -variable [itcl::scope _settings(-axesvisible)] \
1670        -command [itcl::code $this AdjustSetting -axesvisible] \
1671        -font "Arial 9"
1672
1673    checkbutton $inner.labels \
1674        -text "Axis Labels" \
1675        -variable [itcl::scope _settings(-axislabels)] \
1676        -command [itcl::code $this AdjustSetting -axislabels] \
1677        -font "Arial 9"
1678    label $inner.grid_l -text "Grid" -font "Arial 9"
1679    checkbutton $inner.xgrid \
1680        -text "X" \
1681        -variable [itcl::scope _settings(-xaxisgrid)] \
1682        -command [itcl::code $this AdjustSetting -xaxisgrid] \
1683        -font "Arial 9"
1684    checkbutton $inner.ygrid \
1685        -text "Y" \
1686        -variable [itcl::scope _settings(-yaxisgrid)] \
1687        -command [itcl::code $this AdjustSetting -yaxisgrid] \
1688        -font "Arial 9"
1689    checkbutton $inner.zgrid \
1690        -text "Z" \
1691        -variable [itcl::scope _settings(-zaxisgrid)] \
1692        -command [itcl::code $this AdjustSetting -zaxisgrid] \
1693        -font "Arial 9"
1694    checkbutton $inner.minorticks \
1695        -text "Minor Ticks" \
1696        -variable [itcl::scope _settings(-axisminorticks)] \
1697        -command [itcl::code $this AdjustSetting -axisminorticks] \
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 4 \
1715        1,0 $inner.labels  -anchor w -cspan 4 \
1716        2,0 $inner.minorticks  -anchor w -cspan 4 \
1717        4,0 $inner.grid_l  -anchor w \
1718        4,1 $inner.xgrid   -anchor w \
1719        4,2 $inner.ygrid   -anchor w \
1720        4,3 $inner.zgrid   -anchor w \
1721        5,0 $inner.mode_l  -anchor w -padx { 2 0 } \
1722        5,1 $inner.mode    -fill x   -cspan 3
1723
1724    blt::table configure $inner r* c* -resize none
1725    blt::table configure $inner r7 c6 -resize expand
1726    blt::table configure $inner r3 -height 0.125i
1727}
1728
1729itcl::body Rappture::VtkSurfaceViewer::BuildCameraTab {} {
1730    set inner [$itk_component(main) insert end \
1731        -title "Camera Settings" \
1732        -icon [Rappture::icon camera]]
1733    $inner configure -borderwidth 4
1734
1735    label $inner.view_l -text "view" -font "Arial 9"
1736    set f [frame $inner.view]
1737    foreach side { front back left right top bottom } {
1738        button $f.$side  -image [Rappture::icon view$side] \
1739            -command [itcl::code $this SetOrientation $side]
1740        Rappture::Tooltip::for $f.$side "Change the view to $side"
1741        pack $f.$side -side left
1742    }
1743
1744    blt::table $inner \
1745        0,0 $inner.view_l -anchor e -pady 2 \
1746        0,1 $inner.view -anchor w -pady 2
1747
1748    set labels { qx qy qz qw xpan ypan zoom }
1749    set row 1
1750    foreach tag $labels {
1751        label $inner.${tag}label -text $tag -font "Arial 9"
1752        entry $inner.${tag} -font "Arial 9"  -bg white \
1753            -textvariable [itcl::scope _view($tag)]
1754        bind $inner.${tag} <KeyPress-Return> \
1755            [itcl::code $this camera set ${tag}]
1756        blt::table $inner \
1757            $row,0 $inner.${tag}label -anchor e -pady 2 \
1758            $row,1 $inner.${tag} -anchor w -pady 2
1759        blt::table configure $inner r$row -resize none
1760        incr row
1761    }
1762    checkbutton $inner.ortho \
1763        -text "Orthographic Projection" \
1764        -variable [itcl::scope _view(ortho)] \
1765        -command [itcl::code $this camera set ortho] \
1766        -font "Arial 9"
1767    blt::table $inner \
1768            $row,0 $inner.ortho -cspan 2 -anchor w -pady 2
1769    blt::table configure $inner r$row -resize none
1770    incr row
1771
1772    blt::table configure $inner c* r* -resize none
1773    blt::table configure $inner c2 -resize expand
1774    blt::table configure $inner r$row -resize expand
1775}
1776
1777#
1778#  camera --
1779#
1780itcl::body Rappture::VtkSurfaceViewer::camera {option args} {
1781    switch -- $option {
1782        "show" {
1783            puts [array get _view]
1784        }
1785        "set" {
1786            set who [lindex $args 0]
1787            set x $_view($who)
1788            set code [catch { string is double $x } result]
1789            if { $code != 0 || !$result } {
1790                return
1791            }
1792            switch -- $who {
1793                "ortho" {
1794                    if {$_view(ortho)} {
1795                        SendCmd "camera mode ortho"
1796                    } else {
1797                        SendCmd "camera mode persp"
1798                    }
1799                }
1800                "xpan" - "ypan" {
1801                    PanCamera
1802                }
1803                "qx" - "qy" - "qz" - "qw" {
1804                    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1805                    $_arcball quaternion $q
1806                    EventuallyRotate $q
1807                }
1808                "zoom" {
1809                    SendCmd "camera zoom $_view(zoom)"
1810                }
1811             }
1812        }
1813    }
1814}
1815
1816itcl::body Rappture::VtkSurfaceViewer::GetVtkData { args } {
1817    set bytes ""
1818    foreach dataobj [get] {
1819        foreach cname [$dataobj components] {
1820            set tag $dataobj-$cname
1821            set contents [$dataobj vtkdata $cname]
1822            append bytes "$contents\n"
1823        }
1824    }
1825    return [list .vtk $bytes]
1826}
1827
1828itcl::body Rappture::VtkSurfaceViewer::GetImage { args } {
1829    if { [image width $_image(download)] > 0 &&
1830         [image height $_image(download)] > 0 } {
1831        set bytes [$_image(download) data -format "jpeg -quality 100"]
1832        set bytes [Rappture::encoding::decode -as b64 $bytes]
1833        return [list .jpg $bytes]
1834    }
1835    return ""
1836}
1837
1838itcl::body Rappture::VtkSurfaceViewer::BuildDownloadPopup { popup command } {
1839    Rappture::Balloon $popup \
1840        -title "[Rappture::filexfer::label downloadWord] as..."
1841    set inner [$popup component inner]
1842    label $inner.summary -text "" -anchor w
1843    radiobutton $inner.vtk_button -text "VTK data file" \
1844        -variable [itcl::scope _downloadPopup(format)] \
1845        -font "Arial 9 " \
1846        -value vtk 
1847    Rappture::Tooltip::for $inner.vtk_button "Save as VTK data file."
1848    radiobutton $inner.image_button -text "Image File" \
1849        -variable [itcl::scope _downloadPopup(format)] \
1850        -font "Arial 9 " \
1851        -value image
1852    Rappture::Tooltip::for $inner.image_button \
1853        "Save as digital image."
1854
1855    button $inner.ok -text "Save" \
1856        -highlightthickness 0 -pady 2 -padx 3 \
1857        -command $command \
1858        -compound left \
1859        -image [Rappture::icon download]
1860
1861    button $inner.cancel -text "Cancel" \
1862        -highlightthickness 0 -pady 2 -padx 3 \
1863        -command [list $popup deactivate] \
1864        -compound left \
1865        -image [Rappture::icon cancel]
1866
1867    blt::table $inner \
1868        0,0 $inner.summary -cspan 2  \
1869        1,0 $inner.vtk_button -anchor w -cspan 2 -padx { 4 0 } \
1870        2,0 $inner.image_button -anchor w -cspan 2 -padx { 4 0 } \
1871        4,1 $inner.cancel -width .9i -fill y \
1872        4,0 $inner.ok -padx 2 -width .9i -fill y
1873    blt::table configure $inner r3 -height 4
1874    blt::table configure $inner r4 -pady 4
1875    raise $inner.image_button
1876    $inner.vtk_button invoke
1877    return $inner
1878}
1879
1880itcl::body Rappture::VtkSurfaceViewer::SetObjectStyle { dataobj comp } {
1881    # Parse style string.
1882    set tag $dataobj-$comp
1883    array set style {
1884        -color BCGYR
1885        -edgecolor black
1886        -edges 0
1887        -isolinecolor white
1888        -isolinesvisible 0
1889        -levels 10
1890        -lighting 1
1891        -linewidth 1.0
1892        -opacity 1.0
1893        -outline 0
1894        -surfacevisible 1
1895        -wireframe 0
1896    }
1897    array set style [$dataobj style $comp]
1898    if { $dataobj != $_first || $style(-levels) == 1 } {
1899        set style(-opacity) 1
1900    }
1901
1902    # This is too complicated.  We want to set the colormap, number of
1903    # isolines and opacity for the dataset.  They can be the default values,
1904    # the style hints loaded with the dataset, or set by user controls.  As
1905    # datasets get loaded, they first use the defaults that are overidden
1906    # by the style hints.  If the user changes the global controls, then that
1907    # overrides everything else.  I don't know what it means when global
1908    # controls are specified as style hints by each dataset.  It complicates
1909    # the code to handle aberrant cases.
1910
1911    if { $_changed(-surfaceopacity) } {
1912        set style(-opacity) [expr $_settings(-surfaceopacity) * 0.01]
1913    }
1914    if { $_changed(-numcontours) } {
1915        set style(-levels) $_settings(-numcontours)
1916    }
1917    if { $_changed(-colormap) } {
1918        set style(-color) $_settings(-colormap)
1919    }
1920    if { $_currentColormap == "" } {
1921        SetCurrentColormap $style(-color)
1922        $itk_component(colormap) value $style(-color)
1923    }
1924    if { $_currentNumContours != $style(-levels) } {
1925        set _currentNumContours $style(-levels)
1926        set _settings(-numcontours) $_currentNumContours
1927        $itk_component(numcontours) value $_currentNumContours
1928        UpdateContourList
1929        DrawLegend
1930    }
1931    set _settings(-isolinesvisible) $style(-isolinesvisible)
1932    set _settings(-surfacevisible) $style(-surfacevisible)
1933 
1934    SendCmd "outline add $tag"
1935    SendCmd "outline color [Color2RGB $itk_option(-plotforeground)] $tag"
1936    SendCmd "outline visible $style(-outline) $tag"
1937    set _settings(-outline) $style(-outline)
1938
1939    SendCmd "polydata add $tag"
1940    SendCmd "polydata edges $style(-edges) $tag"
1941    set _settings(-surfaceedges) $style(-edges)
1942    #SendCmd "polydata color [Color2RGB $settings(-color)] $tag"
1943    SendCmd "polydata lighting $style(-lighting) $tag"
1944    set _settings(-surfacelighting) $style(-lighting)
1945    SendCmd "polydata linecolor [Color2RGB $style(-edgecolor)] $tag"
1946    SendCmd "polydata linewidth $style(-linewidth) $tag"
1947    SendCmd "polydata opacity $style(-opacity) $tag"
1948    set _settings(-surfaceopacity) [expr $style(-opacity) * 100.0]
1949    SetCurrentColormap $style(-color)
1950    SendCmd "polydata wireframe $style(-wireframe) $tag"
1951    set _settings(-surfacewireframe) $style(-wireframe)
1952
1953    SendCmd [list contour2d add contourlist $_contourList $tag]
1954    SendCmd "contour2d colormode constant {} $tag"
1955    SendCmd "contour2d color [Color2RGB $style(-isolinecolor)] $tag"
1956}
1957
1958itcl::body Rappture::VtkSurfaceViewer::IsValidObject { dataobj } {
1959    if {[catch {$dataobj isa Rappture::Field} valid] != 0 || !$valid} {
1960        return 0
1961    }
1962    return 1
1963}
1964
1965#
1966# EnterLegend --
1967#
1968itcl::body Rappture::VtkSurfaceViewer::EnterLegend { x y } {
1969    SetLegendTip $x $y
1970}
1971
1972#
1973# MotionLegend --
1974#
1975itcl::body Rappture::VtkSurfaceViewer::MotionLegend { x y } {
1976    Rappture::Tooltip::tooltip cancel
1977    set c $itk_component(view)
1978    set cw [winfo width $c]
1979    set ch [winfo height $c]
1980    if { $x >= 0 && $x < $cw && $y >= 0 && $y < $ch } {
1981        SetLegendTip $x $y
1982    }
1983}
1984
1985#
1986# LeaveLegend --
1987#
1988itcl::body Rappture::VtkSurfaceViewer::LeaveLegend { } {
1989    Rappture::Tooltip::tooltip cancel
1990    .rappturetooltip configure -icon ""
1991}
1992
1993#
1994# SetLegendTip --
1995#
1996itcl::body Rappture::VtkSurfaceViewer::SetLegendTip { x y } {
1997    set fname $_curFldName
1998    set c $itk_component(view)
1999    set w [winfo width $c]
2000    set h [winfo height $c]
2001
2002    set font "Arial 8"
2003    set lineht [font metrics $font -linespace]
2004   
2005    set ih [image height $_image(legend)]
2006    set iy [expr $y - ($lineht + 2)]
2007
2008    if { [string match "component*" $fname] } {
2009        set title ""
2010    } else {
2011        if { [info exists _fields($fname)] } {
2012            foreach { title units } $_fields($fname) break
2013            if { $units != "" } {
2014                set title [format "%s (%s)" $title $units]
2015            }
2016        } else {
2017            set title $fname
2018        }
2019    }
2020    # If there's a legend title, increase the offset by the line height.
2021    if { $title != "" } {
2022        incr iy -$lineht
2023    }
2024    # Make a swatch of the selected color
2025    if { [catch { $_image(legend) get 10 $iy } pixel] != 0 } {
2026        return
2027    }
2028    if { ![info exists _image(swatch)] } {
2029        set _image(swatch) [image create photo -width 24 -height 24]
2030    }
2031    set color [eval format "\#%02x%02x%02x" $pixel]
2032    $_image(swatch) put black  -to 0 0 23 23
2033    $_image(swatch) put $color -to 1 1 22 22
2034    .rappturetooltip configure -icon $_image(swatch)
2035
2036    # Compute the value of the point
2037    if { [info exists _limits($_curFldName)] } {
2038        foreach { vmin vmax } $_limits($_curFldName) break
2039        set t [expr 1.0 - (double($iy) / double($ih-1))]
2040        set value [expr $t * ($vmax - $vmin) + $vmin]
2041    } else {
2042        set value 0.0
2043    }
2044    set tx [expr $x + 15]
2045    set ty [expr $y - 5]
2046    if { [info exists _isolines($y)] } {
2047        Rappture::Tooltip::text $c [format "$title %g (isoline)" $_isolines($y)]
2048    } else {
2049        Rappture::Tooltip::text $c [format "$title %g" $value]
2050    }
2051    Rappture::Tooltip::tooltip show $c +$tx,+$ty   
2052}
2053
2054#
2055# ReceiveLegend --
2056#
2057#       Invoked automatically whenever the "legend" command comes in from
2058#       the rendering server.  Indicates that binary image data with the
2059#       specified <size> will follow.
2060#
2061itcl::body Rappture::VtkSurfaceViewer::ReceiveLegend { colormap title min max size } {
2062    #puts stderr "ReceiveLegend colormap=$colormap title=$title range=$min,$max size=$size"
2063    set _title $title
2064    regsub {\(mag\)} $title "" _title
2065    if { [IsConnected] } {
2066        set bytes [ReceiveBytes $size]
2067        if { ![info exists _image(legend)] } {
2068            set _image(legend) [image create photo]
2069        }
2070        $_image(legend) configure -data $bytes
2071        #puts stderr "read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
2072        if { [catch {DrawLegend} errs] != 0 } {
2073            global errorInfo
2074            puts stderr "errs=$errs errorInfo=$errorInfo"
2075        }
2076    }
2077}
2078
2079#
2080# DrawLegend --
2081#
2082#       Draws the legend in the own canvas on the right side of the plot area.
2083#
2084itcl::body Rappture::VtkSurfaceViewer::DrawLegend {} {
2085    set fname $_curFldName
2086    set c $itk_component(view)
2087    set w [winfo width $c]
2088    set h [winfo height $c]
2089    set font "Arial 8"
2090    set lineht [font metrics $font -linespace]
2091
2092    if { [string match "component*" $fname] } {
2093        set title ""
2094    } else {
2095        if { [info exists _fields($fname)] } {
2096            foreach { title units } $_fields($fname) break
2097            if { $units != "" } {
2098                set title [format "%s (%s)" $title $units]
2099            }
2100        } else {
2101            set title $fname
2102        }
2103    }
2104    set x [expr $w - 2]
2105    if { !$_settings(-legendvisible) } {
2106        $c delete legend
2107        return
2108    }
2109    if { [$c find withtag "legend"] == "" } {
2110        set y 2
2111        # If there's a legend title, create a text item for the title.
2112        $c create text $x $y \
2113            -anchor ne \
2114            -fill $itk_option(-plotforeground) -tags "title legend" \
2115            -font $font
2116        if { $title != "" } {
2117            incr y $lineht
2118        }
2119        $c create text $x $y \
2120            -anchor ne \
2121            -fill $itk_option(-plotforeground) -tags "vmax legend" \
2122            -font $font
2123        incr y $lineht
2124        $c create image $x $y \
2125            -anchor ne \
2126            -image $_image(legend) -tags "colormap legend"
2127        $c create rectangle $x $y 1 1 \
2128            -fill "" -outline "" -tags "sensor legend"
2129        $c create text $x [expr {$h-2}] \
2130            -anchor se \
2131            -fill $itk_option(-plotforeground) -tags "vmin legend" \
2132            -font $font
2133        $c bind sensor <Enter> [itcl::code $this EnterLegend %x %y]
2134        $c bind sensor <Leave> [itcl::code $this LeaveLegend]
2135        $c bind sensor <Motion> [itcl::code $this MotionLegend %x %y]
2136    }
2137    $c delete isoline
2138    set x2 $x
2139    set iw [image width $_image(legend)]
2140    set ih [image height $_image(legend)]
2141    set x1 [expr $x2 - ($iw*12)/10]
2142    set color $_settings(-isolinecolor)
2143    # Draw the isolines on the legend.
2144    array unset _isolines
2145    if { $color != "none"  && [info exists _limits($_curFldName)] &&
2146         $_settings(-isolinesvisible) && $_settings(-numcontours) > 0 } {
2147
2148        foreach { vmin vmax } $_limits($_curFldName) break
2149        set range [expr double($vmax - $vmin)]
2150        if { $range <= 0.0 } {
2151            set range 1.0;              # Min is greater or equal to max.
2152        }
2153        set tags "isoline legend"
2154        set offset [expr 2 + $lineht]
2155        if { $title != "" } {
2156            incr offset $lineht
2157        }
2158        foreach value $_contourList {
2159            set norm [expr 1.0 - (($value - $vmin) / $range)]
2160            set y1 [expr int(round(($norm * $ih) + $offset))]
2161            for { set off 0 } { $off < 3 } { incr off } {
2162                set _isolines([expr $y1 + $off]) $value
2163                set _isolines([expr $y1 - $off]) $value
2164            }
2165            $c create line $x1 $y1 $x2 $y1 -fill $color -tags $tags
2166        }
2167    }
2168
2169    $c bind title <ButtonPress> [itcl::code $this Combo post]
2170    $c bind title <Enter> [itcl::code $this Combo activate]
2171    $c bind title <Leave> [itcl::code $this Combo deactivate]
2172    # Reset the item coordinates according the current size of the plot.
2173    $c itemconfigure title -text $title
2174    if { [info exists _limits($_curFldName)] } {
2175        foreach { vmin vmax } $_limits($_curFldName) break
2176        $c itemconfigure vmin -text [format %g $vmin]
2177        $c itemconfigure vmax -text [format %g $vmax]
2178    }
2179    set y 2
2180    # If there's a legend title, move the title to the correct position
2181    if { $title != "" } {
2182        $c itemconfigure title -text $title
2183        $c coords title $x $y
2184        incr y $lineht
2185        $c raise title
2186    }
2187    $c coords vmax $x $y
2188    incr y $lineht
2189    $c coords colormap $x $y
2190    $c coords sensor [expr $x - $iw] $y $x [expr $y + $ih]
2191    $c raise sensor
2192    $c coords vmin $x [expr {$h - 2}]
2193}
2194
2195# ----------------------------------------------------------------------
2196# USAGE: _dropdown post
2197# USAGE: _dropdown unpost
2198# USAGE: _dropdown select
2199#
2200# Used internally to handle the dropdown list for this combobox.  The
2201# post/unpost options are invoked when the list is posted or unposted
2202# to manage the relief of the controlling button.  The select option
2203# is invoked whenever there is a selection from the list, to assign
2204# the value back to the gauge.
2205# ----------------------------------------------------------------------
2206itcl::body Rappture::VtkSurfaceViewer::Combo {option} {
2207    set c $itk_component(view)
2208    switch -- $option {
2209        post {
2210            foreach { x1 y1 x2 y2 } [$c bbox title] break
2211            set cw [winfo width $itk_component(view)]
2212            set mw [winfo reqwidth $itk_component(fieldmenu)]
2213            set x1 [expr $cw - $mw]
2214            set x [expr $x1 + [winfo rootx $itk_component(view)]]
2215            set y [expr $y2 + [winfo rooty $itk_component(view)]]
2216            tk_popup $itk_component(fieldmenu) $x $y
2217        }
2218        activate {
2219            $c itemconfigure title -fill red
2220        }
2221        deactivate {
2222            $c itemconfigure title -fill $itk_option(-plotforeground)
2223        }
2224        invoke {
2225            $itk_component(field) value $_curFldLabel
2226            AdjustSetting -field
2227        }
2228        default {
2229            error "bad option \"$option\": should be post, unpost, select"
2230        }
2231    }
2232}
2233
2234#
2235# SetCurrentColormap --
2236#
2237itcl::body Rappture::VtkSurfaceViewer::SetCurrentColormap { name } {
2238    # Keep track of the colormaps that we build.
2239    if { ![info exists _colormaps($name)] } {
2240        BuildColormap $name
2241        set _colormaps($name) 1
2242    }
2243    set _currentColormap $name
2244    SendCmd "contour2d colormap $_currentColormap"
2245    SendCmd "polydata colormap $_currentColormap"
2246}
2247
2248#
2249# BuildColormap --
2250#
2251#       Build the designated colormap on the server.
2252#
2253itcl::body Rappture::VtkSurfaceViewer::BuildColormap { name } {
2254    set cmap [ColorsToColormap $name]
2255    if { [llength $cmap] == 0 } {
2256        set cmap "0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0"
2257    }
2258    set wmap "0.0 1.0 1.0 1.0"
2259    SendCmd "colormap add $name { $cmap } { $wmap }"
2260}
2261
2262itcl::body Rappture::VtkSurfaceViewer::SetOrientation { side } {
2263    array set positions {
2264        front "1 0 0 0"
2265        back  "0 0 1 0"
2266        left  "0.707107 0 -0.707107 0"
2267        right "0.707107 0 0.707107 0"
2268        top   "0.707107 -0.707107 0 0"
2269        bottom "0.707107 0.707107 0 0"
2270    }
2271    foreach name { qw qx qy qz } value $positions($side) {
2272        set _view($name) $value
2273    }
2274    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
2275    $_arcball quaternion $q
2276    SendCmd "camera orient $q"
2277    SendCmd "camera reset"
2278    set _view(xpan) 0
2279    set _view(ypan) 0
2280    set _view(zoom) 1.0
2281}
2282
2283itcl::body Rappture::VtkSurfaceViewer::UpdateContourList {} {
2284    if { ![info exists _limits($_curFldName)] } {
2285        return
2286    }
2287    if { $_currentNumContours < 1 } {
2288        set _contourList ""
2289        return
2290    }
2291    foreach { vmin vmax } $_limits($_curFldName) break
2292    set v [blt::vector create \#auto]
2293    $v seq $vmin $vmax [expr $_currentNumContours+2]
2294    $v delete end 0
2295    set _contourList [$v range 0 end]
2296    blt::vector destroy $v
2297}
2298
Note: See TracBrowser for help on using the repository browser.