source: branches/1.3/gui/scripts/vtkglyphviewer.tcl @ 3739

Last change on this file since 3739 was 3739, checked in by gah, 11 years ago

bandaid R bindings for R 3.0.1

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