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

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

merge r4767 from trunk

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