source: branches/blt4/gui/scripts/vtkstreamlinesviewer.tcl @ 2591

Last change on this file since 2591 was 2591, checked in by gah, 13 years ago

move package require vtk into constructor

File size: 68.5 KB
Line 
1
2# ----------------------------------------------------------------------
3#  COMPONENT: vtkviewer - Vtk drawing object viewer
4#
5#  It connects to the Vtk server running on a rendering farm,
6#  transmits data, and displays the results.
7# ======================================================================
8#  AUTHOR:  Michael McLennan, Purdue University
9#  Copyright (c) 2004-2005  Purdue Research Foundation
10#
11#  See the file "license.terms" for information on usage and
12#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
13# ======================================================================
14package require Itk
15package require BLT
16#package require Img
17
18option add *VtkStreamlinesViewer.width 4i widgetDefault
19option add *VtkStreamlinesViewer*cursor crosshair widgetDefault
20option add *VtkStreamlinesViewer.height 4i widgetDefault
21option add *VtkStreamlinesViewer.foreground black widgetDefault
22option add *VtkStreamlinesViewer.controlBackground gray widgetDefault
23option add *VtkStreamlinesViewer.controlDarkBackground #999999 widgetDefault
24option add *VtkStreamlinesViewer.plotBackground black widgetDefault
25option add *VtkStreamlinesViewer.plotForeground white widgetDefault
26option add *VtkStreamlinesViewer.font \
27    -*-helvetica-medium-r-normal-*-12-* widgetDefault
28
29# must use this name -- plugs into Rappture::resources::load
30proc VtkStreamlinesViewer_init_resources {} {
31    Rappture::resources::register \
32        vtkvis_server Rappture::VtkStreamlinesViewer::SetServerList
33}
34
35itcl::class Rappture::VtkStreamlinesViewer {
36    inherit Rappture::VisViewer
37
38    itk_option define -plotforeground plotForeground Foreground ""
39    itk_option define -plotbackground plotBackground Background ""
40
41    constructor { hostlist args } {
42        Rappture::VisViewer::constructor $hostlist
43    } {
44        # defined below
45    }
46    destructor {
47        # defined below
48    }
49    public proc SetServerList { namelist } {
50        Rappture::VisViewer::SetServerList "vtkvis" $namelist
51    }
52    public method add {dataobj {settings ""}}
53    public method camera {option args}
54    public method delete {args}
55    public method disconnect {}
56    public method download {option args}
57    public method get {args}
58    public method isconnected {}
59    public method limits { colormap }
60    public method sendto { string }
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 FixSettings { 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 SendCmd {string}
81    protected method Zoom {option}
82
83    # The following methods are only used by this class.
84    private method BuildAxisTab {}
85    private method BuildCameraTab {}
86    private method BuildColormap { colormap dataobj comp }
87    private method BuildCutawayTab {}
88    private method BuildDownloadPopup { widget command }
89    private method BuildStreamsTab {}
90    private method BuildVolumeTab {}
91    private method ConvertToVtkData { dataobj comp }
92    private method DrawLegend {}
93    private method EnterLegend { x y }
94    private method EventuallyResize { w h }
95    private method EventuallyRotate { q }
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 SetColormap { dataobj comp }
104    private method SetLegendTip { x y }
105    private method SetObjectStyle { dataobj comp }
106    private method Slice {option args}
107
108    private variable _arcball ""
109    private variable _outbuf       ;# buffer for outgoing commands
110
111    private variable _dlist ""     ;# list of data objects
112    private variable _allDataObjs
113    private variable _obj2datasets
114    private variable _obj2ovride   ;# maps dataobj => style override
115    private variable _datasets     ;# contains all the dataobj-component
116                                   ;# datasets in the server
117    private variable _colormaps    ;# contains all the colormaps
118                                   ;# in the server.
119    private variable _dataset2style    ;# maps dataobj-component to transfunc
120    private variable _style2datasets   ;# maps tf back to list of
121                                    # dataobj-components using the tf.
122
123    private variable _click        ;# info used for rotate operations
124    private variable _limits       ;# autoscale min/max for all axes
125    private variable _view         ;# view params for 3D view
126    private variable _settings
127    private variable _volume
128    private variable _axis
129    private variable _streamlines
130    private variable _reset 1      ;# indicates if camera needs to be reset
131                                    # to starting position.
132
133    private variable _first ""     ;# This is the topmost dataset.
134    private variable _start 0
135    private variable _buffering 0
136    private variable _title ""
137    private variable _seeds
138
139    common _downloadPopup          ;# download options from popup
140    private common _hardcopy
141    private variable _width 0
142    private variable _height 0
143    private variable _resizePending 0
144    private variable _rotatePending 0
145    private variable _outline
146}
147
148itk::usual VtkStreamlinesViewer {
149    keep -background -foreground -cursor -font
150    keep -plotbackground -plotforeground
151}
152
153# ----------------------------------------------------------------------
154# CONSTRUCTOR
155# ----------------------------------------------------------------------
156itcl::body Rappture::VtkStreamlinesViewer::constructor {hostlist args} {
157    package require vtk
158    # Rebuild event
159    $_dispatcher register !rebuild
160    $_dispatcher dispatch $this !rebuild "[itcl::code $this Rebuild]; list"
161
162    # Resize event
163    $_dispatcher register !resize
164    $_dispatcher dispatch $this !resize "[itcl::code $this DoResize]; list"
165
166    # Rotate event
167    $_dispatcher register !rotate
168    $_dispatcher dispatch $this !rotate "[itcl::code $this DoRotate]; list"
169
170    set _outbuf ""
171
172    #
173    # Populate parser with commands handle incoming requests
174    #
175    $_parser alias image [itcl::code $this ReceiveImage]
176    $_parser alias dataset [itcl::code $this ReceiveDataset]
177    $_parser alias legend [itcl::code $this ReceiveLegend]
178
179    array set _outline {
180        id -1
181        afterId -1
182        x1 -1
183        y1 -1
184        x2 -1
185        y2 -1
186    }
187    # Initialize the view to some default parameters.
188    array set _view {
189        qw              1
190        qx              0
191        qy              0
192        qz              0
193        zoom            1.0
194        xpan            0
195        ypan            0
196        ortho           0
197    }
198    set _arcball [blt::arcball create 100 100]
199    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
200    $_arcball quaternion $q
201
202    set _limits(zmin) 0.0
203    set _limits(zmax) 1.0
204
205    array set _axis [subst {
206        xgrid           0
207        ygrid           0
208        zgrid           0
209        xcutaway        0
210        ycutaway        0
211        zcutaway        0
212        xposition       0
213        yposition       0
214        zposition       0
215        xdirection      -1
216        ydirection      -1
217        zdirection      -1
218        visible         1
219        labels          1
220    }]
221    array set _volume [subst {
222        edges           0
223        lighting        1
224        opacity         40
225        visible         1
226        wireframe       0
227    }]
228    array set _streamlines [subst {
229        seeds           0
230        visible         1
231        opacity         100
232    }]
233    array set _settings [subst {
234        legend          1
235    }]
236
237    itk_component add view {
238        canvas $itk_component(plotarea).view \
239            -highlightthickness 0 -borderwidth 0
240    } {
241        usual
242        ignore -highlightthickness -borderwidth  -background
243    }
244
245    set c $itk_component(view)
246    bind $c <Configure> [itcl::code $this EventuallyResize %w %h]
247    bind $c <4> [itcl::code $this Zoom in 0.25]
248    bind $c <5> [itcl::code $this Zoom out 0.25]
249    bind $c <KeyPress-Left>  [list %W xview scroll 10 units]
250    bind $c <KeyPress-Right> [list %W xview scroll -10 units]
251    bind $c <KeyPress-Up>    [list %W yview scroll 10 units]
252    bind $c <KeyPress-Down>  [list %W yview scroll -10 units]
253    bind $c <Enter> "focus %W"
254
255    # Fix the scrollregion in case we go off screen
256    $c configure -scrollregion [$c bbox all]
257
258    set _map(id) [$c create image 0 0 -anchor nw -image $_image(plot)]
259    set _map(cwidth) -1
260    set _map(cheight) -1
261    set _map(zoom) 1.0
262    set _map(original) ""
263
264    set f [$itk_component(main) component controls]
265    itk_component add reset {
266        button $f.reset -borderwidth 1 -padx 1 -pady 1 \
267            -highlightthickness 0 \
268            -image [Rappture::icon reset-view] \
269            -command [itcl::code $this Zoom reset]
270    } {
271        usual
272        ignore -highlightthickness
273    }
274    pack $itk_component(reset) -side top -padx 2 -pady 2
275    Rappture::Tooltip::for $itk_component(reset) "Reset the view to the default zoom level"
276
277    itk_component add zoomin {
278        button $f.zin -borderwidth 1 -padx 1 -pady 1 \
279            -highlightthickness 0 \
280            -image [Rappture::icon zoom-in] \
281            -command [itcl::code $this Zoom in]
282    } {
283        usual
284        ignore -highlightthickness
285    }
286    pack $itk_component(zoomin) -side top -padx 2 -pady 2
287    Rappture::Tooltip::for $itk_component(zoomin) "Zoom in"
288
289    itk_component add zoomout {
290        button $f.zout -borderwidth 1 -padx 1 -pady 1 \
291            -highlightthickness 0 \
292            -image [Rappture::icon zoom-out] \
293            -command [itcl::code $this Zoom out]
294    } {
295        usual
296        ignore -highlightthickness
297    }
298    pack $itk_component(zoomout) -side top -padx 2 -pady 2
299    Rappture::Tooltip::for $itk_component(zoomout) "Zoom out"
300
301    if { [catch {
302        BuildVolumeTab
303        BuildStreamsTab
304        BuildAxisTab
305        BuildCutawayTab
306        BuildCameraTab
307    } errs] != 0 } {
308        puts stderr errs=$errs
309    }
310    # Legend
311
312    set _image(legend) [image create photo]
313    itk_component add legend {
314        canvas $itk_component(plotarea).legend -width 50 -highlightthickness 0
315    } {
316        usual
317        ignore -highlightthickness
318        rename -background -plotbackground plotBackground Background
319    }
320
321    # Hack around the Tk panewindow.  The problem is that the requested
322    # size of the 3d view isn't set until an image is retrieved from
323    # the server.  So the panewindow uses the tiny size.
324    set w 10000
325    pack forget $itk_component(view)
326    blt::table $itk_component(plotarea) \
327        0,0 $itk_component(view) -fill both -reqwidth $w
328    blt::table configure $itk_component(plotarea) c1 -resize none
329
330    # Bindings for rotation via mouse
331    bind $itk_component(view) <ButtonPress-1> \
332        [itcl::code $this Rotate click %x %y]
333    bind $itk_component(view) <B1-Motion> \
334        [itcl::code $this Rotate drag %x %y]
335    bind $itk_component(view) <ButtonRelease-1> \
336        [itcl::code $this Rotate release %x %y]
337    bind $itk_component(view) <Configure> \
338        [itcl::code $this EventuallyResize %w %h]
339
340    if 0 {
341    bind $itk_component(view) <Configure> \
342        [itcl::code $this EventuallyResize %w %h]
343    }
344    # Bindings for panning via mouse
345    bind $itk_component(view) <ButtonPress-2> \
346        [itcl::code $this Pan click %x %y]
347    bind $itk_component(view) <B2-Motion> \
348        [itcl::code $this Pan drag %x %y]
349    bind $itk_component(view) <ButtonRelease-2> \
350        [itcl::code $this Pan release %x %y]
351
352    bind $itk_component(view) <ButtonRelease-3> \
353        [itcl::code $this Pick %x %y]
354
355    # Bindings for panning via keyboard
356    bind $itk_component(view) <KeyPress-Left> \
357        [itcl::code $this Pan set -10 0]
358    bind $itk_component(view) <KeyPress-Right> \
359        [itcl::code $this Pan set 10 0]
360    bind $itk_component(view) <KeyPress-Up> \
361        [itcl::code $this Pan set 0 -10]
362    bind $itk_component(view) <KeyPress-Down> \
363        [itcl::code $this Pan set 0 10]
364    bind $itk_component(view) <Shift-KeyPress-Left> \
365        [itcl::code $this Pan set -2 0]
366    bind $itk_component(view) <Shift-KeyPress-Right> \
367        [itcl::code $this Pan set 2 0]
368    bind $itk_component(view) <Shift-KeyPress-Up> \
369        [itcl::code $this Pan set 0 -2]
370    bind $itk_component(view) <Shift-KeyPress-Down> \
371        [itcl::code $this Pan set 0 2]
372
373    # Bindings for zoom via keyboard
374    bind $itk_component(view) <KeyPress-Prior> \
375        [itcl::code $this Zoom out]
376    bind $itk_component(view) <KeyPress-Next> \
377        [itcl::code $this Zoom in]
378
379    bind $itk_component(view) <Enter> "focus $itk_component(view)"
380
381    if {[string equal "x11" [tk windowingsystem]]} {
382        # Bindings for zoom via mouse
383        bind $itk_component(view) <4> [itcl::code $this Zoom out]
384        bind $itk_component(view) <5> [itcl::code $this Zoom in]
385    }
386
387    set _image(download) [image create photo]
388
389    eval itk_initialize $args
390    Connect
391}
392
393# ----------------------------------------------------------------------
394# DESTRUCTOR
395# ----------------------------------------------------------------------
396itcl::body Rappture::VtkStreamlinesViewer::destructor {} {
397    Disconnect
398    $_dispatcher cancel !rebuild
399    $_dispatcher cancel !resize
400    $_dispatcher cancel !rotate
401    image delete $_image(plot)
402    image delete $_image(download)
403    catch { blt::arcball destroy $_arcball }
404}
405
406itcl::body Rappture::VtkStreamlinesViewer::DoResize {} {
407    if { $_width < 2 } {
408        set _width 500
409    }
410    if { $_height < 2 } {
411        set _height 500
412    }
413    #puts stderr "DoResize screen size $_width $_height"
414    set _start [clock clicks -milliseconds]
415    #puts stderr "screen size request width=$_width height=$_height"
416    SendCmd "screen size $_width $_height"
417    RequestLegend
418
419    #SendCmd "imgflush"
420
421    # Must reset camera to have object scaling to take effect.
422    #SendCmd "camera reset"
423    #SendCmd "camera zoom $_view(zoom)"
424    set _resizePending 0
425}
426
427itcl::body Rappture::VtkStreamlinesViewer::DoRotate {} {
428    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
429    SendCmd "camera orient $q"
430    set _rotatePending 0
431}
432
433itcl::body Rappture::VtkStreamlinesViewer::EventuallyResize { w h } {
434    #puts stderr "EventuallyResize $w $h"
435    set _width $w
436    set _height $h
437    $_arcball resize $w $h
438    if { !$_resizePending } {
439        set _resizePending 1
440        $_dispatcher event -after 200 !resize
441    }
442}
443
444set rotate_delay 100
445
446itcl::body Rappture::VtkStreamlinesViewer::EventuallyRotate { q } {
447    #puts stderr "EventuallyRotate $w $h"
448    foreach { _view(qw) _view(qx) _view(qy) _view(qz) } $q break
449    if { !$_rotatePending } {
450        set _rotatePending 1
451        global rotate_delay
452        $_dispatcher event -after $rotate_delay !rotate
453    }
454}
455
456# ----------------------------------------------------------------------
457# USAGE: add <dataobj> ?<settings>?
458#
459# Clients use this to add a data object to the plot.  The optional
460# <settings> are used to configure the plot.  Allowed settings are
461# -color, -brightness, -width, -linestyle, and -raise.
462# ----------------------------------------------------------------------
463itcl::body Rappture::VtkStreamlinesViewer::add {dataobj {settings ""}} {
464    array set params {
465        -color auto
466        -width 1
467        -linestyle solid
468        -brightness 0
469        -raise 0
470        -description ""
471        -param ""
472        -type ""
473    }
474    array set params $settings
475    set params(-description) ""
476    set params(-param) ""
477    foreach {opt val} $settings {
478        if {![info exists params($opt)]} {
479            error "bad setting \"$opt\": should be [join [lsort [array names params]] {, }]"
480        }
481        set params($opt) $val
482    }
483    if {$params(-color) == "auto" || $params(-color) == "autoreset"} {
484        # can't handle -autocolors yet
485        set params(-color) black
486    }
487    set pos [lsearch -exact $dataobj $_dlist]
488    if {$pos < 0} {
489        lappend _dlist $dataobj
490    }
491    set _allDataObjs($dataobj) 1
492    set _obj2ovride($dataobj-color) $params(-color)
493    set _obj2ovride($dataobj-width) $params(-width)
494    set _obj2ovride($dataobj-raise) $params(-raise)
495    $_dispatcher event -idle !rebuild
496}
497
498
499# ----------------------------------------------------------------------
500# USAGE: delete ?<dataobj1> <dataobj2> ...?
501#
502#       Clients use this to delete a dataobj from the plot.  If no dataobjs
503#       are specified, then all dataobjs are deleted.  No data objects are
504#       deleted.  They are only removed from the display list.
505#
506# ----------------------------------------------------------------------
507itcl::body Rappture::VtkStreamlinesViewer::delete {args} {
508    if { [llength $args] == 0} {
509        set args $_dlist
510    }
511    # Delete all specified dataobjs
512    set changed 0
513    foreach dataobj $args {
514        set pos [lsearch -exact $_dlist $dataobj]
515        if { $pos < 0 } {
516            continue;                   # Don't know anything about it.
517        }
518        # Remove it from the dataobj list.
519        set _dlist [lreplace $_dlist $pos $pos]
520        foreach comp [$dataobj components] {
521            SendCmd "dataset visible 0 $dataobj-$comp"
522        }
523        array unset _obj2ovride $dataobj-*
524        # Append to the end of the dataobj list.
525        lappend _dlist $dataobj
526        set changed 1
527    }
528    # If anything changed, then rebuild the plot
529    if { $changed } {
530        $_dispatcher event -idle !rebuild
531    }
532}
533
534# ----------------------------------------------------------------------
535# USAGE: get ?-objects?
536# USAGE: get ?-visible?
537# USAGE: get ?-image view?
538#
539# Clients use this to query the list of objects being plotted, in
540# order from bottom to top of this result.  The optional "-image"
541# flag can also request the internal images being shown.
542# ----------------------------------------------------------------------
543itcl::body Rappture::VtkStreamlinesViewer::get {args} {
544    if {[llength $args] == 0} {
545        set args "-objects"
546    }
547
548    set op [lindex $args 0]
549    switch -- $op {
550        "-objects" {
551            # put the dataobj list in order according to -raise options
552            set dlist {}
553            foreach dataobj $_dlist {
554                if { ![IsValidObject $dataobj] } {
555                    continue
556                }
557                if {[info exists _obj2ovride($dataobj-raise)] &&
558                    $_obj2ovride($dataobj-raise)} {
559                    set dlist [linsert $dlist 0 $dataobj]
560                } else {
561                    lappend dlist $dataobj
562                }
563            }
564            return $dlist
565        }
566        "-visible" {
567            set dlist {}
568            foreach dataobj $_dlist {
569                if { ![IsValidObject $dataobj] } {
570                    continue
571                }
572                if { ![info exists _obj2ovride($dataobj-raise)] } {
573                    # No setting indicates that the object isn't invisible.
574                    continue
575                }
576                # Otherwise use the -raise parameter to put the object to
577                # the front of the list.
578                if { $_obj2ovride($dataobj-raise) } {
579                    set dlist [linsert $dlist 0 $dataobj]
580                } else {
581                    lappend dlist $dataobj
582                }
583            }
584            return $dlist
585        }           
586        -image {
587            if {[llength $args] != 2} {
588                error "wrong # args: should be \"get -image view\""
589            }
590            switch -- [lindex $args end] {
591                view {
592                    return $_image(plot)
593                }
594                default {
595                    error "bad image name \"[lindex $args end]\": should be view"
596                }
597            }
598        }
599        default {
600            error "bad option \"$op\": should be -objects or -image"
601        }
602    }
603}
604
605# ----------------------------------------------------------------------
606# USAGE: scale ?<data1> <data2> ...?
607#
608# Sets the default limits for the overall plot according to the
609# limits of the data for all of the given <data> objects.  This
610# accounts for all objects--even those not showing on the screen.
611# Because of this, the limits are appropriate for all objects as
612# the user scans through data in the ResultSet viewer.
613# ----------------------------------------------------------------------
614itcl::body Rappture::VtkStreamlinesViewer::scale {args} {
615    array unset _limits
616    foreach dataobj $args {
617        set string [limits $dataobj]
618        if { $string == "" } {
619            continue
620        }
621        array set bounds $string
622        if {![info exists _limits(xmin)] || $_limits(xmin) > $bounds(xmin)} {
623            set _limits(xmin) $bounds(xmin)
624        }
625        if {![info exists _limits(xmax)] || $_limits(xmax) < $bounds(xmax)} {
626            set _limits(xmax) $bounds(xmax)
627        }
628
629        if {![info exists _limits(ymin)] || $_limits(ymin) > $bounds(ymin)} {
630            set _limits(ymin) $bounds(ymin)
631        }
632        if {![info exists _limits(ymax)] || $_limits(ymax) < $bounds(ymax)} {
633            set _limits(ymax) $bounds(ymax)
634        }
635
636        if {![info exists _limits(zmin)] || $_limits(zmin) > $bounds(zmin)} {
637            set _limits(zmin) $bounds(zmin)
638        }
639        if {![info exists _limits(zmax)] || $_limits(zmax) < $bounds(zmax)} {
640            set _limits(zmax) $bounds(zmax)
641        }
642    }
643}
644
645# ----------------------------------------------------------------------
646# USAGE: download coming
647# USAGE: download controls <downloadCommand>
648# USAGE: download now
649#
650# Clients use this method to create a downloadable representation
651# of the plot.  Returns a list of the form {ext string}, where
652# "ext" is the file extension (indicating the type of data) and
653# "string" is the data itself.
654# ----------------------------------------------------------------------
655itcl::body Rappture::VtkStreamlinesViewer::download {option args} {
656    switch $option {
657        coming {
658            if {[catch {
659                blt::winop snap $itk_component(plotarea) $_image(download)
660            }]} {
661                $_image(download) configure -width 1 -height 1
662                $_image(download) put #000000
663            }
664        }
665        controls {
666            set popup .vtkviewerdownload
667            if { ![winfo exists .vtkviewerdownload] } {
668                set inner [BuildDownloadPopup $popup [lindex $args 0]]
669            } else {
670                set inner [$popup component inner]
671            }
672            set _downloadPopup(image_controls) $inner.image_frame
673            set num [llength [get]]
674            set num [expr {($num == 1) ? "1 result" : "$num results"}]
675            set word [Rappture::filexfer::label downloadWord]
676            $inner.summary configure -text "$word $num in the following format:"
677            update idletasks            ;# Fix initial sizes
678            return $popup
679        }
680        now {
681            set popup .vtkviewerdownload
682            if {[winfo exists .vtkviewerdownload]} {
683                $popup deactivate
684            }
685            switch -- $_downloadPopup(format) {
686                "image" {
687                    return [$this GetImage [lindex $args 0]]
688                }
689                "vtk" {
690                    return [$this GetVtkData [lindex $args 0]]
691                }
692            }
693            return ""
694        }
695        default {
696            error "bad option \"$option\": should be coming, controls, now"
697        }
698    }
699}
700
701# ----------------------------------------------------------------------
702# USAGE: Connect ?<host:port>,<host:port>...?
703#
704# Clients use this method to establish a connection to a new
705# server, or to reestablish a connection to the previous server.
706# Any existing connection is automatically closed.
707# ----------------------------------------------------------------------
708itcl::body Rappture::VtkStreamlinesViewer::Connect {} {
709    #puts stderr "Enter Connect: [info level -1]"
710    set _hosts [GetServerList "vtkvis"]
711    if { "" == $_hosts } {
712        return 0
713    }
714    set result [VisViewer::Connect $_hosts]
715    if { $result } {
716        #puts stderr "Connected to $_hostname sid=$_sid"
717        set w [winfo width $itk_component(view)]
718        set h [winfo height $itk_component(view)]
719        EventuallyResize $w $h
720    }
721    return $result
722}
723
724#
725# isconnected --
726#
727#       Indicates if we are currently connected to the visualization server.
728#
729itcl::body Rappture::VtkStreamlinesViewer::isconnected {} {
730    return [VisViewer::IsConnected]
731}
732
733#
734# disconnect --
735#
736itcl::body Rappture::VtkStreamlinesViewer::disconnect {} {
737    Disconnect
738    set _reset 1
739}
740
741#
742# Disconnect --
743#
744#       Clients use this method to disconnect from the current rendering
745#       server.
746#
747itcl::body Rappture::VtkStreamlinesViewer::Disconnect {} {
748    VisViewer::Disconnect
749
750    # disconnected -- no more data sitting on server
751    set _outbuf ""
752    array unset _datasets
753    array unset _data
754    array unset _colormaps
755}
756
757#
758# sendto --
759#
760itcl::body Rappture::VtkStreamlinesViewer::sendto { bytes } {
761    SendBytes "$bytes\n"
762}
763
764#
765# SendCmd
766#
767#       Send commands off to the rendering server.  If we're currently
768#       sending data objects to the server, buffer the commands to be
769#       sent later.
770#
771itcl::body Rappture::VtkStreamlinesViewer::SendCmd {string} {
772    if { $_buffering } {
773        append _outbuf $string "\n"
774    } else {
775        SendBytes "$string\n"
776    }
777}
778
779# ----------------------------------------------------------------------
780# USAGE: ReceiveImage -bytes <size> -type <type> -token <token>
781#
782# Invoked automatically whenever the "image" command comes in from
783# the rendering server.  Indicates that binary image data with the
784# specified <size> will follow.
785# ----------------------------------------------------------------------
786itcl::body Rappture::VtkStreamlinesViewer::ReceiveImage { args } {
787    array set info {
788        -token "???"
789        -bytes 0
790        -type image
791    }
792    array set info $args
793    set bytes [ReceiveBytes $info(-bytes)]
794    if { $info(-type) == "image" } {
795        if 0 {
796            set f [open "last.ppm" "w"]
797            puts $f $bytes
798            close $f
799        }
800        $_image(plot) configure -data $bytes
801        set time [clock seconds]
802        set date [clock format $time]
803        #puts stderr "$date: received image [image width $_image(plot)]x[image height $_image(plot)] image>"       
804        if { $_start > 0 } {
805            set finish [clock clicks -milliseconds]
806            #puts stderr "round trip time [expr $finish -$_start] milliseconds"
807            set _start 0
808        }
809    } elseif { $info(type) == "print" } {
810        set tag $this-print-$info(-token)
811        set _hardcopy($tag) $bytes
812    }
813}
814
815#
816# ReceiveDataset --
817#
818itcl::body Rappture::VtkStreamlinesViewer::ReceiveDataset { args } {
819    if { ![isconnected] } {
820        return
821    }
822    set option [lindex $args 0]
823    switch -- $option {
824        "scalar" {
825            set option [lindex $args 1]
826            switch -- $option {
827                "world" {
828                    foreach { x y z value tag } [lrange $args 2 end] break
829                }
830                "pixel" {
831                    foreach { x y value tag } [lrange $args 2 end] break
832                }
833            }
834        }
835        "vector" {
836            set option [lindex $args 1]
837            switch -- $option {
838                "world" {
839                    foreach { x y z vx vy vz tag } [lrange $args 2 end] break
840                }
841                "pixel" {
842                    foreach { x y vx vy vz tag } [lrange $args 2 end] break
843                }
844            }
845        }
846        "names" {
847            foreach { name } [lindex $args 1] {
848                #puts stderr "Dataset: $name"
849            }
850        }
851        default {
852            error "unknown dataset option \"$option\" from server"
853        }
854    }
855}
856
857# ----------------------------------------------------------------------
858# USAGE: Rebuild
859#
860# Called automatically whenever something changes that affects the
861# data in the widget.  Clears any existing data and rebuilds the
862# widget to display new data.
863# ----------------------------------------------------------------------
864itcl::body Rappture::VtkStreamlinesViewer::Rebuild {} {
865
866    set w [winfo width $itk_component(view)]
867    set h [winfo height $itk_component(view)]
868    if { $w < 2 || $h < 2 } {
869        $_dispatcher event -idle !rebuild
870        return
871    }
872
873    # Turn on buffering of commands to the server.  We don't want to
874    # be preempted by a server disconnect/reconnect (which automatically
875    # generates a new call to Rebuild).   
876    set _buffering 1
877
878    set _width $w
879    set _height $h
880    $_arcball resize $w $h
881    DoResize
882    #
883    # Reset the camera and other view parameters
884    #
885    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
886    $_arcball quaternion $q
887    if {$_view(ortho)} {
888        SendCmd "camera mode ortho"
889    } else {
890        SendCmd "camera mode persp"
891    }
892    DoRotate
893    PanCamera
894    set _first [lindex [get -objects] 0]
895    if { $_reset || $_first == "" } {
896        Zoom reset
897        set _reset 0
898    }
899    FixSettings axis-xgrid axis-ygrid axis-zgrid axis-mode \
900        axis-visible axis-labels \
901        streamlines-seeds streamlines-visible streamlines-opacity \
902        volume-edges volume-lighting volume-opacity volume-visible \
903        volume-wireframe
904
905    #SendCmd "imgflush"
906
907    set _limits(zmin) ""
908    set _limits(zmax) ""
909    set _first ""
910    foreach dataobj [get -objects] {
911        if { [info exists _obj2ovride($dataobj-raise)] &&  $_first == "" } {
912            set _first $dataobj
913        }
914        set _obj2datasets($dataobj) ""
915        foreach comp [$dataobj components] {
916            set tag $dataobj-$comp
917            if { ![info exists _datasets($tag)] } {
918                set bytes [$dataobj blob $comp]
919                set length [string length $bytes]
920                append _outbuf "dataset add $tag data follows $length\n"
921                append _outbuf $bytes
922                set _datasets($tag) 1
923            }
924            lappend _obj2datasets($dataobj) $tag
925            if { [info exists _obj2ovride($dataobj-raise)] } {
926                SendCmd "dataset visible 1 $tag"
927            } else {
928                SendCmd "dataset visible 0 $tag"
929            }
930            SetObjectStyle $dataobj $comp
931        }
932    }
933    if {"" != $_first} {
934        set location [$_first hints camera]
935        if { $location != "" } {
936            array set view $location
937        }
938    }
939    foreach axis { x y z } {
940        set label [$_first hints ${axis}label]
941        if { $label != "" } {
942            SendCmd "axis name $axis $label"
943        }
944        set units [$_first hints ${axis}units]
945        if { $units != "" } {
946            SendCmd "axis units $axis $units"
947        }
948    }
949       
950    set _buffering 0;                        # Turn off buffering.
951
952    # Actually write the commands to the server socket.  If it fails, we don't
953    # care.  We're finished here.
954    blt::busy hold $itk_component(hull)
955    SendBytes $_outbuf;                       
956    blt::busy release $itk_component(hull)
957    set _outbuf "";                        # Clear the buffer.               
958}
959
960# ----------------------------------------------------------------------
961# USAGE: CurrentDatasets ?-all -visible? ?dataobjs?
962#
963# Returns a list of server IDs for the current datasets being displayed.  This
964# is normally a single ID, but it might be a list of IDs if the current data
965# object has multiple components.
966# ----------------------------------------------------------------------
967itcl::body Rappture::VtkStreamlinesViewer::CurrentDatasets {args} {
968    set flag [lindex $args 0]
969    switch -- $flag {
970        "-all" {
971            if { [llength $args] > 1 } {
972                error "CurrentDatasets: can't specify dataobj after \"-all\""
973            }
974            set dlist [get -objects]
975        }
976        "-visible" {
977            if { [llength $args] > 1 } {
978                set dlist {}
979                set args [lrange $args 1 end]
980                foreach dataobj $args {
981                    if { [info exists _obj2ovride($dataobj-raise)] } {
982                        lappend dlist $dataobj
983                    }
984                }
985            } else {
986                set dlist [get -visible]
987            }
988        }           
989        default {
990            set dlist $args
991        }
992    }
993    set rlist ""
994    foreach dataobj $dlist {
995        foreach comp [$dataobj components] {
996            set tag $dataobj-$comp
997            if { [info exists _datasets($tag)] && $_datasets($tag) } {
998                lappend rlist $tag
999            }
1000        }
1001    }
1002    return $rlist
1003}
1004
1005# ----------------------------------------------------------------------
1006# USAGE: Zoom in
1007# USAGE: Zoom out
1008# USAGE: Zoom reset
1009#
1010# Called automatically when the user clicks on one of the zoom
1011# controls for this widget.  Changes the zoom for the current view.
1012# ----------------------------------------------------------------------
1013itcl::body Rappture::VtkStreamlinesViewer::Zoom {option} {
1014    switch -- $option {
1015        "in" {
1016            set _view(zoom) [expr {$_view(zoom)*1.25}]
1017            SendCmd "camera zoom $_view(zoom)"
1018        }
1019        "out" {
1020            set _view(zoom) [expr {$_view(zoom)*0.8}]
1021            SendCmd "camera zoom $_view(zoom)"
1022        }
1023        "reset" {
1024            array set _view {
1025                qw      1
1026                qx      0
1027                qy      0
1028                qz      0
1029                zoom    1.0
1030                xpan   0
1031                ypan   0
1032            }
1033            SendCmd "camera reset all"
1034            if { $_first != "" } {
1035                set location [$_first hints camera]
1036                if { $location != "" } {
1037                    array set _view $location
1038                }
1039            }
1040            set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1041            $_arcball quaternion $q
1042            DoRotate
1043        }
1044    }
1045}
1046
1047itcl::body Rappture::VtkStreamlinesViewer::PanCamera {} {
1048    set x $_view(xpan)
1049    set y $_view(ypan)
1050    SendCmd "camera pan $x $y"
1051}
1052
1053
1054# ----------------------------------------------------------------------
1055# USAGE: Rotate click <x> <y>
1056# USAGE: Rotate drag <x> <y>
1057# USAGE: Rotate release <x> <y>
1058#
1059# Called automatically when the user clicks/drags/releases in the
1060# plot area.  Moves the plot according to the user's actions.
1061# ----------------------------------------------------------------------
1062itcl::body Rappture::VtkStreamlinesViewer::Rotate {option x y} {
1063    switch -- $option {
1064        "click" {
1065            $itk_component(view) configure -cursor fleur
1066            set _click(x) $x
1067            set _click(y) $y
1068        }
1069        "drag" {
1070            if {[array size _click] == 0} {
1071                Rotate click $x $y
1072            } else {
1073                set w [winfo width $itk_component(view)]
1074                set h [winfo height $itk_component(view)]
1075                if {$w <= 0 || $h <= 0} {
1076                    return
1077                }
1078
1079                if {[catch {
1080                    # this fails sometimes for no apparent reason
1081                    set dx [expr {double($x-$_click(x))/$w}]
1082                    set dy [expr {double($y-$_click(y))/$h}]
1083                }]} {
1084                    return
1085                }
1086                if { $dx == 0 && $dy == 0 } {
1087                    return
1088                }
1089                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1090                EventuallyRotate $q
1091                set _click(x) $x
1092                set _click(y) $y
1093            }
1094        }
1095        "release" {
1096            Rotate drag $x $y
1097            $itk_component(view) configure -cursor ""
1098            catch {unset _click}
1099        }
1100        default {
1101            error "bad option \"$option\": should be click, drag, release"
1102        }
1103    }
1104}
1105
1106itcl::body Rappture::VtkStreamlinesViewer::Pick {x y} {
1107    foreach tag [CurrentDatasets -visible] {
1108        SendCmd "dataset getscalar pixel $x $y $tag"
1109    }
1110}
1111
1112# ----------------------------------------------------------------------
1113# USAGE: $this Pan click x y
1114#        $this Pan drag x y
1115#        $this Pan release x y
1116#
1117# Called automatically when the user clicks on one of the zoom
1118# controls for this widget.  Changes the zoom for the current view.
1119# ----------------------------------------------------------------------
1120itcl::body Rappture::VtkStreamlinesViewer::Pan {option x y} {
1121    switch -- $option {
1122        "set" {
1123            set w [winfo width $itk_component(view)]
1124            set h [winfo height $itk_component(view)]
1125            set x [expr $x / double($w)]
1126            set y [expr $y / double($h)]
1127            set _view(xpan) [expr $_view(xpan) + $x]
1128            set _view(ypan) [expr $_view(ypan) + $y]
1129            PanCamera
1130            return
1131        }
1132        "click" {
1133            set _click(x) $x
1134            set _click(y) $y
1135            $itk_component(view) configure -cursor hand1
1136        }
1137        "drag" {
1138            if { ![info exists _click(x)] } {
1139                set _click(x) $x
1140            }
1141            if { ![info exists _click(y)] } {
1142                set _click(y) $y
1143            }
1144            set w [winfo width $itk_component(view)]
1145            set h [winfo height $itk_component(view)]
1146            set dx [expr ($_click(x) - $x)/double($w)]
1147            set dy [expr ($_click(y) - $y)/double($h)]
1148            set _click(x) $x
1149            set _click(y) $y
1150            set _view(xpan) [expr $_view(xpan) - $dx]
1151            set _view(ypan) [expr $_view(ypan) - $dy]
1152            PanCamera
1153        }
1154        "release" {
1155            Pan drag $x $y
1156            $itk_component(view) configure -cursor ""
1157        }
1158        default {
1159            error "unknown option \"$option\": should set, click, drag, or release"
1160        }
1161    }
1162}
1163
1164# ----------------------------------------------------------------------
1165# USAGE: FixSettings <what> ?<value>?
1166#
1167# Used internally to update rendering settings whenever parameters
1168# change in the popup settings panel.  Sends the new settings off
1169# to the back end.
1170# ----------------------------------------------------------------------
1171itcl::body Rappture::VtkStreamlinesViewer::FixSettings { args } {
1172    foreach setting $args {
1173        AdjustSetting $setting
1174    }
1175}
1176
1177#
1178# AdjustSetting --
1179#
1180#       Changes/updates a specific setting in the widget.  There are
1181#       usually user-setable option.  Commands are sent to the render
1182#       server.
1183#
1184itcl::body Rappture::VtkStreamlinesViewer::AdjustSetting {what {value ""}} {
1185    if { ![isconnected] } {
1186        return
1187    }
1188    switch -- $what {
1189        "volume-opacity" {
1190            set val $_volume(opacity)
1191            set sval [expr { 0.01 * double($val) }]
1192            foreach dataset [CurrentDatasets -visible $_first] {
1193                SendCmd "polydata opacity $sval $dataset"
1194            }
1195        }
1196        "volume-wireframe" {
1197            set bool $_volume(wireframe)
1198            foreach dataset [CurrentDatasets -visible $_first] {
1199                SendCmd "polydata wireframe $bool $dataset"
1200            }
1201        }
1202        "volume-visible" {
1203            set bool $_volume(visible)
1204            foreach dataset [CurrentDatasets -visible $_first] {
1205                SendCmd "polydata visible $bool $dataset"
1206            }
1207        }
1208        "volume-lighting" {
1209            set bool $_volume(lighting)
1210            foreach dataset [CurrentDatasets -visible $_first] {
1211                SendCmd "polydata lighting $bool $dataset"
1212            }
1213        }
1214        "volume-edges" {
1215            set bool $_volume(edges)
1216            foreach dataset [CurrentDatasets -visible $_first] {
1217                SendCmd "polydata edges $bool $dataset"
1218            }
1219        }
1220        "axis-visible" {
1221            set bool $_axis(visible)
1222            SendCmd "axis visible all $bool"
1223        }
1224        "axis-labels" {
1225            set bool $_axis(labels)
1226            SendCmd "axis labels all $bool"
1227        }
1228        "axis-xgrid" {
1229            set bool $_axis(xgrid)
1230            SendCmd "axis grid x $bool"
1231        }
1232        "axis-ygrid" {
1233            set bool $_axis(ygrid)
1234            SendCmd "axis grid y $bool"
1235        }
1236        "axis-zgrid" {
1237            set bool $_axis(zgrid)
1238            SendCmd "axis grid z $bool"
1239        }
1240        "axis-mode" {
1241            set mode [$itk_component(axismode) value]
1242            set mode [$itk_component(axismode) translate $mode]
1243            SendCmd "axis flymode $mode"
1244        }
1245        "axis-xcutaway" - "axis-ycutaway" - "axis-zcutaway" {
1246            set axis [string range $what 5 5]
1247            set bool $_axis(${axis}cutaway)
1248            if { $bool } {
1249                set pos [expr $_axis(${axis}position) * 0.01]
1250                set dir $_axis(${axis}direction)
1251                $itk_component(${axis}CutScale) configure -state normal \
1252                    -troughcolor white
1253                SendCmd "renderer clipplane $axis $pos $dir"
1254            } else {
1255                $itk_component(${axis}CutScale) configure -state disabled \
1256                    -troughcolor grey82
1257                SendCmd "renderer clipplane $axis 1 -1"
1258            }
1259        }
1260        "axis-xposition" - "axis-yposition" - "axis-zposition" -
1261        "axis-xdirection" - "axis-ydirection" - "axis-zdirection" {
1262            set axis [string range $what 5 5]
1263            #set dir $_axis(${axis}direction)
1264            set pos [expr $_axis(${axis}position) * 0.01]
1265            SendCmd "renderer clipplane ${axis} $pos -1"
1266        }
1267        "streamlines-seeds" {
1268            set bool $_streamlines(seeds)
1269            foreach dataset [CurrentDatasets -visible $_first] {
1270                SendCmd "streamlines seed visible $bool $dataset"
1271            }
1272        }
1273        "streamlines-visible" {
1274            set bool $_streamlines(visible)
1275            foreach dataset [CurrentDatasets -visible $_first] {
1276                SendCmd "streamlines visible $bool $dataset"
1277            }
1278        }
1279        "streamlines-mode" {
1280            set mode [$itk_component(streammode) value]
1281            foreach dataset [CurrentDatasets -visible $_first] {
1282                switch -- $mode {
1283                    "lines" {
1284                        SendCmd "streamlines lines $dataset"
1285                    }
1286                    "ribbons" {
1287                        SendCmd "streamlines ribbons 1 0 $dataset"
1288                    }
1289                    "tubes" {
1290                        SendCmd "streamlines tubes 5 1 $dataset"
1291                    }
1292                }
1293            }
1294        }
1295        "streamlines-opacity" {
1296            set val $_streamlines(opacity)
1297            set sval [expr { 0.01 * double($val) }]
1298            foreach dataset [CurrentDatasets -visible $_first] {
1299                SendCmd "streamlines opacity $sval $dataset"
1300            }
1301        }
1302        default {
1303            error "don't know how to fix $what"
1304        }
1305    }
1306}
1307
1308#
1309# RequestLegend --
1310#
1311#       Request a new legend from the server.  The size of the legend
1312#       is determined from the height of the canvas.  It will be rotated
1313#       to be vertical when drawn.
1314#
1315itcl::body Rappture::VtkStreamlinesViewer::RequestLegend {} {
1316    #puts stderr "RequestLegend _first=$_first"
1317    #puts stderr "RequestLegend width=$_width height=$_height"
1318    set font "Arial 8"
1319    set lineht [font metrics $font -linespace]
1320    set c $itk_component(legend)
1321    set w 12
1322    set h [expr {$_height - 2 * ($lineht + 2)}]
1323    if { $h < 1} {
1324        return
1325    }
1326    # Set the legend on the first streamlines dataset.
1327    foreach dataset [CurrentDatasets -visible] {
1328        foreach {dataobj comp} [split $dataset -] break
1329        if { [info exists _dataset2style($dataset)] } {
1330            #puts stderr "RequestLegend w=$w h=$h"
1331            SendCmd "legend $_dataset2style($dataset) vmag {} $w $h 0"
1332            break;
1333        }
1334    }
1335}
1336
1337#
1338# SetColormap --
1339#
1340itcl::body Rappture::VtkStreamlinesViewer::SetColormap { dataobj comp } {
1341    array set style {
1342        -color rainbow
1343        -levels 6
1344        -opacity 1.0
1345    }
1346    set tag $dataobj-$comp
1347    array set style [$dataobj style $comp]
1348    set colormap "$style(-color):$style(-levels):$style(-opacity)"
1349    if { [info exists _colormaps($colormap)] } {
1350        puts stderr "Colormap $colormap already built"
1351        return $colormap
1352    }
1353    if { ![info exists _dataset2style($tag)] } {
1354        set _dataset2style($tag) $colormap
1355        lappend _style2datasets($colormap) $tag
1356    }
1357    if { ![info exists _colormaps($colormap)] } {
1358        # Build the pseudo colormap if it doesn't exist.
1359        BuildColormap $colormap $dataobj $comp
1360        set _colormaps($colormap) 1
1361    }
1362    SendCmd "streamlines colormap $colormap $tag"
1363    return $colormap
1364}
1365
1366#
1367# BuildColormap --
1368#
1369itcl::body Rappture::VtkStreamlinesViewer::BuildColormap { colormap dataobj comp } {
1370    array set style {
1371        -color rainbow
1372        -levels 6
1373        -opacity 1.0
1374    }
1375    array set style [$dataobj style $comp]
1376    if {$style(-color) == "rainbow"} {
1377        set style(-color) "white:yellow:green:cyan:blue:magenta"
1378    }
1379    set clist [split $style(-color) :]
1380    set cmap {}
1381    for {set i 0} {$i < [llength $clist]} {incr i} {
1382        set x [expr {double($i)/([llength $clist]-1)}]
1383        set color [lindex $clist $i]
1384        append cmap "$x [Color2RGB $color] "
1385    }
1386    if { [llength $cmap] == 0 } {
1387        set cmap "0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0"
1388    }
1389    if { ![info exists _volume(opacity)] } {
1390        set _volume(opacity) $style(-opacity)
1391    }
1392    set max $_volume(opacity)
1393
1394    set wmap "0.0 1.0 1.0 1.0"
1395    SendCmd "colormap add $colormap { $cmap } { $wmap }"
1396}
1397
1398# ----------------------------------------------------------------------
1399# CONFIGURATION OPTION: -plotbackground
1400# ----------------------------------------------------------------------
1401itcl::configbody Rappture::VtkStreamlinesViewer::plotbackground {
1402    if { [isconnected] } {
1403        foreach {r g b} [Color2RGB $itk_option(-plotbackground)] break
1404        SendCmd "screen bgcolor $r $g $b"
1405    }
1406}
1407
1408# ----------------------------------------------------------------------
1409# CONFIGURATION OPTION: -plotforeground
1410# ----------------------------------------------------------------------
1411itcl::configbody Rappture::VtkStreamlinesViewer::plotforeground {
1412    if { [isconnected] } {
1413        foreach {r g b} [Color2RGB $itk_option(-plotforeground)] break
1414        #fix this!
1415        #SendCmd "color background $r $g $b"
1416    }
1417}
1418
1419itcl::body Rappture::VtkStreamlinesViewer::limits { dataobj } {
1420
1421    array unset _limits $dataobj-*
1422    foreach comp [$dataobj components] {
1423        set tag $dataobj-$comp
1424        if { ![info exists _limits($tag)] } {
1425            set data [$dataobj blob $comp]
1426            set tmpfile file[pid].vtk
1427            set f [open "$tmpfile" "w"]
1428            puts $f $data
1429            close $f
1430            set reader [vtkDataSetReader $tag-xvtkDataSetReader]
1431            $reader SetFileName $tmpfile
1432            $reader ReadAllNormalsOn
1433            $reader ReadAllScalarsOn
1434            $reader ReadAllVectorsOn
1435            $reader ReadAllFieldsOn
1436            $reader Update
1437            set output [$reader GetOutput]
1438            set _limits($tag) [$output GetBounds]
1439            set pointData [$output GetPointData]
1440            puts stderr "\#scalars=[$reader GetNumberOfScalarsInFile]"
1441            puts stderr "\#vectors=[$reader GetNumberOfVectorsInFile]"
1442            puts stderr "\#tensors=[$reader GetNumberOfTensorsInFile]"
1443            puts stderr "\#normals=[$reader GetNumberOfNormalsInFile]"
1444            puts stderr "\#fielddata=[$reader GetNumberOfFieldDataInFile]"
1445            puts stderr "fielddataname=[$reader GetFieldDataNameInFile 0]"
1446            set fieldData [$output GetFieldData]
1447            set pointData [$output GetPointData]
1448            puts stderr "field \#arrays=[$fieldData GetNumberOfArrays]"
1449            puts stderr "point \#arrays=[$pointData GetNumberOfArrays]"
1450            puts stderr "field \#components=[$fieldData GetNumberOfComponents]"
1451            puts stderr "point \#components=[$pointData GetNumberOfComponents]"
1452            puts stderr "field \#tuples=[$fieldData GetNumberOfTuples]"
1453            puts stderr "point \#tuples=[$pointData GetNumberOfTuples]"
1454            puts stderr "point \#scalars=[$pointData GetScalars]"
1455            puts stderr vectors=[$pointData GetVectors]
1456            rename $output ""
1457            rename $reader ""
1458            file delete $tmpfile
1459        }
1460        foreach { xMin xMax yMin yMax zMin zMax} $_limits($tag) break
1461        if {![info exists limits(xmin)] || $limits(xmin) > $xMin} {
1462            set limits(xmin) $xMin
1463        }
1464        if {![info exists limits(xmax)] || $limits(xmax) < $xMax} {
1465            set limits(xmax) $xMax
1466        }
1467        if {![info exists limits(ymin)] || $limits(ymin) > $yMin} {
1468            set limits(ymin) $xMin
1469        }
1470        if {![info exists limits(ymax)] || $limits(ymax) < $yMax} {
1471            set limits(ymax) $yMax
1472        }
1473        if {![info exists limits(zmin)] || $limits(zmin) > $zMin} {
1474            set limits(zmin) $zMin
1475        }
1476        if {![info exists limits(zmax)] || $limits(zmax) < $zMax} {
1477            set limits(zmax) $zMax
1478        }
1479    }
1480    return [array get limits]
1481}
1482
1483itcl::body Rappture::VtkStreamlinesViewer::BuildVolumeTab {} {
1484
1485    set fg [option get $itk_component(hull) font Font]
1486    #set bfg [option get $itk_component(hull) boldFont Font]
1487
1488    set inner [$itk_component(main) insert end \
1489        -title "Volume Settings" \
1490        -icon [Rappture::icon volume-on]]
1491    $inner configure -borderwidth 4
1492
1493    checkbutton $inner.volume \
1494        -text "Show Volume" \
1495        -variable [itcl::scope _volume(visible)] \
1496        -command [itcl::code $this AdjustSetting volume-visible] \
1497        -font "Arial 9"
1498
1499    checkbutton $inner.wireframe \
1500        -text "Show Wireframe" \
1501        -variable [itcl::scope _volume(wireframe)] \
1502        -command [itcl::code $this AdjustSetting volume-wireframe] \
1503        -font "Arial 9"
1504
1505    checkbutton $inner.lighting \
1506        -text "Enable Lighting" \
1507        -variable [itcl::scope _volume(lighting)] \
1508        -command [itcl::code $this AdjustSetting volume-lighting] \
1509        -font "Arial 9"
1510
1511    checkbutton $inner.edges \
1512        -text "Show Edges" \
1513        -variable [itcl::scope _volume(edges)] \
1514        -command [itcl::code $this AdjustSetting volume-edges] \
1515        -font "Arial 9"
1516
1517    label $inner.opacity_l -text "Opacity" -font "Arial 9"
1518    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1519        -variable [itcl::scope _volume(opacity)] \
1520        -width 10 \
1521        -showvalue off \
1522        -command [itcl::code $this AdjustSetting volume-opacity]
1523
1524    blt::table $inner \
1525        0,0 $inner.volume    -anchor w -pady 2 \
1526        1,0 $inner.wireframe -anchor w -pady 2 \
1527        2,0 $inner.lighting  -anchor w -pady 2 \
1528        3,0 $inner.edges     -anchor w -pady 2 \
1529        4,0 $inner.opacity_l -anchor w -pady 2 \
1530        5,0 $inner.opacity   -fill x   -pady 2
1531
1532    blt::table configure $inner r* c* -resize none
1533    blt::table configure $inner r6 c1 -resize expand
1534}
1535
1536
1537itcl::body Rappture::VtkStreamlinesViewer::BuildStreamsTab {} {
1538
1539    set fg [option get $itk_component(hull) font Font]
1540    #set bfg [option get $itk_component(hull) boldFont Font]
1541
1542    set inner [$itk_component(main) insert end \
1543        -title "Streams Settings" \
1544        -icon [Rappture::icon stream]]
1545    $inner configure -borderwidth 4
1546
1547    checkbutton $inner.streamlines \
1548        -text "Show Streamlines" \
1549        -variable [itcl::scope _streamlines(visible)] \
1550        -command [itcl::code $this AdjustSetting streamlines-visible] \
1551        -font "Arial 9"
1552
1553    checkbutton $inner.seeds \
1554        -text "Show Seeds" \
1555        -variable [itcl::scope _streamlines(seeds)] \
1556        -command [itcl::code $this AdjustSetting streamlines-seeds] \
1557        -font "Arial 9"
1558
1559    label $inner.mode_l -text "Mode" -font "Arial 9"
1560    itk_component add streammode {
1561        Rappture::Combobox $inner.mode -width 10 -editable no
1562    }
1563    $inner.mode choices insert end \
1564        "lines"    "lines" \
1565        "ribbons"   "ribbons" \
1566        "tubes"     "tubes"
1567    $itk_component(streammode) value "lines"
1568    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting streamlines-mode]
1569
1570    label $inner.opacity_l -text "Opacity" -font "Arial 9"
1571    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1572        -variable [itcl::scope _streamlines(opacity)] \
1573        -width 10 \
1574        -showvalue off \
1575        -command [itcl::code $this AdjustSetting streamlines-opacity]
1576
1577    blt::table $inner \
1578        0,0 $inner.streamlines -anchor w -pady 2 -cspan 2 \
1579        1,0 $inner.seeds       -anchor w -pady 2 -cspan 2 \
1580        2,0 $inner.mode_l      -anchor w -pady 2  \
1581        2,1 $inner.mode        -anchor w -pady 2  \
1582        3,0 $inner.opacity_l   -anchor w -pady 2  \
1583        4,0 $inner.opacity     -fill x   -pady 2 -cspan 2
1584
1585    blt::table configure $inner r* c* -resize none
1586    blt::table configure $inner r5 c1 c2 -resize expand
1587}
1588
1589itcl::body Rappture::VtkStreamlinesViewer::BuildAxisTab {} {
1590
1591    set fg [option get $itk_component(hull) font Font]
1592    #set bfg [option get $itk_component(hull) boldFont Font]
1593
1594    set inner [$itk_component(main) insert end \
1595        -title "Axis Settings" \
1596        -icon [Rappture::icon axis1]]
1597    $inner configure -borderwidth 4
1598
1599    checkbutton $inner.visible \
1600        -text "Show Axes" \
1601        -variable [itcl::scope _axis(visible)] \
1602        -command [itcl::code $this AdjustSetting axis-visible] \
1603        -font "Arial 9"
1604
1605    checkbutton $inner.labels \
1606        -text "Show Axis Labels" \
1607        -variable [itcl::scope _axis(labels)] \
1608        -command [itcl::code $this AdjustSetting axis-labels] \
1609        -font "Arial 9"
1610
1611    checkbutton $inner.gridx \
1612        -text "Show X Grid" \
1613        -variable [itcl::scope _axis(xgrid)] \
1614        -command [itcl::code $this AdjustSetting axis-xgrid] \
1615        -font "Arial 9"
1616    checkbutton $inner.gridy \
1617        -text "Show Y Grid" \
1618        -variable [itcl::scope _axis(ygrid)] \
1619        -command [itcl::code $this AdjustSetting axis-ygrid] \
1620        -font "Arial 9"
1621    checkbutton $inner.gridz \
1622        -text "Show Z Grid" \
1623        -variable [itcl::scope _axis(zgrid)] \
1624        -command [itcl::code $this AdjustSetting axis-zgrid] \
1625        -font "Arial 9"
1626
1627    label $inner.mode_l -text "Mode" -font "Arial 9"
1628
1629    itk_component add axismode {
1630        Rappture::Combobox $inner.mode -width 10 -editable no
1631    }
1632    $inner.mode choices insert end \
1633        "static_triad"    "static" \
1634        "closest_triad"   "closest" \
1635        "furthest_triad"  "furthest" \
1636        "outer_edges"     "outer"         
1637    $itk_component(axismode) value "static"
1638    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting axis-mode]
1639
1640    blt::table $inner \
1641        0,0 $inner.visible -anchor w -cspan 2 \
1642        1,0 $inner.labels  -anchor w -cspan 2 \
1643        2,0 $inner.gridx   -anchor w -cspan 2 \
1644        3,0 $inner.gridy   -anchor w -cspan 2 \
1645        4,0 $inner.gridz   -anchor w -cspan 2 \
1646        5,0 $inner.mode_l  -anchor w -cspan 2 -padx { 2 0 } \
1647        6,0 $inner.mode    -fill x   -cspan 2
1648
1649    blt::table configure $inner r* c* -resize none
1650    blt::table configure $inner r7 c1 -resize expand
1651}
1652
1653
1654itcl::body Rappture::VtkStreamlinesViewer::BuildCameraTab {} {
1655    set inner [$itk_component(main) insert end \
1656        -title "Camera Settings" \
1657        -icon [Rappture::icon camera]]
1658    $inner configure -borderwidth 4
1659
1660    set labels { qx qy qz qw xpan ypan zoom }
1661    set row 0
1662    foreach tag $labels {
1663        label $inner.${tag}label -text $tag -font "Arial 9"
1664        entry $inner.${tag} -font "Arial 9"  -bg white \
1665            -textvariable [itcl::scope _view($tag)]
1666        bind $inner.${tag} <KeyPress-Return> \
1667            [itcl::code $this camera set ${tag}]
1668        blt::table $inner \
1669            $row,0 $inner.${tag}label -anchor e -pady 2 \
1670            $row,1 $inner.${tag} -anchor w -pady 2
1671        blt::table configure $inner r$row -resize none
1672        incr row
1673    }
1674    checkbutton $inner.ortho \
1675        -text "Orthographic Projection" \
1676        -variable [itcl::scope _view(ortho)] \
1677        -command [itcl::code $this camera set ortho] \
1678        -font "Arial 9"
1679    blt::table $inner \
1680            $row,0 $inner.ortho -columnspan 2 -anchor w -pady 2
1681    blt::table configure $inner r$row -resize none
1682    incr row
1683
1684    blt::table configure $inner c0 c1 -resize none
1685    blt::table configure $inner c2 -resize expand
1686    blt::table configure $inner r$row -resize expand
1687}
1688
1689itcl::body Rappture::VtkStreamlinesViewer::BuildCutawayTab {} {
1690
1691    set fg [option get $itk_component(hull) font Font]
1692   
1693    set inner [$itk_component(main) insert end \
1694        -title "Cutaway Along Axis" \
1695        -icon [Rappture::icon cutbutton]]
1696
1697    $inner configure -borderwidth 4
1698
1699    # X-value slicer...
1700    itk_component add xCutButton {
1701        Rappture::PushButton $inner.xbutton \
1702            -onimage [Rappture::icon x-cutplane] \
1703            -offimage [Rappture::icon x-cutplane] \
1704            -command [itcl::code $this AdjustSetting axis-xcutaway] \
1705            -variable [itcl::scope _axis(xcutaway)]
1706    }
1707    Rappture::Tooltip::for $itk_component(xCutButton) \
1708        "Toggle the X-axis cutaway on/off"
1709
1710    itk_component add xCutScale {
1711        ::scale $inner.xval -from 100 -to 1 \
1712            -width 10 -orient vertical -showvalue yes \
1713            -borderwidth 1 -highlightthickness 0 \
1714            -command [itcl::code $this Slice move x] \
1715            -variable [itcl::scope _axis(xposition)]
1716    } {
1717        usual
1718        ignore -borderwidth -highlightthickness
1719    }
1720    # Set the default cutaway value before disabling the scale.
1721    $itk_component(xCutScale) set 100
1722    $itk_component(xCutScale) configure -state disabled
1723    Rappture::Tooltip::for $itk_component(xCutScale) \
1724        "@[itcl::code $this Slice tooltip x]"
1725
1726    itk_component add xDirButton {
1727        Rappture::PushButton $inner.xdir \
1728            -onimage [Rappture::icon arrow-down] \
1729            -onvalue -1 \
1730            -offimage [Rappture::icon arrow-up] \
1731            -offvalue 1 \
1732            -command [itcl::code $this AdjustSetting axis-xdirection] \
1733            -variable [itcl::scope _axis(xdirection)]
1734    }
1735    set _axis(xdirection) -1
1736    Rappture::Tooltip::for $itk_component(xDirButton) \
1737        "Toggle the direction of the X-axis cutaway"
1738
1739    # Y-value slicer...
1740    itk_component add yCutButton {
1741        Rappture::PushButton $inner.ybutton \
1742            -onimage [Rappture::icon y-cutplane] \
1743            -offimage [Rappture::icon y-cutplane] \
1744            -command [itcl::code $this AdjustSetting axis-ycutaway] \
1745            -variable [itcl::scope _axis(ycutaway)]
1746    }
1747    Rappture::Tooltip::for $itk_component(yCutButton) \
1748        "Toggle the Y-axis cutaway on/off"
1749
1750    itk_component add yCutScale {
1751        ::scale $inner.yval -from 100 -to 1 \
1752            -width 10 -orient vertical -showvalue yes \
1753            -borderwidth 1 -highlightthickness 0 \
1754            -command [itcl::code $this Slice move y] \
1755            -variable [itcl::scope _axis(yposition)]
1756    } {
1757        usual
1758        ignore -borderwidth -highlightthickness
1759    }
1760    Rappture::Tooltip::for $itk_component(yCutScale) \
1761        "@[itcl::code $this Slice tooltip y]"
1762    # Set the default cutaway value before disabling the scale.
1763    $itk_component(yCutScale) set 100
1764    $itk_component(yCutScale) configure -state disabled
1765
1766    itk_component add yDirButton {
1767        Rappture::PushButton $inner.ydir \
1768            -onimage [Rappture::icon arrow-down] \
1769            -onvalue -1 \
1770            -offimage [Rappture::icon arrow-up] \
1771            -offvalue 1 \
1772            -command [itcl::code $this AdjustSetting axis-ydirection] \
1773            -variable [itcl::scope _axis(ydirection)]
1774    }
1775    Rappture::Tooltip::for $itk_component(yDirButton) \
1776        "Toggle the direction of the Y-axis cutaway"
1777    set _axis(ydirection) -1
1778
1779    # Z-value slicer...
1780    itk_component add zCutButton {
1781        Rappture::PushButton $inner.zbutton \
1782            -onimage [Rappture::icon z-cutplane] \
1783            -offimage [Rappture::icon z-cutplane] \
1784            -command [itcl::code $this AdjustSetting axis-zcutaway] \
1785            -variable [itcl::scope _axis(zcutaway)]
1786    }
1787    Rappture::Tooltip::for $itk_component(zCutButton) \
1788        "Toggle the Z-axis cutaway on/off"
1789
1790    itk_component add zCutScale {
1791        ::scale $inner.zval -from 100 -to 1 \
1792            -width 10 -orient vertical -showvalue yes \
1793            -borderwidth 1 -highlightthickness 0 \
1794            -command [itcl::code $this Slice move z] \
1795            -variable [itcl::scope _axis(zposition)]
1796    } {
1797        usual
1798        ignore -borderwidth -highlightthickness
1799    }
1800    $itk_component(zCutScale) set 100
1801    $itk_component(zCutScale) configure -state disabled
1802    #$itk_component(zCutScale) configure -state disabled
1803    Rappture::Tooltip::for $itk_component(zCutScale) \
1804        "@[itcl::code $this Slice tooltip z]"
1805
1806    itk_component add zDirButton {
1807        Rappture::PushButton $inner.zdir \
1808            -onimage [Rappture::icon arrow-down] \
1809            -onvalue -1 \
1810            -offimage [Rappture::icon arrow-up] \
1811            -offvalue 1 \
1812            -command [itcl::code $this AdjustSetting axis-zdirection] \
1813            -variable [itcl::scope _axis(zdirection)]
1814    }
1815    set _axis(zdirection) -1
1816    Rappture::Tooltip::for $itk_component(zDirButton) \
1817        "Toggle the direction of the Z-axis cutaway"
1818
1819    blt::table $inner \
1820        0,0 $itk_component(xCutButton)  -anchor e -padx 2 -pady 2 \
1821        1,0 $itk_component(xCutScale)   -fill y \
1822        0,1 $itk_component(yCutButton)  -anchor e -padx 2 -pady 2 \
1823        1,1 $itk_component(yCutScale)   -fill y \
1824        0,2 $itk_component(zCutButton)  -anchor e -padx 2 -pady 2 \
1825        1,2 $itk_component(zCutScale)   -fill y \
1826
1827    blt::table configure $inner r* c* -resize none
1828    blt::table configure $inner r1 c3 -resize expand
1829}
1830
1831
1832
1833#
1834#  camera --
1835#
1836itcl::body Rappture::VtkStreamlinesViewer::camera {option args} {
1837    switch -- $option {
1838        "show" {
1839            puts [array get _view]
1840        }
1841        "set" {
1842            set who [lindex $args 0]
1843            set x $_view($who)
1844            set code [catch { string is double $x } result]
1845            if { $code != 0 || !$result } {
1846                return
1847            }
1848            switch -- $who {
1849                "ortho" {
1850                    if {$_view(ortho)} {
1851                        SendCmd "camera mode ortho"
1852                    } else {
1853                        SendCmd "camera mode persp"
1854                    }
1855                }
1856                "xpan" - "ypan" {
1857                    PanCamera
1858                }
1859                "qx" - "qy" - "qz" - "qw" {
1860                    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1861                    $_arcball quaternion $q
1862                    EventuallyRotate $q
1863                }
1864                "zoom" {
1865                    SendCmd "camera zoom $_view(zoom)"
1866                }
1867            }
1868        }
1869    }
1870}
1871
1872itcl::body Rappture::VtkStreamlinesViewer::ConvertToVtkData { dataobj comp } {
1873    foreach { x1 x2 xN y1 y2 yN } [$dataobj mesh $comp] break
1874    set values [$dataobj values $comp]
1875    append out "# vtk DataFile Version 2.0 \n"
1876    append out "Test data \n"
1877    append out "ASCII \n"
1878    append out "DATASET STRUCTURED_POINTS \n"
1879    append out "DIMENSIONS $xN $yN 1 \n"
1880    append out "ORIGIN 0 0 0 \n"
1881    append out "SPACING 1 1 1 \n"
1882    append out "POINT_DATA [expr $xN * $yN] \n"
1883    append out "SCALARS field float 1 \n"
1884    append out "LOOKUP_TABLE default \n"
1885    append out [join $values "\n"]
1886    append out "\n"
1887    return $out
1888}
1889
1890
1891itcl::body Rappture::VtkStreamlinesViewer::GetVtkData { args } {
1892    set bytes ""
1893    foreach dataobj [get] {
1894        foreach comp [$dataobj components] {
1895            set tag $dataobj-$comp
1896            #set contents [ConvertToVtkData $dataobj $comp]
1897            set contents [$dataobj blob $comp]
1898            append bytes "$contents\n\n"
1899        }
1900    }
1901    return [list .txt $bytes]
1902}
1903
1904itcl::body Rappture::VtkStreamlinesViewer::GetImage { args } {
1905    if { [image width $_image(download)] > 0 &&
1906         [image height $_image(download)] > 0 } {
1907        set bytes [$_image(download) data -format "jpeg -quality 100"]
1908        set bytes [Rappture::encoding::decode -as b64 $bytes]
1909        return [list .jpg $bytes]
1910    }
1911    return ""
1912}
1913
1914itcl::body Rappture::VtkStreamlinesViewer::BuildDownloadPopup { popup command } {
1915    Rappture::Balloon $popup \
1916        -title "[Rappture::filexfer::label downloadWord] as..."
1917    set inner [$popup component inner]
1918    label $inner.summary -text "" -anchor w
1919    radiobutton $inner.vtk_button -text "VTK data file" \
1920        -variable [itcl::scope _downloadPopup(format)] \
1921        -font "Helvetica 9 " \
1922        -value vtk 
1923    Rappture::Tooltip::for $inner.vtk_button "Save as VTK data file."
1924    radiobutton $inner.image_button -text "Image File" \
1925        -variable [itcl::scope _downloadPopup(format)] \
1926        -value image
1927    Rappture::Tooltip::for $inner.image_button \
1928        "Save as digital image."
1929
1930    button $inner.ok -text "Save" \
1931        -highlightthickness 0 -pady 2 -padx 3 \
1932        -command $command \
1933        -compound left \
1934        -image [Rappture::icon download]
1935
1936    button $inner.cancel -text "Cancel" \
1937        -highlightthickness 0 -pady 2 -padx 3 \
1938        -command [list $popup deactivate] \
1939        -compound left \
1940        -image [Rappture::icon cancel]
1941
1942    blt::table $inner \
1943        0,0 $inner.summary -cspan 2  \
1944        1,0 $inner.vtk_button -anchor w -cspan 2 -padx { 4 0 } \
1945        2,0 $inner.image_button -anchor w -cspan 2 -padx { 4 0 } \
1946        4,1 $inner.cancel -width .9i -fill y \
1947        4,0 $inner.ok -padx 2 -width .9i -fill y
1948    blt::table configure $inner r3 -height 4
1949    blt::table configure $inner r4 -pady 4
1950    raise $inner.image_button
1951    $inner.vtk_button invoke
1952    return $inner
1953}
1954
1955itcl::body Rappture::VtkStreamlinesViewer::SetObjectStyle { dataobj comp } {
1956    # Parse style string.
1957    set tag $dataobj-$comp
1958    set style [$dataobj style $comp]
1959    #puts stderr "style $dataobj-$comp \"$style\""
1960    if { $dataobj != $_first } {
1961        set settings(-wireframe) 1
1962    }
1963    array set settings {
1964        -color \#808080
1965        -edges 0
1966        -edgecolor black
1967        -linewidth 1.0
1968        -opacity 0.4
1969        -wireframe 0
1970        -lighting 1
1971        -seeds 1
1972        -seedcolor white
1973        -visible 1
1974    }
1975    array set settings $style
1976    SendCmd "streamlines add $tag"
1977    SendCmd "streamlines seed visible off"
1978    set seeds [$dataobj hints seeds]
1979    if { $seeds != "" && ![info exists _seeds($dataobj)] } {
1980        set length [string length $seeds]
1981        set stag $dataobj-seeds
1982        SendCmd "dataset add $stag data follows $length"
1983        SendCmd "$seeds"
1984        SendCmd "dataset visible 0 $stag"
1985        SendCmd "streamlines seed random 1000 $stag"
1986        set _seeds($dataobj) 1
1987    }
1988    SendCmd "polydata add $tag"
1989    SendCmd "polydata edges $settings(-edges) $tag"
1990    set _volume(edges) $settings(-edges)
1991    SendCmd "polydata color [Color2RGB $settings(-color)] $tag"
1992    SendCmd "polydata lighting $settings(-lighting) $tag"
1993    set _volume(lighting) $settings(-lighting)
1994    SendCmd "polydata linecolor [Color2RGB $settings(-edgecolor)] $tag"
1995    SendCmd "polydata linewidth $settings(-linewidth) $tag"
1996    SendCmd "polydata opacity $settings(-opacity) $tag"
1997    set _volume(opacity) $settings(-opacity)
1998    SendCmd "polydata wireframe $settings(-wireframe) $tag"
1999    set _volume(wireframe) $settings(-wireframe)
2000    set _volume(opacity) [expr $settings(-opacity) * 100.0]
2001    SetColormap $dataobj $comp
2002}
2003
2004itcl::body Rappture::VtkStreamlinesViewer::IsValidObject { dataobj } {
2005    if {[catch {$dataobj isa Rappture::Field} valid] != 0 || !$valid} {
2006        return 0
2007    }
2008    return 1
2009}
2010
2011# ----------------------------------------------------------------------
2012# USAGE: ReceiveLegend <colormap> <title> <vmin> <vmax> <size>
2013#
2014# Invoked automatically whenever the "legend" command comes in from
2015# the rendering server.  Indicates that binary image data with the
2016# specified <size> will follow.
2017# ----------------------------------------------------------------------
2018itcl::body Rappture::VtkStreamlinesViewer::ReceiveLegend { colormap title vmin vmax size } {
2019    #puts stderr "ReceiveLegend colormap=$colormap title=$title range=$vmin,$vmax size=$size"
2020    set _limits(vmin) $vmin
2021    set _limits(vmax) $vmax
2022    set _title $title
2023    if { [IsConnected] } {
2024        set bytes [ReceiveBytes $size]
2025        if { ![info exists _image(legend)] } {
2026            set _image(legend) [image create photo]
2027        }
2028        $_image(legend) configure -data $bytes
2029        #puts stderr "read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
2030        DrawLegend
2031    }
2032}
2033
2034#
2035# DrawLegend --
2036#
2037#       Draws the legend in it's own canvas which resides to the right
2038#       of the contour plot area.
2039#
2040itcl::body Rappture::VtkStreamlinesViewer::DrawLegend {} {
2041    set c $itk_component(view)
2042    set w [winfo width $c]
2043    set h [winfo height $c]
2044    set font "Arial 8"
2045    set lineht [font metrics $font -linespace]
2046   
2047    if { $_settings(legend) } {
2048        set x [expr $w - 2]
2049        if { [$c find withtag "legend"] == "" } {
2050            $c create image $x [expr {$lineht+2}] \
2051                -anchor ne \
2052                -image $_image(legend) -tags "colormap legend"
2053            $c create text $x 2 \
2054                -anchor ne \
2055                -fill $itk_option(-plotforeground) -tags "vmax legend" \
2056                -font $font
2057            $c create text $x [expr {$h-2}] \
2058                -anchor se \
2059                -fill $itk_option(-plotforeground) -tags "vmin legend" \
2060                -font $font
2061            #$c bind colormap <Enter> [itcl::code $this EnterLegend %x %y]
2062            $c bind colormap <Leave> [itcl::code $this LeaveLegend]
2063            $c bind colormap <Motion> [itcl::code $this MotionLegend %x %y]
2064        }
2065        # Reset the item coordinates according the current size of the plot.
2066        $c coords colormap $x [expr {$lineht+2}]
2067        if { $_limits(vmin) != "" } {
2068            $c itemconfigure vmin -text [format %g $_limits(vmin)]
2069        }
2070        if { $_limits(vmax) != "" } {
2071            $c itemconfigure vmax -text [format %g $_limits(vmax)]
2072        }
2073        $c coords vmin $x [expr {$h-2}]
2074        $c coords vmax $x 2
2075    }
2076}
2077
2078#
2079# EnterLegend --
2080#
2081itcl::body Rappture::VtkStreamlinesViewer::EnterLegend { x y } {
2082    SetLegendTip $x $y
2083}
2084
2085#
2086# MotionLegend --
2087#
2088itcl::body Rappture::VtkStreamlinesViewer::MotionLegend { x y } {
2089    Rappture::Tooltip::tooltip cancel
2090    set c $itk_component(view)
2091    SetLegendTip $x $y
2092}
2093
2094#
2095# LeaveLegend --
2096#
2097itcl::body Rappture::VtkStreamlinesViewer::LeaveLegend { } {
2098    Rappture::Tooltip::tooltip cancel
2099    .rappturetooltip configure -icon ""
2100}
2101
2102#
2103# SetLegendTip --
2104#
2105itcl::body Rappture::VtkStreamlinesViewer::SetLegendTip { x y } {
2106    set c $itk_component(view)
2107    set w [winfo width $c]
2108    set h [winfo height $c]
2109    set font "Arial 8"
2110    set lineht [font metrics $font -linespace]
2111   
2112    set imgHeight [image height $_image(legend)]
2113    set coords [$c coords colormap]
2114    set imgX [expr $w - [image width $_image(legend)] - 2]
2115    set imgY [expr $y - $lineht - 2]
2116
2117    # Make a swatch of the selected color
2118    if { [catch { $_image(legend) get 10 $imgY } pixel] != 0 } {
2119        #puts stderr "out of range: $imgY"
2120        return
2121    }
2122    if { ![info exists _image(swatch)] } {
2123        set _image(swatch) [image create photo -width 24 -height 24]
2124    }
2125    set color [eval format "\#%02x%02x%02x" $pixel]
2126    $_image(swatch) put black  -to 0 0 23 23
2127    $_image(swatch) put $color -to 1 1 22 22
2128    .rappturetooltip configure -icon $_image(swatch)
2129
2130    # Compute the value of the point
2131    set t [expr 1.0 - (double($imgY) / double($imgHeight-1))]
2132    #puts stderr "t=$t x=$x y=$y imgY=$imgY"
2133    set value [expr $t * ($_limits(vmax) - $_limits(vmin)) + $_limits(vmin)]
2134    set tipx [expr $x + 15]
2135    set tipy [expr $y - 5]
2136    #puts stderr "tipx=$tipx tipy=$tipy x=$x y=$y"
2137    Rappture::Tooltip::text $c "$_title $value"
2138    Rappture::Tooltip::tooltip show $c +$tipx,+$tipy   
2139}
2140
2141
2142# ----------------------------------------------------------------------
2143# USAGE: Slice move x|y|z <newval>
2144#
2145# Called automatically when the user drags the slider to move the
2146# cut plane that slices 3D data.  Gets the current value from the
2147# slider and moves the cut plane to the appropriate point in the
2148# data set.
2149# ----------------------------------------------------------------------
2150itcl::body Rappture::VtkStreamlinesViewer::Slice {option args} {
2151    switch -- $option {
2152        "move" {
2153            set axis [lindex $args 0]
2154            set oldval $_axis(${axis}position)
2155            set newval [lindex $args 1]
2156            if {[llength $args] != 2} {
2157                error "wrong # args: should be \"Slice move x|y|z newval\""
2158            }
2159            set newpos [expr {0.01*$newval}]
2160            SendCmd "renderer clipplane $axis $newpos -1"
2161        }
2162        "tooltip" {
2163            set axis [lindex $args 0]
2164            set val [$itk_component(${axis}CutScale) get]
2165            return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
2166        }
2167        default {
2168            error "bad option \"$option\": should be axis, move, or tooltip"
2169        }
2170    }
2171}
Note: See TracBrowser for help on using the repository browser.