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

Last change on this file since 6337 was 6337, checked in by ldelgass, 8 years ago

whitespace

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