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

Last change on this file since 4344 was 4344, checked in by ldelgass, 7 years ago

Add VTK surface viewer for viewing colormapped surfaces from any field.

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