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

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

Some cleanups for glyph viewer

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