source: trunk/gui/scripts/vtkisosurfaceviewer.tcl @ 4096

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

Fix comment spelling

File size: 86.1 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 cutplaneXPosition]; list"
191
192    # Y-Cutplane event
193    $_dispatcher register !ycutplane
194    $_dispatcher dispatch $this !ycutplane \
195        "[itcl::code $this AdjustSetting cutplaneYPosition]; list"
196
197    # Z-Cutplane event
198    $_dispatcher register !zcutplane
199    $_dispatcher dispatch $this !zcutplane \
200        "[itcl::code $this AdjustSetting cutplaneZPosition]; 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 [subst {
225        background              black
226        colormap                BCGYR
227        colormapVisible         1
228        field                   "Default"
229        isolineColor            white
230        axesVisible             1
231        axisLabelsVisible       1
232        axisXGrid               0
233        axisYGrid               0
234        axisZGrid               0
235        cutplaneEdges           0
236        cutplaneLighting        1
237        cutplanePreinterp       1
238        cutplaneOpacity         100
239        cutplaneVisible         0
240        cutplaneWireframe       0
241        cutplaneXPosition       50
242        cutplaneXVisible        1
243        cutplaneYPosition       50
244        cutplaneYVisible        1
245        cutplaneZPosition       50
246        cutplaneZVisible        1
247        isosurfaceEdges         0
248        isosurfaceLighting      1
249        isosurfaceOpacity       60
250        saveIsosurfaceOpacity   60
251        isosurfaceOutline       0
252        isosurfaceVisible       1
253        isosurfaceWireframe     0
254        legendVisible           1
255        numContours             10
256    }]
257    array set _changed {
258        isosurfaceOpacity       0
259        colormap                0
260        numContours             0
261    }
262
263    itk_component add view {
264        canvas $itk_component(plotarea).view \
265            -highlightthickness 0 -borderwidth 0
266    } {
267        usual
268        ignore -highlightthickness -borderwidth  -background
269    }
270
271    itk_component add fieldmenu {
272        menu $itk_component(plotarea).menu -bg black -fg white -relief flat \
273            -tearoff no
274    } {
275        usual
276        ignore -background -foreground -relief -tearoff
277    }
278    set c $itk_component(view)
279    bind $c <Configure> [itcl::code $this EventuallyResize %w %h]
280    bind $c <4> [itcl::code $this Zoom in 0.25]
281    bind $c <5> [itcl::code $this Zoom out 0.25]
282    bind $c <KeyPress-Left>  [list %W xview scroll 10 units]
283    bind $c <KeyPress-Right> [list %W xview scroll -10 units]
284    bind $c <KeyPress-Up>    [list %W yview scroll 10 units]
285    bind $c <KeyPress-Down>  [list %W yview scroll -10 units]
286    bind $c <Enter> "focus %W"
287    bind $c <Control-F1> [itcl::code $this ToggleConsole]
288
289    # Fix the scrollregion in case we go off screen
290    $c configure -scrollregion [$c bbox all]
291
292    set _map(id) [$c create image 0 0 -anchor nw -image $_image(plot)]
293    set _map(cwidth) -1
294    set _map(cheight) -1
295    set _map(zoom) 1.0
296    set _map(original) ""
297
298    set f [$itk_component(main) component controls]
299    itk_component add reset {
300        button $f.reset -borderwidth 1 -padx 1 -pady 1 \
301            -highlightthickness 0 \
302            -image [Rappture::icon reset-view] \
303            -command [itcl::code $this Zoom reset]
304    } {
305        usual
306        ignore -highlightthickness
307    }
308    pack $itk_component(reset) -side top -padx 2 -pady 2
309    Rappture::Tooltip::for $itk_component(reset) \
310        "Reset the view to the default zoom level"
311
312    itk_component add zoomin {
313        button $f.zin -borderwidth 1 -padx 1 -pady 1 \
314            -highlightthickness 0 \
315            -image [Rappture::icon zoom-in] \
316            -command [itcl::code $this Zoom in]
317    } {
318        usual
319        ignore -highlightthickness
320    }
321    pack $itk_component(zoomin) -side top -padx 2 -pady 2
322    Rappture::Tooltip::for $itk_component(zoomin) "Zoom in"
323
324    itk_component add zoomout {
325        button $f.zout -borderwidth 1 -padx 1 -pady 1 \
326            -highlightthickness 0 \
327            -image [Rappture::icon zoom-out] \
328            -command [itcl::code $this Zoom out]
329    } {
330        usual
331        ignore -highlightthickness
332    }
333    pack $itk_component(zoomout) -side top -padx 2 -pady 2
334    Rappture::Tooltip::for $itk_component(zoomout) "Zoom out"
335
336    itk_component add contour {
337        Rappture::PushButton $f.contour \
338            -onimage [Rappture::icon volume-on] \
339            -offimage [Rappture::icon volume-off] \
340            -variable [itcl::scope _settings(isosurfaceVisible)] \
341            -command [itcl::code $this AdjustSetting isosurfaceVisible]
342    }
343    $itk_component(contour) select
344    Rappture::Tooltip::for $itk_component(contour) \
345        "Don't display the isosurface"
346    pack $itk_component(contour) -padx 2 -pady 2
347
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(cutplaneVisible)] \
353            -command [itcl::code $this AdjustSetting cutplaneVisible]
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        #puts stderr "$date: received image [image width $_image(plot)]x[image height $_image(plot)] image>"       
870        if { $_start > 0 } {
871            set finish [clock clicks -milliseconds]
872            #puts stderr "round trip time [expr $finish -$_start] milliseconds"
873            set _start 0
874        }
875    } elseif { $info(type) == "print" } {
876        set tag $this-print-$info(-token)
877        set _hardcopy($tag) $bytes
878    }
879}
880
881#
882# ReceiveDataset --
883#
884itcl::body Rappture::VtkIsosurfaceViewer::ReceiveDataset { args } {
885    if { ![isconnected] } {
886        return
887    }
888    set option [lindex $args 0]
889    switch -- $option {
890        "scalar" {
891            set option [lindex $args 1]
892            switch -- $option {
893                "world" {
894                    foreach { x y z value tag } [lrange $args 2 end] break
895                }
896                "pixel" {
897                    foreach { x y value tag } [lrange $args 2 end] break
898                }
899            }
900        }
901        "vector" {
902            set option [lindex $args 1]
903            switch -- $option {
904                "world" {
905                    foreach { x y z vx vy vz tag } [lrange $args 2 end] break
906                }
907                "pixel" {
908                    foreach { x y vx vy vz tag } [lrange $args 2 end] break
909                }
910            }
911        }
912        "names" {
913            foreach { name } [lindex $args 1] {
914                #puts stderr "Dataset: $name"
915            }
916        }
917        default {
918            error "unknown dataset option \"$option\" from server"
919        }
920    }
921}
922
923# ----------------------------------------------------------------------
924# USAGE: Rebuild
925#
926# Called automatically whenever something changes that affects the
927# data in the widget.  Clears any existing data and rebuilds the
928# widget to display new data.
929# ----------------------------------------------------------------------
930itcl::body Rappture::VtkIsosurfaceViewer::Rebuild {} {
931    set w [winfo width $itk_component(view)]
932    set h [winfo height $itk_component(view)]
933    if { $w < 2 || $h < 2 } {
934        $_dispatcher event -idle !rebuild
935        return
936    }
937
938    # Turn on buffering of commands to the server.  We don't want to
939    # be preempted by a server disconnect/reconnect (which automatically
940    # generates a new call to Rebuild).   
941    StartBufferingCommands
942
943    if { $_reset } {
944        set _width $w
945        set _height $h
946        $_arcball resize $w $h
947        DoResize
948        #
949        # Reset the camera and other view parameters
950        #
951        set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
952        $_arcball quaternion $q
953        if {$_view(ortho)} {
954            SendCmd "camera mode ortho"
955        } else {
956            SendCmd "camera mode persp"
957        }
958        DoRotate
959        PanCamera
960        set _first ""
961        InitSettings axisXGrid axisYGrid axisZGrid axisMode \
962            axesVisible axisLabelsVisible
963        foreach axis { x y z } {
964            SendCmd "axis lformat $axis %g"
965        }
966        StopBufferingCommands
967        SendCmd "imgflush"
968        StartBufferingCommands
969    }
970    set _first ""
971    SendCmd "dataset visible 0"
972    foreach dataobj [get -objects] {
973        if { [info exists _obj2ovride($dataobj-raise)] &&  $_first == "" } {
974            set _first $dataobj
975        }
976        set _obj2datasets($dataobj) ""
977        foreach comp [$dataobj components] {
978            set tag $dataobj-$comp
979            if { ![info exists _datasets($tag)] } {
980                set bytes [$dataobj vtkdata $comp]
981                if 0 {
982                    set f [open "/tmp/isosurface.vtk" "w"]
983                    puts $f $bytes
984                    close $f
985                }
986                set length [string length $bytes]
987                if { $_reportClientInfo }  {
988                    set info {}
989                    lappend info "tool_id"       [$dataobj hints toolId]
990                    lappend info "tool_name"     [$dataobj hints toolName]
991                    lappend info "tool_version"  [$dataobj hints toolRevision]
992                    lappend info "tool_title"    [$dataobj hints toolTitle]
993                    lappend info "dataset_label" [$dataobj hints label]
994                    lappend info "dataset_size"  $length
995                    lappend info "dataset_tag"   $tag
996                    SendCmd "clientinfo [list $info]"
997                }
998                append _outbuf "dataset add $tag data follows $length\n"
999                append _outbuf $bytes
1000                set _datasets($tag) 1
1001                SetObjectStyle $dataobj $comp
1002            }
1003            lappend _obj2datasets($dataobj) $tag
1004            if { [info exists _obj2ovride($dataobj-raise)] } {
1005                # Setting dataset visible enables outline
1006                # and contour3d
1007                SendCmd "dataset visible 1 $tag"
1008            }
1009        }
1010    }
1011
1012    if { $_first != "" } {
1013        $itk_component(field) choices delete 0 end
1014        $itk_component(fieldmenu) delete 0 end
1015        array unset _fields
1016        set _curFldName ""
1017        foreach cname [$_first components] {
1018            foreach fname [$_first fieldnames $cname] {
1019                if { [info exists _fields($fname)] } {
1020                    continue
1021                }
1022                foreach { label units components } \
1023                    [$_first fieldinfo $fname] break
1024                $itk_component(field) choices insert end "$fname" "$label"
1025                $itk_component(fieldmenu) add radiobutton -label "$label" \
1026                    -value $label -variable [itcl::scope _curFldLabel] \
1027                    -selectcolor red \
1028                    -activebackground $itk_option(-plotbackground) \
1029                    -activeforeground $itk_option(-plotforeground) \
1030                    -font "Arial 8" \
1031                    -command [itcl::code $this Combo invoke]
1032                set _fields($fname) [list $label $units $components]
1033                if { $_curFldName == "" } {
1034                    set _curFldName $fname
1035                    set _curFldLabel $label
1036                }
1037            }
1038        }
1039        $itk_component(field) value $_curFldLabel
1040    }
1041    InitSettings cutplaneVisible isosurfaceOutline
1042    if { $_reset } {
1043        # These are settings that rely on a dataset being loaded.
1044        InitSettings \
1045            isosurfaceLighting \
1046            field \
1047            isosurfaceEdges isosurfaceLighting isosurfaceOpacity \
1048            isosurfaceWireframe \
1049            cutplaneXPosition cutplaneYPosition cutplaneZPosition \
1050            cutplaneXVisible cutplaneYVisible cutplaneZVisible \
1051            cutplanePreinterp numContours
1052
1053        Zoom reset
1054        foreach axis { x y z } {
1055            # Another problem fixed by a <view>. We looking into a data
1056            # object for the name of the axes. This should be global to
1057            # the viewer itself.
1058            set label [$_first hints ${axis}label]
1059            if { $label == "" } {
1060                set label [string toupper $axis]
1061            }
1062            # May be a space in the axis label.
1063            SendCmd [list axis name $axis $label]
1064        }
1065        if { [array size _fields] < 2 } {
1066            blt::table forget $itk_component(field) $itk_component(field_l)
1067        }
1068        set _reset 0
1069    }
1070
1071    # Actually write the commands to the server socket.  If it fails, we don't
1072    # care.  We're finished here.
1073    blt::busy hold $itk_component(hull)
1074    StopBufferingCommands;              # Turn off buffering and send commands.
1075    blt::busy release $itk_component(hull)
1076}
1077
1078# ----------------------------------------------------------------------
1079# USAGE: CurrentDatasets ?-all -visible? ?dataobjs?
1080#
1081# Returns a list of server IDs for the current datasets being displayed.  This
1082# is normally a single ID, but it might be a list of IDs if the current data
1083# object has multiple components.
1084# ----------------------------------------------------------------------
1085itcl::body Rappture::VtkIsosurfaceViewer::CurrentDatasets {args} {
1086    set flag [lindex $args 0]
1087    switch -- $flag {
1088        "-all" {
1089            if { [llength $args] > 1 } {
1090                error "CurrentDatasets: can't specify dataobj after \"-all\""
1091            }
1092            set dlist [get -objects]
1093        }
1094        "-visible" {
1095            if { [llength $args] > 1 } {
1096                set dlist {}
1097                set args [lrange $args 1 end]
1098                foreach dataobj $args {
1099                    if { [info exists _obj2ovride($dataobj-raise)] } {
1100                        lappend dlist $dataobj
1101                    }
1102                }
1103            } else {
1104                set dlist [get -visible]
1105            }
1106        }           
1107        default {
1108            set dlist $args
1109        }
1110    }
1111    set rlist ""
1112    foreach dataobj $dlist {
1113        foreach comp [$dataobj components] {
1114            set tag $dataobj-$comp
1115            if { [info exists _datasets($tag)] && $_datasets($tag) } {
1116                lappend rlist $tag
1117            }
1118        }
1119    }
1120    return $rlist
1121}
1122
1123# ----------------------------------------------------------------------
1124# USAGE: Zoom in
1125# USAGE: Zoom out
1126# USAGE: Zoom reset
1127#
1128# Called automatically when the user clicks on one of the zoom
1129# controls for this widget.  Changes the zoom for the current view.
1130# ----------------------------------------------------------------------
1131itcl::body Rappture::VtkIsosurfaceViewer::Zoom {option} {
1132    switch -- $option {
1133        "in" {
1134            set _view(zoom) [expr {$_view(zoom)*1.25}]
1135            SendCmd "camera zoom $_view(zoom)"
1136        }
1137        "out" {
1138            set _view(zoom) [expr {$_view(zoom)*0.8}]
1139            SendCmd "camera zoom $_view(zoom)"
1140        }
1141        "reset" {
1142            array set _view {
1143                qw     0.853553
1144                qx     -0.353553
1145                qy     0.353553
1146                qz     0.146447
1147                zoom   1.0
1148                xpan   0
1149                ypan   0
1150            }
1151            if { $_first != "" } {
1152                set location [$_first hints camera]
1153                if { $location != "" } {
1154                    array set _view $location
1155                }
1156            }
1157            set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
1158            $_arcball quaternion $q
1159            DoRotate
1160            SendCmd "camera reset"
1161        }
1162    }
1163}
1164
1165itcl::body Rappture::VtkIsosurfaceViewer::PanCamera {} {
1166    set x $_view(xpan)
1167    set y $_view(ypan)
1168    SendCmd "camera pan $x $y"
1169}
1170
1171
1172# ----------------------------------------------------------------------
1173# USAGE: Rotate click <x> <y>
1174# USAGE: Rotate drag <x> <y>
1175# USAGE: Rotate release <x> <y>
1176#
1177# Called automatically when the user clicks/drags/releases in the
1178# plot area.  Moves the plot according to the user's actions.
1179# ----------------------------------------------------------------------
1180itcl::body Rappture::VtkIsosurfaceViewer::Rotate {option x y} {
1181    switch -- $option {
1182        "click" {
1183            $itk_component(view) configure -cursor fleur
1184            set _click(x) $x
1185            set _click(y) $y
1186        }
1187        "drag" {
1188            if {[array size _click] == 0} {
1189                Rotate click $x $y
1190            } else {
1191                set w [winfo width $itk_component(view)]
1192                set h [winfo height $itk_component(view)]
1193                if {$w <= 0 || $h <= 0} {
1194                    return
1195                }
1196
1197                if {[catch {
1198                    # this fails sometimes for no apparent reason
1199                    set dx [expr {double($x-$_click(x))/$w}]
1200                    set dy [expr {double($y-$_click(y))/$h}]
1201                }]} {
1202                    return
1203                }
1204                if { $dx == 0 && $dy == 0 } {
1205                    return
1206                }
1207                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1208                EventuallyRotate $q
1209                set _click(x) $x
1210                set _click(y) $y
1211            }
1212        }
1213        "release" {
1214            Rotate drag $x $y
1215            $itk_component(view) configure -cursor ""
1216            catch {unset _click}
1217        }
1218        default {
1219            error "bad option \"$option\": should be click, drag, release"
1220        }
1221    }
1222}
1223
1224itcl::body Rappture::VtkIsosurfaceViewer::Pick {x y} {
1225    foreach tag [CurrentDatasets -visible] {
1226        SendCmdNoSplash "dataset getscalar pixel $x $y $tag"
1227    }
1228}
1229
1230# ----------------------------------------------------------------------
1231# USAGE: $this Pan click x y
1232#        $this Pan drag x y
1233#        $this Pan release x y
1234#
1235# Called automatically when the user clicks on one of the zoom
1236# controls for this widget.  Changes the zoom for the current view.
1237# ----------------------------------------------------------------------
1238itcl::body Rappture::VtkIsosurfaceViewer::Pan {option x y} {
1239    switch -- $option {
1240        "set" {
1241            set w [winfo width $itk_component(view)]
1242            set h [winfo height $itk_component(view)]
1243            set x [expr $x / double($w)]
1244            set y [expr $y / double($h)]
1245            set _view(xpan) [expr $_view(xpan) + $x]
1246            set _view(ypan) [expr $_view(ypan) + $y]
1247            PanCamera
1248            return
1249        }
1250        "click" {
1251            set _click(x) $x
1252            set _click(y) $y
1253            $itk_component(view) configure -cursor hand1
1254        }
1255        "drag" {
1256            if { ![info exists _click(x)] } {
1257                set _click(x) $x
1258            }
1259            if { ![info exists _click(y)] } {
1260                set _click(y) $y
1261            }
1262            set w [winfo width $itk_component(view)]
1263            set h [winfo height $itk_component(view)]
1264            set dx [expr ($_click(x) - $x)/double($w)]
1265            set dy [expr ($_click(y) - $y)/double($h)]
1266            set _click(x) $x
1267            set _click(y) $y
1268            set _view(xpan) [expr $_view(xpan) - $dx]
1269            set _view(ypan) [expr $_view(ypan) - $dy]
1270            PanCamera
1271        }
1272        "release" {
1273            Pan drag $x $y
1274            $itk_component(view) configure -cursor ""
1275        }
1276        default {
1277            error "unknown option \"$option\": should set, click, drag, or release"
1278        }
1279    }
1280}
1281
1282# ----------------------------------------------------------------------
1283# USAGE: InitSettings <what> ?<value>?
1284#
1285# Used internally to update rendering settings whenever parameters
1286# change in the popup settings panel.  Sends the new settings off
1287# to the back end.
1288# ----------------------------------------------------------------------
1289itcl::body Rappture::VtkIsosurfaceViewer::InitSettings { args } {
1290    foreach spec $args {
1291        if { [info exists _settings($_first-$spec)] } {
1292            # Reset global setting with dataobj specific setting
1293            set _settings($spec) $_settings($_first-$spec)
1294        }
1295        AdjustSetting $spec
1296    }
1297}
1298
1299#
1300# AdjustSetting --
1301#
1302#       Changes/updates a specific setting in the widget.  There are
1303#       usually user-setable option.  Commands are sent to the render
1304#       server.
1305#
1306itcl::body Rappture::VtkIsosurfaceViewer::AdjustSetting {what {value ""}} {
1307    if { ![isconnected] } {
1308        return
1309    }
1310    switch -- $what {
1311        "background" {
1312            set bgcolor [$itk_component(background) value]
1313            array set fgcolors {
1314                "black" "white"
1315                "white" "black"
1316                "grey"  "black"
1317            }
1318            configure -plotbackground $bgcolor \
1319                -plotforeground $fgcolors($bgcolor)
1320            $itk_component(view) delete "legend"
1321            DrawLegend
1322        }
1323        "axesVisible" {
1324            set bool $_settings(axesVisible)
1325            SendCmd "axis visible all $bool"
1326        }
1327        "axisLabelsVisible" {
1328            set bool $_settings(axisLabelsVisible)
1329            SendCmd "axis labels all $bool"
1330        }
1331        "axisXGrid" - "axisYGrid" - "axisZGrid" {
1332            set axis [string tolower [string range $what 4 4]]
1333            set bool $_settings($what)
1334            SendCmd "axis grid $axis $bool"
1335        }
1336        "axisMode" {
1337            set mode [$itk_component(axisMode) value]
1338            set mode [$itk_component(axisMode) translate $mode]
1339            set _settings($what) $mode
1340            SendCmd "axis flymode $mode"
1341        }
1342        "cutplaneEdges" {
1343            set bool $_settings($what)
1344            SendCmd "cutplane edges $bool"
1345        }
1346        "cutplaneVisible" {
1347            set bool $_settings($what)
1348            SendCmd "cutplane visible $bool"
1349        }
1350        "cutplaneWireframe" {
1351            set bool $_settings($what)
1352            SendCmd "cutplane wireframe $bool"
1353        }
1354        "cutplaneLighting" {
1355            set bool $_settings($what)
1356            SendCmd "cutplane lighting $bool"
1357        }
1358        "cutplaneOpacity" {
1359            set val $_settings($what)
1360            set sval [expr { 0.01 * double($val) }]
1361            SendCmd "cutplane opacity $sval"
1362        }
1363        "cutplanePreinterp" {
1364            set bool $_settings($what)
1365            SendCmd "cutplane preinterp $bool"
1366        }
1367        "cutplaneXVisible" - "cutplaneYVisible" - "cutplaneZVisible" {
1368            set axis [string tolower [string range $what 8 8]]
1369            set bool $_settings($what)
1370            if { $bool } {
1371                $itk_component(${axis}position) configure -state normal \
1372                    -troughcolor white
1373            } else {
1374                $itk_component(${axis}position) configure -state disabled \
1375                    -troughcolor grey82
1376            }
1377            SendCmd "cutplane axis $axis $bool"
1378        }
1379        "cutplaneXPosition" - "cutplaneYPosition" - "cutplaneZPosition" {
1380            set axis [string tolower [string range $what 8 8]]
1381            set pos [expr $_settings($what) * 0.01]
1382            SendCmd "cutplane slice ${axis} ${pos}"
1383            set _cutplanePending 0
1384        }
1385        "colormap" {
1386            set _changed(colormap) 1
1387            StartBufferingCommands
1388            set color [$itk_component(colormap) value]
1389            set _settings(colormap) $color
1390            if { $color == "none" } {
1391                if { $_settings(colormapVisible) } {
1392                    SendCmd "contour3d colormode constant {}"
1393                    set _settings(colormapVisible) 0
1394                }
1395            } else {
1396                if { !$_settings(colormapVisible) } {
1397                    SendCmd "contour3d colormode $_colorMode $_curFldName"
1398                    set _settings(colormapVisible) 1
1399                }
1400                SetCurrentColormap $color
1401            }
1402            StopBufferingCommands
1403            EventuallyRequestLegend
1404        }
1405        "numContours" {
1406            set _settings(numContours) [$itk_component(numcontours) value]
1407            set _currentNumContours $_settings(numContours)
1408            UpdateContourList
1409            set _changed(numContours) 1
1410            SendCmd "contour3d contourlist [list $_contourList]"
1411            DrawLegend
1412        }
1413        "isosurfaceWireframe" {
1414            set bool $_settings(isosurfaceWireframe)
1415            SendCmd "contour3d wireframe $bool"
1416        }
1417        "isosurfaceVisible" {
1418            set bool $_settings(isosurfaceVisible)
1419            SendCmd "contour3d visible $bool"
1420            if { $bool } {
1421                Rappture::Tooltip::for $itk_component(contour) \
1422                    "Hide the isosurface"
1423            } else {
1424                Rappture::Tooltip::for $itk_component(contour) \
1425                    "Show the isosurface"
1426            }
1427            DrawLegend
1428        }
1429        "isosurfaceLighting" {
1430            set bool $_settings(isosurfaceLighting)
1431            SendCmd "contour3d lighting $bool"
1432        }
1433        "isosurfaceEdges" {
1434            set bool $_settings(isosurfaceEdges)
1435            SendCmd "contour3d edges $bool"
1436        }
1437        "isosurfaceOutline" {
1438            set bool $_settings(isosurfaceOutline)
1439            SendCmd "outline visible $bool"
1440        }
1441        "isolineColor" {
1442            set color [$itk_component(isolineColor) value]
1443            set _settings(isolineColor) $color
1444            DrawLegend
1445        }
1446        "isosurfaceOpacity" {
1447            set val $_settings(isosurfaceOpacity)
1448            set sval [expr { 0.01 * double($val) }]
1449            SendCmd "contour3d opacity $sval"
1450        }
1451        "field" {
1452            set label [$itk_component(field) value]
1453            set fname [$itk_component(field) translate $label]
1454            set _settings(field) $fname
1455            if { [info exists _fields($fname)] } {
1456                foreach { label units components } $_fields($fname) break
1457                if { $components > 1 } {
1458                    set _colorMode vmag
1459                } else {
1460                    set _colorMode scalar
1461                }
1462                set _curFldName $fname
1463                set _curFldLabel $label
1464            } else {
1465                puts stderr "unknown field \"$fname\""
1466                return
1467            }
1468            SendCmd "dataset scalar $_curFldName"
1469            SendCmd "dataset maprange explicit $_limits($_curFldName) $_curFldName"
1470            SendCmd "cutplane colormode $_colorMode $_curFldName"
1471            SendCmd "contour3d colormode $_colorMode $_curFldName"
1472            SendCmd "camera reset"
1473            UpdateContourList
1474            DrawLegend
1475        }
1476        "legendVisible" {
1477            if { !$_settings(legendVisible) } {
1478                $itk_component(view) delete legend
1479            }
1480            DrawLegend
1481        }
1482        default {
1483            error "don't know how to fix $what"
1484        }
1485    }
1486}
1487
1488
1489#
1490# RequestLegend --
1491#
1492#       Request a new legend from the server.  The size of the legend
1493#       is determined from the height of the canvas. 
1494#
1495# This should be called when
1496#       1.  A new current colormap is set.
1497#       2.  Window is resized.
1498#       3.  The limits of the data have changed.  (Just need a redraw).
1499#       4.  Number of isolines have changed. (Just need a redraw).
1500#       5.  Legend becomes visible (Just need a redraw).
1501#
1502itcl::body Rappture::VtkIsosurfaceViewer::RequestLegend {} {
1503    set _legendPending 0
1504    if { ![info exists _fields($_curFldName)] } {
1505        return
1506    }
1507    set fname $_curFldName
1508    set font "Arial 8"
1509    set lineht [font metrics $font -linespace]
1510    set w 12
1511    set h [expr {$_height - 2 * ($lineht + 2)}]
1512    if { $h < 1 } {
1513        return
1514    }
1515    if { [string match "component*" $fname] } {
1516        set title ""
1517    } else {
1518        if { [info exists _fields($fname)] } {
1519            foreach { title units } $_fields($fname) break
1520            if { $units != "" } {
1521                set title [format "%s (%s)" $title $units]
1522            }
1523        } else {
1524            set title $fname
1525        }
1526    }
1527    # If there's a title too, subtract one more line
1528    if { $title != "" } {
1529        incr h -$lineht
1530    }
1531    # Set the legend on the first heightmap dataset.
1532    if { $_currentColormap != ""  } {
1533        set cmap $_currentColormap
1534        SendCmdNoWait "legend $cmap scalar $_curFldName {} $w $h 0"
1535    }
1536}
1537
1538# ----------------------------------------------------------------------
1539# CONFIGURATION OPTION: -plotbackground
1540# ----------------------------------------------------------------------
1541itcl::configbody Rappture::VtkIsosurfaceViewer::plotbackground {
1542    if { [isconnected] } {
1543        set rgb [Color2RGB $itk_option(-plotbackground)]
1544        SendCmd "screen bgcolor $rgb"
1545    }
1546}
1547
1548# ----------------------------------------------------------------------
1549# CONFIGURATION OPTION: -plotforeground
1550# ----------------------------------------------------------------------
1551itcl::configbody Rappture::VtkIsosurfaceViewer::plotforeground {
1552    if { [isconnected] } {
1553        set rgb [Color2RGB $itk_option(-plotforeground)]
1554        SendCmd "axis color all $rgb"
1555        SendCmd "outline color $rgb"
1556        SendCmd "cutplane color $rgb"
1557    }
1558}
1559
1560itcl::body Rappture::VtkIsosurfaceViewer::limits { dataobj } {
1561    foreach { limits(xmin) limits(xmax) } [$dataobj limits x] break
1562    foreach { limits(ymin) limits(ymax) } [$dataobj limits y] break
1563    foreach { limits(zmin) limits(zmax) } [$dataobj limits z] break
1564    foreach { limits(vmin) limits(vmax) } [$dataobj limits v] break
1565    return [array get limits]
1566}
1567
1568itcl::body Rappture::VtkIsosurfaceViewer::BuildIsosurfaceTab {} {
1569
1570    set fg [option get $itk_component(hull) font Font]
1571    #set bfg [option get $itk_component(hull) boldFont Font]
1572
1573    set inner [$itk_component(main) insert end \
1574        -title "Isosurface Settings" \
1575        -icon [Rappture::icon volume-on]]
1576    $inner configure -borderwidth 4
1577
1578    checkbutton $inner.contour \
1579        -text "Isosurfaces" \
1580        -variable [itcl::scope _settings(isosurfaceVisible)] \
1581        -command [itcl::code $this AdjustSetting isosurfaceVisible] \
1582        -font "Arial 9"
1583
1584    checkbutton $inner.wireframe \
1585        -text "Wireframe" \
1586        -variable [itcl::scope _settings(isosurfaceWireframe)] \
1587        -command [itcl::code $this AdjustSetting isosurfaceWireframe] \
1588        -font "Arial 9"
1589
1590    checkbutton $inner.lighting \
1591        -text "Enable Lighting" \
1592        -variable [itcl::scope _settings(isosurfaceLighting)] \
1593        -command [itcl::code $this AdjustSetting isosurfaceLighting] \
1594        -font "Arial 9"
1595
1596    checkbutton $inner.edges \
1597        -text "Edges" \
1598        -variable [itcl::scope _settings(isosurfaceEdges)] \
1599        -command [itcl::code $this AdjustSetting isosurfaceEdges] \
1600        -font "Arial 9"
1601
1602    checkbutton $inner.outline \
1603        -text "Outline" \
1604        -variable [itcl::scope _settings(isosurfaceOutline)] \
1605        -command [itcl::code $this AdjustSetting isosurfaceOutline] \
1606        -font "Arial 9"
1607
1608    checkbutton $inner.legend \
1609        -text "Legend" \
1610        -variable [itcl::scope _settings(legendVisible)] \
1611        -command [itcl::code $this AdjustSetting legendVisible] \
1612        -font "Arial 9"
1613
1614    label $inner.linecolor_l -text "Isolines" -font "Arial 9"
1615    itk_component add isolineColor {
1616        Rappture::Combobox $inner.linecolor -width 10 -editable no
1617    }
1618    $inner.linecolor choices insert end \
1619        "black"              "black"            \
1620        "blue"               "blue"             \
1621        "cyan"               "cyan"             \
1622        "green"              "green"            \
1623        "grey"               "grey"             \
1624        "magenta"            "magenta"          \
1625        "orange"             "orange"           \
1626        "red"                "red"              \
1627        "white"              "white"            \
1628        "none"               "none"
1629
1630    $itk_component(isolineColor) value "white"
1631    bind $inner.linecolor <<Value>> \
1632        [itcl::code $this AdjustSetting isolineColor]
1633
1634    label $inner.background_l -text "Background" -font "Arial 9"
1635    itk_component add background {
1636        Rappture::Combobox $inner.background -width 10 -editable no
1637    }
1638    $inner.background choices insert end \
1639        "black"              "black"            \
1640        "white"              "white"            \
1641        "grey"               "grey"             
1642
1643    $itk_component(background) value $_settings(background)
1644    bind $inner.background <<Value>> [itcl::code $this AdjustSetting background]
1645
1646    label $inner.opacity_l -text "Opacity" -font "Arial 9"
1647    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1648        -variable [itcl::scope _settings(isosurfaceOpacity)] \
1649        -width 10 \
1650        -showvalue off \
1651        -command [itcl::code $this AdjustSetting isosurfaceOpacity]
1652
1653    label $inner.scale_l -text "Scale" -font "Arial 9"
1654    ::scale $inner.scale -from 1 -to 100 -orient horizontal \
1655        -variable [itcl::scope _settings(contour-scale)] \
1656        -width 10 \
1657        -showvalue off \
1658        -command [itcl::code $this AdjustSetting contour-scale]
1659
1660    itk_component add field_l {
1661        label $inner.field_l -text "Field" -font "Arial 9"
1662    } {
1663        ignore -font
1664    }
1665    itk_component add field {
1666        Rappture::Combobox $inner.field -width 10 -editable no
1667    }
1668    bind $inner.field <<Value>> \
1669        [itcl::code $this AdjustSetting field]
1670
1671    label $inner.colormap_l -text "Colormap" -font "Arial 9"
1672    itk_component add colormap {
1673        Rappture::Combobox $inner.colormap -width 10 -editable no
1674    }
1675    $inner.colormap choices insert end \
1676        "BCGYR"              "BCGYR"            \
1677        "BGYOR"              "BGYOR"            \
1678        "blue"               "blue"             \
1679        "blue-to-brown"      "blue-to-brown"    \
1680        "blue-to-orange"     "blue-to-orange"   \
1681        "blue-to-grey"       "blue-to-grey"     \
1682        "green-to-magenta"   "green-to-magenta" \
1683        "greyscale"          "greyscale"        \
1684        "nanohub"            "nanohub"          \
1685        "rainbow"            "rainbow"          \
1686        "spectral"           "spectral"         \
1687        "ROYGB"              "ROYGB"            \
1688        "RYGCB"              "RYGCB"            \
1689        "brown-to-blue"      "brown-to-blue"    \
1690        "grey-to-blue"       "grey-to-blue"     \
1691        "orange-to-blue"     "orange-to-blue"   
1692
1693    $itk_component(colormap) value "BCGYR"
1694    bind $inner.colormap <<Value>> \
1695        [itcl::code $this AdjustSetting colormap]
1696
1697    label $inner.numcontours_l -text "Number of Isosurfaces" -font "Arial 9"
1698    itk_component add numcontours {
1699        Rappture::Spinint $inner.numcontours \
1700            -min 1 -max 50 -font "arial 9"
1701    }
1702    $itk_component(numcontours) value $_settings(numContours)
1703    bind $itk_component(numcontours) <<Value>> \
1704        [itcl::code $this AdjustSetting numContours]
1705
1706    blt::table $inner \
1707        0,0 $inner.field_l   -anchor w -pady 2  \
1708        0,1 $inner.field     -anchor w -pady 2  -fill x \
1709        1,0 $inner.colormap_l -anchor w -pady 2  \
1710        1,1 $inner.colormap   -anchor w -pady 2  -fill x \
1711        2,0 $inner.linecolor_l  -anchor w -pady 2  \
1712        2,1 $inner.linecolor    -anchor w -pady 2 -fill x  \
1713        3,0 $inner.background_l -anchor w -pady 2 \
1714        3,1 $inner.background -anchor w -pady 2  -fill x \
1715        4,0 $inner.numcontours_l -anchor w -pady 2 \
1716        4,1 $inner.numcontours -anchor w -pady 2 \
1717        5,0 $inner.wireframe -anchor w -pady 2 -cspan 2 \
1718        6,0 $inner.lighting  -anchor w -pady 2 -cspan 2 \
1719        7,0 $inner.edges     -anchor w -pady 2 -cspan 2 \
1720        8,0 $inner.outline   -anchor w -pady 2 -cspan 2 \
1721        9,0 $inner.legend    -anchor w -pady 2 \
1722        10,0 $inner.opacity_l -anchor w -pady 2 \
1723        10,1 $inner.opacity   -fill x   -pady 2 -fill x \
1724
1725    blt::table configure $inner r* c* -resize none
1726    blt::table configure $inner r11 c1 -resize expand
1727}
1728
1729itcl::body Rappture::VtkIsosurfaceViewer::BuildAxisTab {} {
1730
1731    set fg [option get $itk_component(hull) font Font]
1732    #set bfg [option get $itk_component(hull) boldFont Font]
1733
1734    set inner [$itk_component(main) insert end \
1735        -title "Axis Settings" \
1736        -icon [Rappture::icon axis2]]
1737    $inner configure -borderwidth 4
1738
1739    checkbutton $inner.visible \
1740        -text "Show Axes" \
1741        -variable [itcl::scope _settings(axesVisible)] \
1742        -command [itcl::code $this AdjustSetting axesVisible] \
1743        -font "Arial 9"
1744
1745    checkbutton $inner.labels \
1746        -text "Show Axis Labels" \
1747        -variable [itcl::scope _settings(axisLabelsVisible)] \
1748        -command [itcl::code $this AdjustSetting axisLabelsVisible] \
1749        -font "Arial 9"
1750
1751    checkbutton $inner.gridx \
1752        -text "Show X Grid" \
1753        -variable [itcl::scope _settings(axisXGrid)] \
1754        -command [itcl::code $this AdjustSetting axisXGrid] \
1755        -font "Arial 9"
1756    checkbutton $inner.gridy \
1757        -text "Show Y Grid" \
1758        -variable [itcl::scope _settings(axisYGrid)] \
1759        -command [itcl::code $this AdjustSetting axisYGrid] \
1760        -font "Arial 9"
1761    checkbutton $inner.gridz \
1762        -text "Show Z Grid" \
1763        -variable [itcl::scope _settings(axisZGrid)] \
1764        -command [itcl::code $this AdjustSetting axisZGrid] \
1765        -font "Arial 9"
1766
1767    label $inner.mode_l -text "Mode" -font "Arial 9"
1768
1769    itk_component add axisMode {
1770        Rappture::Combobox $inner.mode -width 10 -editable no
1771    }
1772    $inner.mode choices insert end \
1773        "static_triad"    "static" \
1774        "closest_triad"   "closest" \
1775        "furthest_triad"  "farthest" \
1776        "outer_edges"     "outer"         
1777    $itk_component(axisMode) value "static"
1778    bind $inner.mode <<Value>> [itcl::code $this AdjustSetting axisMode]
1779
1780    blt::table $inner \
1781        0,0 $inner.visible -anchor w -cspan 2 \
1782        1,0 $inner.labels  -anchor w -cspan 2 \
1783        2,0 $inner.gridx   -anchor w -cspan 2 \
1784        3,0 $inner.gridy   -anchor w -cspan 2 \
1785        4,0 $inner.gridz   -anchor w -cspan 2 \
1786        5,0 $inner.mode_l  -anchor w -cspan 2 -padx { 2 0 } \
1787        6,0 $inner.mode    -fill x   -cspan 2
1788
1789    blt::table configure $inner r* c* -resize none
1790    blt::table configure $inner r7 c1 -resize expand
1791}
1792
1793
1794itcl::body Rappture::VtkIsosurfaceViewer::BuildCameraTab {} {
1795    set inner [$itk_component(main) insert end \
1796        -title "Camera Settings" \
1797        -icon [Rappture::icon camera]]
1798    $inner configure -borderwidth 4
1799
1800    label $inner.view_l -text "view" -font "Arial 9"
1801    set f [frame $inner.view]
1802    foreach side { front back left right top bottom } {
1803        button $f.$side  -image [Rappture::icon view$side] \
1804            -command [itcl::code $this SetOrientation $side]
1805        Rappture::Tooltip::for $f.$side "Change the view to $side"
1806        pack $f.$side -side left
1807    }
1808
1809    blt::table $inner \
1810        0,0 $inner.view_l -anchor e -pady 2 \
1811        0,1 $inner.view -anchor w -pady 2
1812
1813    set labels { qx qy qz qw xpan ypan zoom }
1814    set row 1
1815    foreach tag $labels {
1816        label $inner.${tag}label -text $tag -font "Arial 9"
1817        entry $inner.${tag} -font "Arial 9"  -bg white \
1818            -textvariable [itcl::scope _view($tag)]
1819        bind $inner.${tag} <KeyPress-Return> \
1820            [itcl::code $this camera set ${tag}]
1821        blt::table $inner \
1822            $row,0 $inner.${tag}label -anchor e -pady 2 \
1823            $row,1 $inner.${tag} -anchor w -pady 2
1824        blt::table configure $inner r$row -resize none
1825        incr row
1826    }
1827    checkbutton $inner.ortho \
1828        -text "Orthographic Projection" \
1829        -variable [itcl::scope _view(ortho)] \
1830        -command [itcl::code $this camera set ortho] \
1831        -font "Arial 9"
1832    blt::table $inner \
1833            $row,0 $inner.ortho -cspan 2 -anchor w -pady 2
1834    blt::table configure $inner r$row -resize none
1835    incr row
1836
1837    blt::table configure $inner c* r* -resize none
1838    blt::table configure $inner c2 -resize expand
1839    blt::table configure $inner r$row -resize expand
1840}
1841
1842itcl::body Rappture::VtkIsosurfaceViewer::BuildCutplaneTab {} {
1843
1844    set fg [option get $itk_component(hull) font Font]
1845   
1846    set inner [$itk_component(main) insert end \
1847        -title "Cutplane Settings" \
1848        -icon [Rappture::icon cutbutton]]
1849
1850    $inner configure -borderwidth 4
1851
1852    checkbutton $inner.visible \
1853        -text "Cutplanes" \
1854        -variable [itcl::scope _settings(cutplaneVisible)] \
1855        -command [itcl::code $this AdjustSetting cutplaneVisible] \
1856        -font "Arial 9"
1857
1858    checkbutton $inner.wireframe \
1859        -text "Wireframe" \
1860        -variable [itcl::scope _settings(cutplaneWireframe)] \
1861        -command [itcl::code $this AdjustSetting cutplaneWireframe] \
1862        -font "Arial 9"
1863
1864    checkbutton $inner.lighting \
1865        -text "Enable Lighting" \
1866        -variable [itcl::scope _settings(cutplaneLighting)] \
1867        -command [itcl::code $this AdjustSetting cutplaneLighting] \
1868        -font "Arial 9"
1869
1870    checkbutton $inner.edges \
1871        -text "Edges" \
1872        -variable [itcl::scope _settings(cutplaneEdges)] \
1873        -command [itcl::code $this AdjustSetting cutplaneEdges] \
1874        -font "Arial 9"
1875
1876    checkbutton $inner.preinterp \
1877        -text "Interpolate Scalars" \
1878        -variable [itcl::scope _settings(cutplanePreinterp)] \
1879        -command [itcl::code $this AdjustSetting cutplanePreinterp] \
1880        -font "Arial 9"
1881
1882    label $inner.opacity_l -text "Opacity" -font "Arial 9"
1883    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1884        -variable [itcl::scope _settings(cutplaneOpacity)] \
1885        -width 10 \
1886        -showvalue off \
1887        -command [itcl::code $this AdjustSetting cutplaneOpacity]
1888    $inner.opacity set $_settings(cutplaneOpacity)
1889
1890    # X-value slicer...
1891    itk_component add xbutton {
1892        Rappture::PushButton $inner.xbutton \
1893            -onimage [Rappture::icon x-cutplane-red] \
1894            -offimage [Rappture::icon x-cutplane-red] \
1895            -command [itcl::code $this AdjustSetting cutplaneXVisible] \
1896            -variable [itcl::scope _settings(cutplaneXVisible)] \
1897    }
1898    Rappture::Tooltip::for $itk_component(xbutton) \
1899        "Toggle the X-axis cutplane on/off"
1900    $itk_component(xbutton) select
1901    itk_component add xposition {
1902        ::scale $inner.xval -from 100 -to 0 \
1903            -width 10 -orient vertical -showvalue yes \
1904            -borderwidth 1 -highlightthickness 0 \
1905            -command [itcl::code $this EventuallySetCutplane x] \
1906            -variable [itcl::scope _settings(cutplaneXPosition)] \
1907            -foreground red2 -font "Arial 9 bold"
1908    } {
1909        usual
1910        ignore -borderwidth -highlightthickness -foreground -font -background
1911    }
1912    # Set the default cutplane value before disabling the scale.
1913    $itk_component(xposition) set 50
1914    $itk_component(xposition) configure -state disabled
1915    Rappture::Tooltip::for $itk_component(xposition) \
1916        "@[itcl::code $this Slice tooltip x]"
1917
1918    # Y-value slicer...
1919    itk_component add ybutton {
1920        Rappture::PushButton $inner.ybutton \
1921            -onimage [Rappture::icon y-cutplane-green] \
1922            -offimage [Rappture::icon y-cutplane-green] \
1923            -command [itcl::code $this AdjustSetting cutplaneYVisible] \
1924            -variable [itcl::scope _settings(cutplaneYVisible)] \
1925    }
1926    Rappture::Tooltip::for $itk_component(ybutton) \
1927        "Toggle the Y-axis cutplane on/off"
1928    $itk_component(ybutton) select
1929
1930    itk_component add yposition {
1931        ::scale $inner.yval -from 100 -to 0 \
1932            -width 10 -orient vertical -showvalue yes \
1933            -borderwidth 1 -highlightthickness 0 \
1934            -command [itcl::code $this EventuallySetCutplane y] \
1935            -variable [itcl::scope _settings(cutplaneYPosition)] \
1936            -foreground green3 -font "Arial 9 bold"
1937    } {
1938        usual
1939        ignore -borderwidth -highlightthickness -foreground -font
1940    }
1941    Rappture::Tooltip::for $itk_component(yposition) \
1942        "@[itcl::code $this Slice tooltip y]"
1943    # Set the default cutplane value before disabling the scale.
1944    $itk_component(yposition) set 50
1945    $itk_component(yposition) configure -state disabled
1946
1947    # Z-value slicer...
1948    itk_component add zbutton {
1949        Rappture::PushButton $inner.zbutton \
1950            -onimage [Rappture::icon z-cutplane-blue] \
1951            -offimage [Rappture::icon z-cutplane-blue] \
1952            -command [itcl::code $this AdjustSetting cutplaneZVisible] \
1953            -variable [itcl::scope _settings(cutplaneZVisible)] \
1954    } {
1955        usual
1956        ignore -foreground
1957    }
1958    Rappture::Tooltip::for $itk_component(zbutton) \
1959        "Toggle the Z-axis cutplane on/off"
1960    $itk_component(zbutton) select
1961
1962    itk_component add zposition {
1963        ::scale $inner.zval -from 100 -to 0 \
1964            -width 10 -orient vertical -showvalue yes \
1965            -borderwidth 1 -highlightthickness 0 \
1966            -command [itcl::code $this EventuallySetCutplane z] \
1967            -variable [itcl::scope _settings(cutplaneZPosition)] \
1968            -foreground blue3 -font "Arial 9 bold"
1969    } {
1970        usual
1971        ignore -borderwidth -highlightthickness -foreground -font
1972    }
1973    $itk_component(zposition) set 50
1974    $itk_component(zposition) configure -state disabled
1975    Rappture::Tooltip::for $itk_component(zposition) \
1976        "@[itcl::code $this Slice tooltip z]"
1977
1978    blt::table $inner \
1979        0,0 $inner.visible              -anchor w -pady 2 -cspan 3 \
1980        1,0 $inner.lighting             -anchor w -pady 2 -cspan 3 \
1981        2,0 $inner.wireframe            -anchor w -pady 2 -cspan 3 \
1982        3,0 $inner.edges                -anchor w -pady 2 -cspan 3 \
1983        4,0 $inner.preinterp            -anchor w -pady 2 -cspan 3 \
1984        5,0 $inner.opacity_l            -anchor w -pady 2 -cspan 1 \
1985        5,1 $inner.opacity              -fill x   -pady 2 -cspan 3 \
1986        6,0 $inner.xbutton              -anchor w -padx 2 -pady 2 \
1987        7,0 $inner.ybutton              -anchor w -padx 2 -pady 2 \
1988        8,0 $inner.zbutton              -anchor w -padx 2 -pady 2 \
1989        6,1 $inner.xval                 -fill y -rspan 4 \
1990        6,2 $inner.yval                 -fill y -rspan 4 \
1991        6,3 $inner.zval                 -fill y -rspan 4 \
1992
1993
1994    blt::table configure $inner r* c* -resize none
1995    blt::table configure $inner r9 c4 -resize expand
1996}
1997
1998
1999
2000#
2001#  camera --
2002#
2003itcl::body Rappture::VtkIsosurfaceViewer::camera {option args} {
2004    switch -- $option {
2005        "show" {
2006            puts [array get _view]
2007        }
2008        "set" {
2009            set who [lindex $args 0]
2010            set x $_view($who)
2011            set code [catch { string is double $x } result]
2012            if { $code != 0 || !$result } {
2013                return
2014            }
2015            switch -- $who {
2016                "ortho" {
2017                    if {$_view(ortho)} {
2018                        SendCmd "camera mode ortho"
2019                    } else {
2020                        SendCmd "camera mode persp"
2021                    }
2022                }
2023                "xpan" - "ypan" {
2024                    PanCamera
2025                }
2026                "qx" - "qy" - "qz" - "qw" {
2027                    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
2028                    $_arcball quaternion $q
2029                    EventuallyRotate $q
2030                }
2031                "zoom" {
2032                    SendCmd "camera zoom $_view(zoom)"
2033                }
2034             }
2035        }
2036    }
2037}
2038
2039itcl::body Rappture::VtkIsosurfaceViewer::GetVtkData { args } {
2040    set bytes ""
2041    foreach dataobj [get] {
2042        foreach cname [$dataobj components] {
2043            set tag $dataobj-$cname
2044            set contents [$dataobj vtkdata $cname]
2045            append bytes "$contents\n"
2046        }
2047    }
2048    return [list .vtk $bytes]
2049}
2050
2051itcl::body Rappture::VtkIsosurfaceViewer::GetImage { args } {
2052    if { [image width $_image(download)] > 0 &&
2053         [image height $_image(download)] > 0 } {
2054        set bytes [$_image(download) data -format "jpeg -quality 100"]
2055        set bytes [Rappture::encoding::decode -as b64 $bytes]
2056        return [list .jpg $bytes]
2057    }
2058    return ""
2059}
2060
2061itcl::body Rappture::VtkIsosurfaceViewer::BuildDownloadPopup { popup command } {
2062    Rappture::Balloon $popup \
2063        -title "[Rappture::filexfer::label downloadWord] as..."
2064    set inner [$popup component inner]
2065    label $inner.summary -text "" -anchor w
2066    radiobutton $inner.vtk_button -text "VTK data file" \
2067        -variable [itcl::scope _downloadPopup(format)] \
2068        -font "Arial 9 " \
2069        -value vtk 
2070    Rappture::Tooltip::for $inner.vtk_button "Save as VTK data file."
2071    radiobutton $inner.image_button -text "Image File" \
2072        -variable [itcl::scope _downloadPopup(format)] \
2073        -font "Arial 9 " \
2074        -value image
2075    Rappture::Tooltip::for $inner.image_button \
2076        "Save as digital image."
2077
2078    button $inner.ok -text "Save" \
2079        -highlightthickness 0 -pady 2 -padx 3 \
2080        -command $command \
2081        -compound left \
2082        -image [Rappture::icon download]
2083
2084    button $inner.cancel -text "Cancel" \
2085        -highlightthickness 0 -pady 2 -padx 3 \
2086        -command [list $popup deactivate] \
2087        -compound left \
2088        -image [Rappture::icon cancel]
2089
2090    blt::table $inner \
2091        0,0 $inner.summary -cspan 2  \
2092        1,0 $inner.vtk_button -anchor w -cspan 2 -padx { 4 0 } \
2093        2,0 $inner.image_button -anchor w -cspan 2 -padx { 4 0 } \
2094        4,1 $inner.cancel -width .9i -fill y \
2095        4,0 $inner.ok -padx 2 -width .9i -fill y
2096    blt::table configure $inner r3 -height 4
2097    blt::table configure $inner r4 -pady 4
2098    raise $inner.image_button
2099    $inner.vtk_button invoke
2100    return $inner
2101}
2102
2103itcl::body Rappture::VtkIsosurfaceViewer::SetObjectStyle { dataobj comp } {
2104    # Parse style string.
2105    set tag $dataobj-$comp
2106    array set style {
2107        -color BCGYR
2108        -edges 0
2109        -edgecolor black
2110        -linewidth 1.0
2111        -opacity 0.6
2112        -wireframe 0
2113        -lighting 1
2114        -outline 0
2115        -levels 10
2116    }
2117    array set style [$dataobj style $comp]
2118    if { $dataobj != $_first || $style(-levels) == 1 } {
2119        set style(-opacity) 1
2120    }
2121    SendCmd "cutplane add $tag"
2122    SendCmd "cutplane visible 0 $tag"
2123
2124    # This is too complicated.  We want to set the colormap, number of
2125    # isolines and opacity for the dataset.  They can be the default values,
2126    # the style hints loaded with the dataset, or set by user controls.  As
2127    # datasets get loaded, they first use the defaults that are overidden
2128    # by the style hints.  If the user changes the global controls, then that
2129    # overrides everything else.  I don't know what it means when global
2130    # controls are specified as style hints by each dataset.  It complicates
2131    # the code to handle aberrant cases.
2132
2133    if { $_changed(isosurfaceOpacity) } {
2134        set style(-opacity) $_settings(isosurfaceOpacity)
2135    }
2136    if { $_changed(numContours) } {
2137        set style(-levels) $_settings(numContours)
2138    }
2139    if { $_changed(colormap) } {
2140        set style(-color) $_settings(colormap)
2141    }
2142    if { $_currentColormap == "" } {
2143        SetCurrentColormap $style(-color)
2144        $itk_component(colormap) value $style(-color)
2145    }
2146    set _currentOpacity $style(-opacity)
2147    if { $_currentNumContours != $style(-levels) } {
2148        set _currentNumContours $style(-levels)
2149        if { $_currentNumContours < 1 } {
2150            set _currentNumContours 1
2151        }
2152        set _settings(numContours) $_currentNumContours
2153        $itk_component(numcontours) value $_currentNumContours
2154        UpdateContourList
2155        DrawLegend
2156    }
2157    SendCmd [list contour3d add contourlist $_contourList $tag]
2158    SendCmd "contour3d edges $style(-edges) $tag"
2159    SendCmd "outline add $tag"
2160    SendCmd "outline color [Color2RGB $itk_option(-plotforeground)] $tag"
2161    SendCmd "outline visible $style(-outline) $tag"
2162    set _settings(isosurfaceOutline) $style(-outline)
2163    set _settings(isosurfaceEdges) $style(-edges)
2164    #SendCmd "contour3d color [Color2RGB $settings(-color)] $tag"
2165    SendCmd "contour3d lighting $style(-lighting) $tag"
2166    set _settings(isosurfaceLighting) $style(-lighting)
2167    SendCmd "contour3d linecolor [Color2RGB $style(-edgecolor)] $tag"
2168    SendCmd "contour3d linewidth $style(-linewidth) $tag"
2169    SendCmd "contour3d opacity $_currentOpacity $tag"
2170    set _settings(isosurfaceOpacity) $style(-opacity)
2171    SetCurrentColormap $style(-color)
2172    SendCmd "contour3d wireframe $style(-wireframe) $tag"
2173    set _settings(isosurfaceWireframe) $style(-wireframe)
2174    set _settings(isosurfaceOpacity) [expr $style(-opacity) * 100.0]
2175}
2176
2177itcl::body Rappture::VtkIsosurfaceViewer::IsValidObject { dataobj } {
2178    if {[catch {$dataobj isa Rappture::Field} valid] != 0 || !$valid} {
2179        return 0
2180    }
2181    return 1
2182}
2183
2184#
2185# EnterLegend --
2186#
2187itcl::body Rappture::VtkIsosurfaceViewer::EnterLegend { x y } {
2188    SetLegendTip $x $y
2189}
2190
2191#
2192# MotionLegend --
2193#
2194itcl::body Rappture::VtkIsosurfaceViewer::MotionLegend { x y } {
2195    Rappture::Tooltip::tooltip cancel
2196    set c $itk_component(view)
2197    set cw [winfo width $c]
2198    set ch [winfo height $c]
2199    if { $x >= 0 && $x < $cw && $y >= 0 && $y < $ch } {
2200        SetLegendTip $x $y
2201    }
2202}
2203
2204#
2205# LeaveLegend --
2206#
2207itcl::body Rappture::VtkIsosurfaceViewer::LeaveLegend { } {
2208    Rappture::Tooltip::tooltip cancel
2209    .rappturetooltip configure -icon ""
2210}
2211
2212#
2213# SetLegendTip --
2214#
2215itcl::body Rappture::VtkIsosurfaceViewer::SetLegendTip { x y } {
2216    set fname $_curFldName
2217    set c $itk_component(view)
2218    set w [winfo width $c]
2219    set h [winfo height $c]
2220
2221    set font "Arial 8"
2222    set lineht [font metrics $font -linespace]
2223   
2224    set ih [image height $_image(legend)]
2225    set iy [expr $y - ($lineht + 2)]
2226
2227    if { [string match "component*" $fname] } {
2228        set title ""
2229    } else {
2230        if { [info exists _fields($fname)] } {
2231            foreach { title units } $_fields($fname) break
2232            if { $units != "" } {
2233                set title [format "%s (%s)" $title $units]
2234            }
2235        } else {
2236            set title $fname
2237        }
2238    }
2239    # If there's a legend title, increase the offset by the line height.
2240    if { $title != "" } {
2241        incr iy -$lineht
2242    }
2243    # Make a swatch of the selected color
2244    if { [catch { $_image(legend) get 10 $iy } pixel] != 0 } {
2245        return
2246    }
2247    if { ![info exists _image(swatch)] } {
2248        set _image(swatch) [image create photo -width 24 -height 24]
2249    }
2250    set color [eval format "\#%02x%02x%02x" $pixel]
2251    $_image(swatch) put black  -to 0 0 23 23
2252    $_image(swatch) put $color -to 1 1 22 22
2253    .rappturetooltip configure -icon $_image(swatch)
2254
2255    # Compute the value of the point
2256    if { [info exists _limits($_curFldName)] } {
2257        foreach { vmin vmax } $_limits($_curFldName) break
2258        set t [expr 1.0 - (double($iy) / double($ih-1))]
2259        set value [expr $t * ($vmax - $vmin) + $vmin]
2260    } else {
2261        set value 0.0
2262    }
2263    set tx [expr $x + 15]
2264    set ty [expr $y - 5]
2265    if { [info exists _isolines($y)] } {
2266        Rappture::Tooltip::text $c [format "$title %g (isosurface)" $_isolines($y)]
2267    } else {
2268        Rappture::Tooltip::text $c [format "$title %g" $value]
2269    }
2270    Rappture::Tooltip::tooltip show $c +$tx,+$ty   
2271}
2272
2273
2274# ----------------------------------------------------------------------
2275# USAGE: Slice move x|y|z <newval>
2276#
2277# Called automatically when the user drags the slider to move the
2278# cut plane that slices 3D data.  Gets the current value from the
2279# slider and moves the cut plane to the appropriate point in the
2280# data set.
2281# ----------------------------------------------------------------------
2282itcl::body Rappture::VtkIsosurfaceViewer::Slice {option args} {
2283    switch -- $option {
2284        "move" {
2285            set axis [lindex $args 0]
2286            set newval [lindex $args 1]
2287            if {[llength $args] != 2} {
2288                error "wrong # args: should be \"Slice move x|y|z newval\""
2289            }
2290            set newpos [expr {0.01*$newval}]
2291            SendCmd "cutplane slice $axis $newpos"
2292        }
2293        "tooltip" {
2294            set axis [lindex $args 0]
2295            set val [$itk_component(${axis}position) get]
2296            return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
2297        }
2298        default {
2299            error "bad option \"$option\": should be axis, move, or tooltip"
2300        }
2301    }
2302}
2303
2304#
2305# ReceiveLegend --
2306#
2307#       Invoked automatically whenever the "legend" command comes in from
2308#       the rendering server.  Indicates that binary image data with the
2309#       specified <size> will follow.
2310#
2311itcl::body Rappture::VtkIsosurfaceViewer::ReceiveLegend { colormap title min max size } {
2312    #puts stderr "ReceiveLegend colormap=$colormap title=$title range=$min,$max size=$size"
2313    set _title $title
2314    regsub {\(mag\)} $title "" _title
2315    if { [IsConnected] } {
2316        set bytes [ReceiveBytes $size]
2317        if { ![info exists _image(legend)] } {
2318            set _image(legend) [image create photo]
2319        }
2320        $_image(legend) configure -data $bytes
2321        #puts stderr "read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
2322        if { [catch {DrawLegend} errs] != 0 } {
2323            global errorInfo
2324            puts stderr "errs=$errs errorInfo=$errorInfo"
2325        }
2326    }
2327}
2328
2329#
2330# DrawLegend --
2331#
2332#       Draws the legend in the own canvas on the right side of the plot area.
2333#
2334itcl::body Rappture::VtkIsosurfaceViewer::DrawLegend {} {
2335    set fname $_curFldName
2336    set c $itk_component(view)
2337    set w [winfo width $c]
2338    set h [winfo height $c]
2339    set font "Arial 8"
2340    set lineht [font metrics $font -linespace]
2341   
2342    if { [string match "component*" $fname] } {
2343        set title ""
2344    } else {
2345        if { [info exists _fields($fname)] } {
2346            foreach { title units } $_fields($fname) break
2347            if { $units != "" } {
2348                set title [format "%s (%s)" $title $units]
2349            }
2350        } else {
2351            set title $fname
2352        }
2353    }
2354    set x [expr $w - 2]
2355    if { !$_settings(legendVisible) } {
2356        $c delete legend
2357        return
2358    }
2359    if { [$c find withtag "legend"] == "" } {
2360        set y 2
2361        # If there's a legend title, create a text item for the title.
2362        $c create text $x $y \
2363                -anchor ne \
2364                -fill $itk_option(-plotforeground) -tags "title legend" \
2365                -font $font
2366            incr y $lineht
2367        $c create text $x $y \
2368            -anchor ne \
2369            -fill $itk_option(-plotforeground) -tags "vmax legend" \
2370            -font $font
2371        incr y $lineht
2372        $c create image $x $y \
2373            -anchor ne \
2374            -image $_image(legend) -tags "colormap legend"
2375        $c create rectangle $x $y 1 1 \
2376            -fill "" -outline "" -tags "sensor legend"
2377        $c create text $x [expr {$h-2}] \
2378            -anchor se \
2379            -fill $itk_option(-plotforeground) -tags "vmin legend" \
2380            -font $font
2381        $c bind sensor <Enter> [itcl::code $this EnterLegend %x %y]
2382        $c bind sensor <Leave> [itcl::code $this LeaveLegend]
2383        $c bind sensor <Motion> [itcl::code $this MotionLegend %x %y]
2384    }
2385    $c delete isoline
2386    set x2 $x
2387    set iw [image width $_image(legend)]
2388    set ih [image height $_image(legend)]
2389    set x1 [expr $x2 - ($iw*12)/10]
2390    set color $_settings(isolineColor)
2391    # Draw the isolines on the legend.
2392    array unset _isolines
2393    if { $color != "none"  && [info exists _limits($_curFldName)] &&
2394         $_settings(numContours) > 0 } {
2395
2396        foreach { vmin vmax } $_limits($_curFldName) break
2397        set range [expr double($vmax - $vmin)]
2398        if { $range <= 0.0 } {
2399            set range 1.0;              # Min is greater or equal to max.
2400        }
2401        set tags "isoline legend"
2402        set offset [expr 2 + $lineht]
2403        if { $title != "" } {
2404            incr offset $lineht
2405        }
2406        foreach value $_contourList {
2407            set norm [expr 1.0 - (($value - $vmin) / $range)]
2408            set y1 [expr int(round(($norm * $ih) + $offset))]
2409            for { set off 0 } { $off < 3 } { incr off } {
2410                set _isolines([expr $y1 + $off]) $value
2411                set _isolines([expr $y1 - $off]) $value
2412            }
2413            $c create line $x1 $y1 $x2 $y1 -fill $color -tags $tags
2414        }
2415    }
2416
2417    $c bind title <ButtonPress> [itcl::code $this Combo post]
2418    $c bind title <Enter> [itcl::code $this Combo activate]
2419    $c bind title <Leave> [itcl::code $this Combo deactivate]
2420    # Reset the item coordinates according the current size of the plot.
2421    $c itemconfigure title -text $title
2422    if { [info exists _limits($_curFldName)] } {
2423        foreach { vmin vmax } $_limits($_curFldName) break
2424        $c itemconfigure vmin -text [format %g $vmin]
2425        $c itemconfigure vmax -text [format %g $vmax]
2426    }
2427    set y 2
2428    # If there's a legend title, move the title to the correct position
2429    if { $title != "" } {
2430        $c itemconfigure title -text $title
2431        $c coords title $x $y
2432        incr y $lineht
2433        $c raise title
2434    }
2435    $c coords vmax $x $y
2436    incr y $lineht
2437    $c coords colormap $x $y
2438    $c coords sensor [expr $x - $iw] $y $x [expr $y + $ih]
2439    $c raise sensor
2440    $c coords vmin $x [expr {$h - 2}]
2441}
2442
2443# ----------------------------------------------------------------------
2444# USAGE: _dropdown post
2445# USAGE: _dropdown unpost
2446# USAGE: _dropdown select
2447#
2448# Used internally to handle the dropdown list for this combobox.  The
2449# post/unpost options are invoked when the list is posted or unposted
2450# to manage the relief of the controlling button.  The select option
2451# is invoked whenever there is a selection from the list, to assign
2452# the value back to the gauge.
2453# ----------------------------------------------------------------------
2454itcl::body Rappture::VtkIsosurfaceViewer::Combo {option} {
2455    set c $itk_component(view)
2456    switch -- $option {
2457        post {
2458            foreach { x1 y1 x2 y2 } [$c bbox title] break
2459            set cw [winfo width $itk_component(view)]
2460            set mw [winfo reqwidth $itk_component(fieldmenu)]
2461            set x1 [expr $cw - $mw]
2462            set x [expr $x1 + [winfo rootx $itk_component(view)]]
2463            set y [expr $y2 + [winfo rooty $itk_component(view)]]
2464            tk_popup $itk_component(fieldmenu) $x $y
2465        }
2466        activate {
2467            $c itemconfigure title -fill red
2468        }
2469        deactivate {
2470            $c itemconfigure title -fill $itk_option(-plotforeground)
2471        }
2472        invoke {
2473            $itk_component(field) value $_curFldLabel
2474            AdjustSetting field
2475        }
2476        default {
2477            error "bad option \"$option\": should be post, unpost, select"
2478        }
2479    }
2480}
2481
2482#
2483# SetCurrentColormap --
2484#
2485itcl::body Rappture::VtkIsosurfaceViewer::SetCurrentColormap { name } {
2486    # Keep track of the colormaps that we build.
2487    if { ![info exists _colormaps($name)] } {
2488        BuildColormap $name
2489        set _colormaps($name) 1
2490    }
2491    set _currentColormap $name
2492    SendCmd "contour3d colormap $_currentColormap"
2493    SendCmd "cutplane colormap $_currentColormap"
2494}
2495
2496#
2497# BuildColormap --
2498#
2499#       Build the designated colormap on the server.
2500#
2501itcl::body Rappture::VtkIsosurfaceViewer::BuildColormap { name } {
2502    set cmap [ColorsToColormap $name]
2503    if { [llength $cmap] == 0 } {
2504        set cmap "0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0"
2505    }
2506    set wmap "0.0 1.0 1.0 1.0"
2507    SendCmd "colormap add $name { $cmap } { $wmap }"
2508}
2509
2510itcl::body Rappture::VtkIsosurfaceViewer::SetOrientation { side } {
2511    array set positions {
2512        front "1 0 0 0"
2513        back  "0 0 1 0"
2514        left  "0.707107 0 -0.707107 0"
2515        right "0.707107 0 0.707107 0"
2516        top   "0.707107 -0.707107 0 0"
2517        bottom "0.707107 0.707107 0 0"
2518    }
2519    foreach name { qw qx qy qz } value $positions($side) {
2520        set _view($name) $value
2521    }
2522    set q [list $_view(qw) $_view(qx) $_view(qy) $_view(qz)]
2523    $_arcball quaternion $q
2524    SendCmd "camera orient $q"
2525    SendCmd "camera reset"
2526    set _view(xpan) 0
2527    set _view(ypan) 0
2528    set _view(zoom) 1.0
2529}
2530
2531itcl::body Rappture::VtkIsosurfaceViewer::UpdateContourList {} {
2532    if { ![info exists _limits($_curFldName)] } {
2533        return
2534    }
2535    foreach { vmin vmax } $_limits($_curFldName) break
2536    set v [blt::vector create \#auto]
2537    $v seq $vmin $vmax [expr $_currentNumContours+2]
2538    $v delete end 0
2539    set _contourList [$v range 0 end]
2540    blt::vector destroy $v
2541}
Note: See TracBrowser for help on using the repository browser.