source: trunk/gui/scripts/vtkstreamlinesviewer.tcl @ 3402

Last change on this file since 3402 was 3402, checked in by ldelgass, 10 years ago

Add viserror parser alias to streamlines viewer

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