source: branches/1.3/gui/scripts/vtkisosurfaceviewer.tcl @ 4339

Last change on this file since 4339 was 4339, checked in by ldelgass, 11 years ago

Fix background setting in isosurface viewer

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