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

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

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

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