source: branches/r9/gui/scripts/vtkglyphviewer.tcl @ 4919

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