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

Last change on this file since 5769 was 5769, checked in by ldelgass, 9 years ago

whitespace

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