source: tags/1.3.5/gui/scripts/vtkisosurfaceviewer.tcl @ 4752

Last change on this file since 4752 was 4752, checked in by ldelgass, 7 years ago

backport vtkisosurface viewer from 1.3 branch head

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