source: branches/1.4/gui/scripts/nanovisviewer.tcl @ 5385

Last change on this file since 5385 was 5385, checked in by ldelgass, 9 years ago

merge 5372 from trunk

File size: 77.2 KB
Line 
1# -*- mode: tcl; indent-tabs-mode: nil -*-
2# ----------------------------------------------------------------------
3#  COMPONENT: nanovisviewer - 3D volume rendering
4#
5#  This widget performs volume rendering on 3D scalar/vector datasets.
6#  It connects to the Nanovis server running on a rendering farm,
7#  transmits data, and displays the results.
8# ======================================================================
9#  AUTHOR:  Michael McLennan, Purdue University
10#  Copyright (c) 2004-2012  HUBzero Foundation, LLC
11#
12#  See the file "license.terms" for information on usage and
13#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
14# ======================================================================
15package require Itk
16package require BLT
17package require Img
18
19option add *NanovisViewer.width 4i widgetDefault
20option add *NanovisViewer*cursor crosshair widgetDefault
21option add *NanovisViewer.height 4i widgetDefault
22option add *NanovisViewer.foreground black widgetDefault
23option add *NanovisViewer.controlBackground gray widgetDefault
24option add *NanovisViewer.controlDarkBackground #999999 widgetDefault
25option add *NanovisViewer.plotBackground black widgetDefault
26option add *NanovisViewer.plotForeground white widgetDefault
27option add *NanovisViewer.plotOutline gray widgetDefault
28option add *NanovisViewer.font \
29    -*-helvetica-medium-r-normal-*-12-* widgetDefault
30
31# must use this name -- plugs into Rappture::resources::load
32proc NanovisViewer_init_resources {} {
33    Rappture::resources::register \
34        nanovis_server Rappture::NanovisViewer::SetServerList
35}
36
37itcl::class Rappture::NanovisViewer {
38    inherit Rappture::VisViewer
39
40    itk_option define -plotforeground plotForeground Foreground ""
41    itk_option define -plotbackground plotBackground Background ""
42    itk_option define -plotoutline plotOutline PlotOutline ""
43
44    constructor { hostlist args } {
45        Rappture::VisViewer::constructor $hostlist
46    } {
47        # defined below
48    }
49    destructor {
50        # defined below
51    }
52    public proc SetServerList { namelist } {
53        Rappture::VisViewer::SetServerList "nanovis" $namelist
54    }
55    public method add {dataobj {settings ""}}
56    public method camera {option args}
57    public method delete {args}
58    public method disconnect {}
59    public method download {option args}
60    public method get {args}
61    public method isconnected {}
62    public method parameters {title args} {
63        # do nothing
64    }
65    public method scale {args}
66    public method updateTransferFunctions {}
67
68    # The following methods are only used by this class.
69    private method AddNewMarker { x y }
70    private method AdjustSetting {what {value ""}}
71    private method BuildCameraTab {}
72    private method BuildCutplanesTab {}
73    private method BuildViewTab {}
74    private method BuildVolumeComponents {}
75    private method BuildVolumeTab {}
76    private method ComputeAlphamap { cname }
77    private method ComputeTransferFunction { cname }
78    private method Connect {}
79    private method CurrentDatasets {{what -all}}
80    private method Disconnect {}
81    private method DoResize {}
82    private method DrawLegend { cname }
83    private method EventuallyRedrawLegend { }
84    private method EventuallyResize { w h }
85    private method FixLegend {}
86    private method GetColormap { cname color }
87    private method GetDatasetsWithComponent { cname }
88    private method HideAllMarkers {}
89    private method InitComponentSettings { cname }
90    private method InitSettings { args }
91    private method NameTransferFunction { dataobj comp }
92    private method Pan {option x y}
93    private method PanCamera {}
94    private method ParseLevelsOption { cname levels }
95    private method ParseMarkersOption { cname markers }
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 ReceiveData { args }
101    private method ReceiveImage { args }
102    private method ReceiveLegend { tf vmin vmax size }
103    private method RemoveMarker { x y }
104    private method ResetColormap { cname color }
105    private method Rotate {option x y}
106    private method SendTransferFunctions {}
107    private method SetObjectStyle { dataobj cname }
108    private method SetOrientation { side }
109    private method Slice {option args}
110    private method SlicerTip {axis}
111    private method SwitchComponent { cname }
112    private method ViewToQuaternion {} {
113        return [list $_view(-qw) $_view(-qx) $_view(-qy) $_view(-qz)]
114    }
115    private method Zoom {option}
116
117    private variable _arcball ""
118    private variable _dlist ""         ;# list of data objects
119    private variable _obj2ovride       ;# maps dataobj => style override
120    private variable _serverDatasets   ;# contains all the dataobj-component
121                                       ;# to volumes in the server
122    private variable _recvdDatasets    ;# list of data objs to send to server
123
124    private variable _reset 1          ;# Connection to server has been reset.
125    private variable _click            ;# Info used for rotate operations.
126    private variable _limits           ;# Autoscale min/max for all axes
127    private variable _view             ;# View params for 3D view
128    private variable _parsedFunction
129    private variable _transferFunctionEditors
130    private variable _settings
131    private variable _first ""         ;# This is the topmost volume.
132    private variable _current ""       ;# Currently selected component
133    private variable _volcomponents    ;# Maps component name to list of
134                                       ;# dataobj-component tags
135    private variable _componentsList   ;# List of components found
136    private variable _cname2transferFunction
137    private variable _cname2defaultcolormap
138    private variable _width 0
139    private variable _height 0
140    private variable _resizePending 0
141    private variable _resizeLegendPending 0
142
143    private common _downloadPopup      ;# download options from popup
144    private common _hardcopy
145}
146
147itk::usual NanovisViewer {
148    keep -background -foreground -cursor -font
149    keep -plotbackground -plotforeground
150}
151
152# ----------------------------------------------------------------------
153# CONSTRUCTOR
154# ----------------------------------------------------------------------
155itcl::body Rappture::NanovisViewer::constructor {hostlist args} {
156    set _serverType "nanovis"
157
158    # Draw legend event
159    $_dispatcher register !legend
160    $_dispatcher dispatch $this !legend "[itcl::code $this FixLegend]; list"
161
162    # Send transfer functions event
163    $_dispatcher register !send_transfunc
164    $_dispatcher dispatch $this !send_transfunc \
165        "[itcl::code $this SendTransferFunctions]; list"
166
167    # Rebuild event
168    $_dispatcher register !rebuild
169    $_dispatcher dispatch $this !rebuild "[itcl::code $this Rebuild]; list"
170
171    # Resize event
172    $_dispatcher register !resize
173    $_dispatcher dispatch $this !resize "[itcl::code $this DoResize]; list"
174
175    #
176    # Populate parser with commands handle incoming requests
177    #
178    $_parser alias image [itcl::code $this ReceiveImage]
179    $_parser alias legend [itcl::code $this ReceiveLegend]
180    $_parser alias data [itcl::code $this ReceiveData]
181
182    # Initialize the view to some default parameters.
183    array set _view {
184        -qw      0.853553
185        -qx      -0.353553
186        -qy      0.353553
187        -qz      0.146447
188        -xpan    0
189        -ypan    0
190        -zoom    1.0
191    }
192    set _arcball [blt::arcball create 100 100]
193    $_arcball quaternion [ViewToQuaternion]
194
195    set _limits(v) [list 0.0 1.0]
196    set _reset 1
197
198    array set _settings {
199        -axesvisible            1
200        -background             black
201        -colormap               "default"
202        -cutplanesvisible       0
203        -gridvisible            0
204        -isosurfaceshading      0
205        -legendvisible          1
206        -light                  40
207        -light2side             1
208        -opacity                50
209        -outlinevisible         0
210        -qw                     0.853553
211        -qx                     -0.353553
212        -qy                     0.353553
213        -qz                     0.146447
214        -thickness              350
215        -volume                 1
216        -volumevisible          1
217        -xcutplaneposition      50
218        -xcutplanevisible       1
219        -xpan                   0
220        -ycutplaneposition      50
221        -ycutplanevisible       1
222        -ypan                   0
223        -zcutplaneposition      50
224        -zcutplanevisible       1
225        -zoom                   1.0
226    }
227
228    itk_component add 3dview {
229        label $itk_component(plotarea).view -image $_image(plot) \
230            -highlightthickness 0 -borderwidth 0
231    } {
232        usual
233        ignore -highlightthickness -borderwidth  -background
234    }
235    bind $itk_component(3dview) <Control-F1> [itcl::code $this ToggleConsole]
236
237    set f [$itk_component(main) component controls]
238    itk_component add reset {
239        button $f.reset -borderwidth 1 -padx 1 -pady 1 \
240            -highlightthickness 0 \
241            -image [Rappture::icon reset-view] \
242            -command [itcl::code $this Zoom reset]
243    } {
244        usual
245        ignore -highlightthickness
246    }
247    pack $itk_component(reset) -side top -padx 2 -pady 2
248    Rappture::Tooltip::for $itk_component(reset) \
249        "Reset the view to the default zoom level"
250
251    itk_component add zoomin {
252        button $f.zin -borderwidth 1 -padx 1 -pady 1 \
253            -highlightthickness 0 \
254            -image [Rappture::icon zoom-in] \
255            -command [itcl::code $this Zoom in]
256    } {
257        usual
258        ignore -highlightthickness
259    }
260    pack $itk_component(zoomin) -side top -padx 2 -pady 2
261    Rappture::Tooltip::for $itk_component(zoomin) "Zoom in"
262
263    itk_component add zoomout {
264        button $f.zout -borderwidth 1 -padx 1 -pady 1 \
265            -highlightthickness 0 \
266            -image [Rappture::icon zoom-out] \
267            -command [itcl::code $this Zoom out]
268    } {
269        usual
270        ignore -highlightthickness
271    }
272    pack $itk_component(zoomout) -side top -padx 2 -pady 2
273    Rappture::Tooltip::for $itk_component(zoomout) "Zoom out"
274
275    itk_component add volume {
276        Rappture::PushButton $f.volume \
277            -onimage [Rappture::icon volume-on] \
278            -offimage [Rappture::icon volume-off] \
279            -command [itcl::code $this AdjustSetting -volume] \
280            -variable [itcl::scope _settings(-volume)]
281    }
282    $itk_component(volume) select
283    Rappture::Tooltip::for $itk_component(volume) \
284        "Toggle the volume cloud on/off"
285    pack $itk_component(volume) -padx 2 -pady 2
286
287    itk_component add cutplane {
288        Rappture::PushButton $f.cutplane \
289            -onimage [Rappture::icon cutbutton] \
290            -offimage [Rappture::icon cutbutton] \
291            -variable [itcl::scope _settings(-cutplanesvisible)] \
292            -command [itcl::code $this AdjustSetting -cutplanesvisible]
293    }
294    Rappture::Tooltip::for $itk_component(cutplane) \
295        "Show/Hide cutplanes"
296    pack $itk_component(cutplane) -padx 2 -pady 2
297
298    if { [catch {
299        BuildViewTab
300        BuildVolumeTab
301        BuildCutplanesTab
302        BuildCameraTab
303    } errs] != 0 } {
304        global errorInfo
305        puts stderr "errs=$errs errorInfo=$errorInfo"
306    }
307
308    # Legend
309    set _image(legend) [image create photo]
310    itk_component add legend {
311        canvas $itk_component(plotarea).legend -height 50 -highlightthickness 0
312    } {
313        usual
314        ignore -highlightthickness
315        rename -background -plotbackground plotBackground Background
316    }
317    bind $itk_component(legend) <Configure> \
318        [itcl::code $this EventuallyRedrawLegend]
319    bind $itk_component(legend) <KeyPress-Delete> \
320        [itcl::code $this RemoveMarker %x %y]
321    bind $itk_component(legend) <Enter> \
322        [list focus $itk_component(legend)]
323
324    # Hack around the Tk panewindow.  The problem is that the requested
325    # size of the 3d view isn't set until an image is retrieved from
326    # the server.  So the panewindow uses the tiny size.
327    set w 10000
328    pack forget $itk_component(3dview)
329    blt::table $itk_component(plotarea) \
330        0,0 $itk_component(3dview) -fill both -reqwidth $w \
331        1,0 $itk_component(legend) -fill x
332    blt::table configure $itk_component(plotarea) r1 -resize none
333
334    # Bindings for rotation via mouse
335    bind $itk_component(3dview) <ButtonPress-1> \
336        [itcl::code $this Rotate click %x %y]
337    bind $itk_component(3dview) <B1-Motion> \
338        [itcl::code $this Rotate drag %x %y]
339    bind $itk_component(3dview) <ButtonRelease-1> \
340        [itcl::code $this Rotate release %x %y]
341    bind $itk_component(3dview) <Configure> \
342        [itcl::code $this EventuallyResize %w %h]
343
344    # Bindings for panning via mouse
345    bind $itk_component(3dview) <ButtonPress-2> \
346        [itcl::code $this Pan click %x %y]
347    bind $itk_component(3dview) <B2-Motion> \
348        [itcl::code $this Pan drag %x %y]
349    bind $itk_component(3dview) <ButtonRelease-2> \
350        [itcl::code $this Pan release %x %y]
351
352    # Bindings for panning via keyboard
353    bind $itk_component(3dview) <KeyPress-Left> \
354        [itcl::code $this Pan set -10 0]
355    bind $itk_component(3dview) <KeyPress-Right> \
356        [itcl::code $this Pan set 10 0]
357    bind $itk_component(3dview) <KeyPress-Up> \
358        [itcl::code $this Pan set 0 -10]
359    bind $itk_component(3dview) <KeyPress-Down> \
360        [itcl::code $this Pan set 0 10]
361    bind $itk_component(3dview) <Shift-KeyPress-Left> \
362        [itcl::code $this Pan set -2 0]
363    bind $itk_component(3dview) <Shift-KeyPress-Right> \
364        [itcl::code $this Pan set 2 0]
365    bind $itk_component(3dview) <Shift-KeyPress-Up> \
366        [itcl::code $this Pan set 0 -2]
367    bind $itk_component(3dview) <Shift-KeyPress-Down> \
368        [itcl::code $this Pan set 0 2]
369
370    # Bindings for zoom via keyboard
371    bind $itk_component(3dview) <KeyPress-Prior> \
372        [itcl::code $this Zoom out]
373    bind $itk_component(3dview) <KeyPress-Next> \
374        [itcl::code $this Zoom in]
375
376    bind $itk_component(3dview) <Enter> "focus $itk_component(3dview)"
377
378    if {[string equal "x11" [tk windowingsystem]]} {
379        # Bindings for zoom via mouse
380        bind $itk_component(3dview) <4> [itcl::code $this Zoom out]
381        bind $itk_component(3dview) <5> [itcl::code $this Zoom in]
382    }
383
384    set _image(download) [image create photo]
385
386    eval itk_initialize $args
387
388    EnableWaitDialog 900
389    Connect
390}
391
392# ----------------------------------------------------------------------
393# DESTRUCTOR
394# ----------------------------------------------------------------------
395itcl::body Rappture::NanovisViewer::destructor {} {
396    $_dispatcher cancel !rebuild
397    $_dispatcher cancel !send_transfunc
398    $_dispatcher cancel !resize
399    image delete $_image(plot)
400    image delete $_image(legend)
401    image delete $_image(download)
402    foreach cname [array names _transferFunctionEditors] {
403        itcl::delete object $_transferFunctionEditors($cname)
404    }
405    catch { blt::arcball destroy $_arcball }
406    array unset _settings
407}
408
409# ----------------------------------------------------------------------
410# USAGE: add <dataobj> ?<settings>?
411#
412# Clients use this to add a data object to the plot.  The optional
413# <settings> are used to configure the plot.  Allowed settings are
414# -color, -brightness, -width, -linestyle, and -raise.
415# ----------------------------------------------------------------------
416itcl::body Rappture::NanovisViewer::add {dataobj {settings ""}} {
417    if { ![$dataobj isvalid] } {
418        return;                         # Object doesn't contain valid data.
419    }
420    array set params {
421        -color auto
422        -width 1
423        -linestyle solid
424        -brightness 0
425        -raise 0
426        -description ""
427        -param ""
428    }
429    array set params $settings
430
431    if {$params(-color) == "auto" || $params(-color) == "autoreset"} {
432        # can't handle -autocolors yet
433        set params(-color) black
434    }
435    set pos [lsearch -exact $_dlist $dataobj]
436    if {$pos < 0} {
437        lappend _dlist $dataobj
438        set _obj2ovride($dataobj-color) $params(-color)
439        set _obj2ovride($dataobj-width) $params(-width)
440        set _obj2ovride($dataobj-raise) $params(-raise)
441        $_dispatcher event -idle !rebuild
442    }
443}
444
445# ----------------------------------------------------------------------
446# USAGE: get ?-objects?
447# USAGE: get ?-image 3dview|legend?
448#
449# Clients use this to query the list of objects being plotted, in
450# order from bottom to top of this result.  The optional "-image"
451# flag can also request the internal images being shown.
452# ----------------------------------------------------------------------
453itcl::body Rappture::NanovisViewer::get {args} {
454    if {[llength $args] == 0} {
455        set args "-objects"
456    }
457
458    set op [lindex $args 0]
459    switch -- $op {
460        -objects {
461            # put the dataobj list in order according to -raise options
462            set dlist $_dlist
463            foreach dataobj $dlist {
464                if {[info exists _obj2ovride($dataobj-raise)] &&
465                    $_obj2ovride($dataobj-raise)} {
466                    set i [lsearch -exact $dlist $dataobj]
467                    if {$i >= 0} {
468                        set dlist [lreplace $dlist $i $i]
469                        lappend dlist $dataobj
470                    }
471                }
472            }
473            return $dlist
474        }
475        -image {
476            if {[llength $args] != 2} {
477                error "wrong # args: should be \"get -image 3dview|legend\""
478            }
479            switch -- [lindex $args end] {
480                3dview {
481                    return $_image(plot)
482                }
483                legend {
484                    return $_image(legend)
485                }
486                default {
487                    error "bad image name \"[lindex $args end]\": should be 3dview or legend"
488                }
489            }
490        }
491        default {
492            error "bad option \"$op\": should be -objects or -image"
493        }
494    }
495}
496
497# ----------------------------------------------------------------------
498# USAGE: delete ?<dataobj1> <dataobj2> ...?
499#
500#       Clients use this to delete a dataobj from the plot.  If no dataobjs
501#       are specified, then all dataobjs are deleted.  No data objects are
502#       deleted.  They are only removed from the display list.
503#
504# ----------------------------------------------------------------------
505itcl::body Rappture::NanovisViewer::delete {args} {
506    if {[llength $args] == 0} {
507        set args $_dlist
508    }
509    # Delete all specified dataobjs
510    set changed 0
511    foreach dataobj $args {
512        set pos [lsearch -exact $_dlist $dataobj]
513        if { $pos >= 0 } {
514            set _dlist [lreplace $_dlist $pos $pos]
515            array unset _obj2ovride $dataobj-*
516            set changed 1
517        }
518    }
519    # If anything changed, then rebuild the plot
520    if {$changed} {
521        $_dispatcher event -idle !rebuild
522    }
523}
524
525# ----------------------------------------------------------------------
526# USAGE: scale ?<data1> <data2> ...?
527#
528# Sets the default limits for the overall plot according to the
529# limits of the data for all of the given <data> objects.  This
530# accounts for all objects--even those not showing on the screen.
531# Because of this, the limits are appropriate for all objects as
532# the user scans through data in the ResultSet viewer.
533# ----------------------------------------------------------------------
534itcl::body Rappture::NanovisViewer::scale {args} {
535    array set style {
536        -color    BCGYR
537        -levels   6
538        -markers  ""
539    }
540    array unset _limits
541    array unset _volcomponents
542    foreach dataobj $args {
543        if { ![$dataobj isvalid] } {
544            continue;                     # Object doesn't contain valid data.
545        }
546        foreach cname [$dataobj components] {
547            if { ![info exists _volcomponents($cname)] } {
548                lappend _componentsList $cname
549                array set style [lindex [$dataobj components -style $cname] 0]
550                set cmap [ColorsToColormap $style(-color)]
551                set _cname2defaultcolormap($cname) $cmap
552                set _settings($cname-colormap) $style(-color)
553            }
554            lappend _volcomponents($cname) $dataobj-$cname
555            array unset limits
556            array set limits [$dataobj valueLimits $cname]
557            set _limits($cname) $limits(v)
558        }
559        foreach axis {x y z v} {
560            foreach { min max } [$dataobj limits $axis] break
561            if {"" != $min && "" != $max} {
562                if { ![info exists _limits($axis)] } {
563                    set _limits($axis) [list $min $max]
564                    continue
565                }
566                foreach {amin amax} $_limits($axis) break
567                if {$min < $amin} {
568                    set amin $min
569                }
570                if {$max > $amax} {
571                    set amax $max
572                }
573                set _limits($axis) [list $amin $amax]
574            }
575        }
576    }
577    BuildVolumeComponents
578}
579
580# ----------------------------------------------------------------------
581# USAGE: download coming
582# USAGE: download controls <downloadCommand>
583# USAGE: download now
584#
585# Clients use this method to create a downloadable representation
586# of the plot.  Returns a list of the form {ext string}, where
587# "ext" is the file extension (indicating the type of data) and
588# "string" is the data itself.
589# ----------------------------------------------------------------------
590itcl::body Rappture::NanovisViewer::download {option args} {
591    switch $option {
592        coming {
593            if {[catch {
594                blt::winop snap $itk_component(plotarea) $_image(download)
595            }]} {
596                $_image(download) configure -width 1 -height 1
597                $_image(download) put #000000
598            }
599        }
600        controls {
601            # no controls for this download yet
602            return ""
603        }
604        now {
605            # Get the image data (as base64) and decode it back to binary.
606            # This is better than writing to temporary files.  When we switch
607            # to the BLT picture image it won't be necessary to decode the
608            # image data.
609            if { [image width $_image(plot)] > 0 &&
610                 [image height $_image(plot)] > 0 } {
611                set bytes [$_image(plot) data -format "jpeg -quality 100"]
612                set bytes [Rappture::encoding::decode -as b64 $bytes]
613                return [list .jpg $bytes]
614            }
615            return ""
616        }
617        default {
618            error "bad option \"$option\": should be coming, controls, now"
619        }
620    }
621}
622
623# ----------------------------------------------------------------------
624# USAGE: Connect ?<host:port>,<host:port>...?
625#
626# Clients use this method to establish a connection to a new
627# server, or to reestablish a connection to the previous server.
628# Any existing connection is automatically closed.
629# ----------------------------------------------------------------------
630itcl::body Rappture::NanovisViewer::Connect {} {
631    set _hosts [GetServerList "nanovis"]
632    if { "" == $_hosts } {
633        return 0
634    }
635    set _reset 1
636    set result [VisViewer::Connect $_hosts]
637    if { $result } {
638        if { $_reportClientInfo }  {
639            # Tell the server the viewer, hub, user and session.
640            # Do this immediately on connect before buffering any commands
641            global env
642
643            set info {}
644            set user "???"
645            if { [info exists env(USER)] } {
646                set user $env(USER)
647            }
648            set session "???"
649            if { [info exists env(SESSION)] } {
650                set session $env(SESSION)
651            }
652            lappend info "version" "$Rappture::version"
653            lappend info "build" "$Rappture::build"
654            lappend info "svnurl" "$Rappture::svnurl"
655            lappend info "installdir" "$Rappture::installdir"
656            lappend info "hub" [exec hostname]
657            lappend info "client" "nanovisviewer"
658            lappend info "user" $user
659            lappend info "session" $session
660            SendCmd "clientinfo [list $info]"
661        }
662
663        set w [winfo width $itk_component(3dview)]
664        set h [winfo height $itk_component(3dview)]
665        EventuallyResize $w $h
666    }
667    return $result
668}
669
670#
671# isconnected --
672#
673#       Indicates if we are currently connected to the visualization server.
674#
675itcl::body Rappture::NanovisViewer::isconnected {} {
676    return [VisViewer::IsConnected]
677}
678
679#
680# disconnect --
681#
682itcl::body Rappture::NanovisViewer::disconnect {} {
683    Disconnect
684}
685
686#
687# Disconnect --
688#
689#       Clients use this method to disconnect from the current rendering
690#       server.
691#
692itcl::body Rappture::NanovisViewer::Disconnect {} {
693    VisViewer::Disconnect
694
695    # disconnected -- no more data sitting on server
696    array unset _serverDatasets
697}
698
699# ----------------------------------------------------------------------
700# USAGE: SendTransferFunctions
701# ----------------------------------------------------------------------
702itcl::body Rappture::NanovisViewer::SendTransferFunctions {} {
703    foreach cname [array names _volcomponents] {
704        ComputeTransferFunction $cname
705    }
706    FixLegend
707}
708
709# ----------------------------------------------------------------------
710# USAGE: ReceiveImage -bytes <size> -type <type> -token <token>
711#
712# Invoked automatically whenever the "image" command comes in from
713# the rendering server.  Indicates that binary image data with the
714# specified <size> will follow.
715# ----------------------------------------------------------------------
716itcl::body Rappture::NanovisViewer::ReceiveImage { args } {
717    array set info {
718        -token "???"
719        -bytes 0
720        -type image
721    }
722    array set info $args
723    set bytes [ReceiveBytes $info(-bytes)]
724    ReceiveEcho <<line "<read $info(-bytes) bytes"
725    if { $info(-type) == "image" } {
726        ReceiveEcho "for [image width $_image(plot)]x[image height $_image(plot)] image>"
727        $_image(plot) configure -data $bytes
728    } elseif { $info(-type) == "print" } {
729        set tag $this-print-$info(-token)
730        set _hardcopy($tag) $bytes
731    }
732}
733
734#
735# DrawLegend --
736#
737itcl::body Rappture::NanovisViewer::DrawLegend { cname } {
738    set c $itk_component(legend)
739    set w [winfo width $c]
740    set h [winfo height $c]
741    set lx 10
742    set ly [expr {$h - 1}]
743    if {"" == [$c find withtag colorbar]} {
744        $c create image 10 10 -anchor nw \
745            -image $_image(legend) -tags colorbar
746        $c create text $lx $ly -anchor sw \
747            -fill $itk_option(-plotforeground) -tags "limits text vmin"
748        $c create text [expr {$w-$lx}] $ly -anchor se \
749            -fill $itk_option(-plotforeground) -tags "limits text vmax"
750        $c create text [expr {$w/2}] $ly -anchor s \
751            -fill $itk_option(-plotforeground) -tags "limits text title"
752        $c lower colorbar
753        $c bind colorbar <ButtonRelease-1> [itcl::code $this AddNewMarker %x %y]
754    }
755
756    # Display the markers used by the current transfer function.
757    HideAllMarkers
758    $_transferFunctionEditors($cname) showMarkers $_limits($cname)
759
760    foreach {min max} $_limits($cname) break
761    $c itemconfigure vmin -text [format %g $min]
762    $c coords vmin $lx $ly
763
764    $c itemconfigure vmax -text [format %g $max]
765    $c coords vmax [expr {$w-$lx}] $ly
766
767    set title [$_first hints label]
768    set units [$_first hints units]
769    if { $units != "" } {
770        set title "$title ($units)"
771    }
772    $c itemconfigure title -text $title
773    $c coords title [expr {$w/2}] $ly
774
775    # The colormap may have changed. Resync the slicers with the colormap.
776    InitSettings -cutplanesvisible -xcutplanevisible -ycutplanevisible \
777        -zcutplanevisible
778}
779
780#
781# ReceiveLegend --
782#
783#       The procedure is the response from the render server to each "legend"
784#       command.  The server sends back a "legend" command invoked our
785#       the slave interpreter.  The purpose is to collect data of the image
786#       representing the legend in the canvas.  In addition, the
787#       active transfer function is displayed.
788#
789itcl::body Rappture::NanovisViewer::ReceiveLegend { cname vmin vmax size } {
790    if { ![isconnected] } {
791        return
792    }
793    set bytes [ReceiveBytes $size]
794    $_image(legend) configure -data $bytes
795    ReceiveEcho <<line "<read $size bytes for [image width $_image(legend)]x[image height $_image(legend)] legend>"
796
797    DrawLegend $_current
798}
799
800#
801# ReceiveData --
802#
803#       The procedure is the response from the render server to each "data
804#       follows" command.  The server sends back a "data" command invoked our
805#       the slave interpreter.  The purpose is to collect the min/max of the
806#       volume sent to the render server.  Since the client (nanovisviewer)
807#       doesn't parse 3D data formats, we rely on the server (nanovis) to
808#       tell us what the limits are.  Once we've received the limits to all
809#       the data we've sent (tracked by _recvdDatasets) we can then determine
810#       what the transfer functions are for these volumes.
811#
812#
813#       Note: There is a considerable tradeoff in having the server report
814#             back what the data limits are.  It means that much of the code
815#             having to do with transfer-functions has to wait for the data
816#             to come back, since the isomarkers are calculated based upon
817#             the data limits.  The client code is much messier because of
818#             this.  The alternative is to parse any of the 3D formats on the
819#             client side.
820#
821itcl::body Rappture::NanovisViewer::ReceiveData { args } {
822    if { ![isconnected] } {
823        return
824    }
825
826    # Arguments from server are name value pairs. Stuff them in an array.
827    array set info $args
828
829    set tag $info(tag)
830    set parts [split $tag -]
831
832    #
833    # Volumes don't exist until we're told about them.
834    #
835    set dataobj [lindex $parts 0]
836    set _serverDatasets($tag) 1
837    if { $_settings(-volumevisible) && $dataobj == $_first } {
838        SendCmd "volume state 1 $tag"
839    }
840    set _limits($tag) [list $info(min)  $info(max)]
841    set _limits(v)    [list $info(vmin) $info(vmax)]
842
843    unset _recvdDatasets($tag)
844    if { [array size _recvdDatasets] == 0 } {
845        updateTransferFunctions
846    }
847}
848
849# ----------------------------------------------------------------------
850# USAGE: Rebuild
851#
852# Called automatically whenever something changes that affects the
853# data in the widget.  Clears any existing data and rebuilds the
854# widget to display new data.
855# ----------------------------------------------------------------------
856itcl::body Rappture::NanovisViewer::Rebuild {} {
857    set w [winfo width $itk_component(3dview)]
858    set h [winfo height $itk_component(3dview)]
859    if { $w < 2 || $h < 2 } {
860        update
861        $_dispatcher event -idle !rebuild
862        return
863    }
864
865    # Turn on buffering of commands to the server.  We don't want to
866    # be preempted by a server disconnect/reconnect (which automatically
867    # generates a new call to Rebuild).
868    StartBufferingCommands
869
870    if { $_width != $w || $_height != $h || $_reset } {
871        set _width $w
872        set _height $h
873        $_arcball resize $w $h
874        DoResize
875    }
876
877    foreach dataobj [get] {
878        foreach cname [$dataobj components] {
879            set tag $dataobj-$cname
880            if { ![info exists _serverDatasets($tag)] } {
881                # Send the data as one huge base64-encoded mess -- yuck!
882                if { [$dataobj type] == "dx" } {
883                    if { ![$dataobj isvalid] } {
884                        puts stderr "??? $dataobj is invalid"
885                    }
886                    set data [$dataobj blob $cname]
887                } else {
888                    set data [$dataobj vtkdata $cname]
889                    if 0 {
890                        set f [open "/tmp/volume.vtk" "w"]
891                        fconfigure $f -translation binary -encoding binary
892                        puts -nonewline $f $data
893                        close $f
894                    }
895                }
896                set nbytes [string length $data]
897                if { $_reportClientInfo }  {
898                    set info {}
899                    lappend info "tool_id"       [$dataobj hints toolid]
900                    lappend info "tool_name"     [$dataobj hints toolname]
901                    lappend info "tool_title"    [$dataobj hints tooltitle]
902                    lappend info "tool_command"  [$dataobj hints toolcommand]
903                    lappend info "tool_revision" [$dataobj hints toolrevision]
904                    lappend info "dataset_label" [$dataobj hints label]
905                    lappend info "dataset_size"  $nbytes
906                    lappend info "dataset_tag"   $tag
907                    SendCmd "clientinfo [list $info]"
908                }
909                SendCmd "volume data follows $nbytes $tag"
910                SendData $data
911                set _recvdDatasets($tag) 1
912                set _serverDatasets($tag) 0
913            }
914            SetObjectStyle $dataobj $cname
915        }
916    }
917
918    # Outline seems to need to be reset every update.
919    InitSettings -outlinevisible -cutplanesvisible -current
920
921    set _first [lindex [get] 0]
922    if { $_reset } {
923        #
924        # Reset the camera and other view parameters
925        #
926        set _settings(-qw)    $_view(-qw)
927        set _settings(-qx)    $_view(-qx)
928        set _settings(-qy)    $_view(-qy)
929        set _settings(-qz)    $_view(-qz)
930        set _settings(-xpan)  $_view(-xpan)
931        set _settings(-ypan)  $_view(-ypan)
932        set _settings(-zoom)  $_view(-zoom)
933
934        set q [ViewToQuaternion]
935        $_arcball quaternion $q
936        SendCmd "camera orient $q"
937        SendCmd "camera reset"
938        PanCamera
939        SendCmd "camera zoom $_view(-zoom)"
940
941        # Turn off cutplanes for all volumes
942        foreach axis {x y z} {
943            SendCmd "cutplane state 0 $axis"
944        }
945
946        InitSettings -light2side -light -opacity \
947            -isosurfaceshading -gridvisible -axesvisible \
948            -xcutplanevisible -ycutplanevisible -zcutplanevisible       
949
950        if {"" != $_first} {
951            set axis [$_first hints updir]
952            if { "" != $axis } {
953                SendCmd "up $axis"
954            }
955            set location [$_first hints camera]
956            if { $location != "" } {
957                array set _view $location
958            }
959        }
960    }
961
962    # nothing to send -- activate the proper ivol
963    SendCmd "volume state 0"
964    if {"" != $_first} {
965        set datasets [array names _serverDatasets $_first-*]
966        if { $datasets != "" } {
967            SendCmd "volume state 1 $datasets"
968        }
969        # If the first volume already exists on the server, then make sure
970        # we display the proper transfer function in the legend.
971        set cname [lindex [$_first components] 0]
972        if { [info exists _serverDatasets($_first-$cname)] } {
973            updateTransferFunctions
974        }
975    }
976    # Actually write the commands to the server socket.  If it fails, we don't
977    # care.  We're finished here.
978    blt::busy hold $itk_component(hull)
979    StopBufferingCommands
980    blt::busy release $itk_component(hull)
981    set _reset 0
982}
983
984# ----------------------------------------------------------------------
985# USAGE: CurrentDatasets ?-cutplanes?
986#
987# Returns a list of volume server IDs for the current volume being
988# displayed.  This is normally a single ID, but it might be a list
989# of IDs if the current data object has multiple components.
990# ----------------------------------------------------------------------
991itcl::body Rappture::NanovisViewer::CurrentDatasets {{what -all}} {
992    set rlist ""
993    if { $_first == "" } {
994        return
995    }
996    foreach cname [$_first components] {
997        set tag $_first-$cname
998        if { [info exists _serverDatasets($tag)] && $_serverDatasets($tag) } {
999            array set style {
1000                -cutplanes 1
1001            }
1002            array set style [lindex [$_first components -style $cname] 0]
1003            if { $what != "-cutplanes" || $style(-cutplanes) } {
1004                lappend rlist $tag
1005            }
1006        }
1007    }
1008    return $rlist
1009}
1010
1011# ----------------------------------------------------------------------
1012# USAGE: Zoom in
1013# USAGE: Zoom out
1014# USAGE: Zoom reset
1015#
1016# Called automatically when the user clicks on one of the zoom
1017# controls for this widget.  Changes the zoom for the current view.
1018# ----------------------------------------------------------------------
1019itcl::body Rappture::NanovisViewer::Zoom {option} {
1020    switch -- $option {
1021        "in" {
1022            set _view(-zoom) [expr {$_view(-zoom)*1.25}]
1023            set _settings(-zoom) $_view(-zoom)
1024            SendCmd "camera zoom $_view(-zoom)"
1025        }
1026        "out" {
1027            set _view(-zoom) [expr {$_view(-zoom)*0.8}]
1028            set _settings(-zoom) $_view(-zoom)
1029            SendCmd "camera zoom $_view(-zoom)"
1030        }
1031        "reset" {
1032            array set _view {
1033                -qw      0.853553
1034                -qx      -0.353553
1035                -qy      0.353553
1036                -qz      0.146447
1037                -xpan    0
1038                -ypan    0
1039                -zoom    1.0
1040            }
1041            if { $_first != "" } {
1042                set location [$_first hints camera]
1043                if { $location != "" } {
1044                    array set _view $location
1045                }
1046            }
1047            set q [ViewToQuaternion]
1048            $_arcball quaternion $q
1049            SendCmd "camera orient $q"
1050            SendCmd "camera reset"
1051            set _settings(-qw)    $_view(-qw)
1052            set _settings(-qx)    $_view(-qx)
1053            set _settings(-qy)    $_view(-qy)
1054            set _settings(-qz)    $_view(-qz)
1055            set _settings(-xpan)  $_view(-xpan)
1056            set _settings(-ypan)  $_view(-ypan)
1057            set _settings(-zoom)  $_view(-zoom)
1058        }
1059    }
1060}
1061
1062itcl::body Rappture::NanovisViewer::PanCamera {} {
1063    set x $_view(-xpan)
1064    set y $_view(-ypan)
1065    SendCmd "camera pan $x $y"
1066}
1067
1068# ----------------------------------------------------------------------
1069# USAGE: Rotate click <x> <y>
1070# USAGE: Rotate drag <x> <y>
1071# USAGE: Rotate release <x> <y>
1072#
1073# Called automatically when the user clicks/drags/releases in the
1074# plot area.  Moves the plot according to the user's actions.
1075# ----------------------------------------------------------------------
1076itcl::body Rappture::NanovisViewer::Rotate {option x y} {
1077    switch -- $option {
1078        click {
1079            $itk_component(3dview) configure -cursor fleur
1080            set _click(x) $x
1081            set _click(y) $y
1082        }
1083        drag {
1084            if {[array size _click] == 0} {
1085                Rotate click $x $y
1086            } else {
1087                set w [winfo width $itk_component(3dview)]
1088                set h [winfo height $itk_component(3dview)]
1089                if {$w <= 0 || $h <= 0} {
1090                    return
1091                }
1092
1093                if {[catch {
1094                    # this fails sometimes for no apparent reason
1095                    set dx [expr {double($x-$_click(x))/$w}]
1096                    set dy [expr {double($y-$_click(y))/$h}]
1097                }]} {
1098                    return
1099                }
1100
1101                set q [$_arcball rotate $x $y $_click(x) $_click(y)]
1102                QuaternionToView $q
1103                set _settings(-qw) $_view(-qw)
1104                set _settings(-qx) $_view(-qx)
1105                set _settings(-qy) $_view(-qy)
1106                set _settings(-qz) $_view(-qz)
1107                SendCmd "camera orient $q"
1108
1109                set _click(x) $x
1110                set _click(y) $y
1111            }
1112        }
1113        release {
1114            Rotate drag $x $y
1115            $itk_component(3dview) configure -cursor ""
1116            catch {unset _click}
1117        }
1118        default {
1119            error "bad option \"$option\": should be click, drag, release"
1120        }
1121    }
1122}
1123
1124# ----------------------------------------------------------------------
1125# USAGE: $this Pan click x y
1126#        $this Pan drag x y
1127#        $this Pan release x y
1128#
1129# Called automatically when the user clicks on one of the zoom
1130# controls for this widget.  Changes the zoom for the current view.
1131# ----------------------------------------------------------------------
1132itcl::body Rappture::NanovisViewer::Pan {option x y} {
1133    # Experimental stuff
1134    set w [winfo width $itk_component(3dview)]
1135    set h [winfo height $itk_component(3dview)]
1136    if { $option == "set" } {
1137        set x [expr $x / double($w)]
1138        set y [expr $y / double($h)]
1139        set _view(-xpan) [expr $_view(-xpan) + $x]
1140        set _view(-ypan) [expr $_view(-ypan) + $y]
1141        PanCamera
1142        set _settings(-xpan) $_view(-xpan)
1143        set _settings(-ypan) $_view(-ypan)
1144        return
1145    }
1146    if { $option == "click" } {
1147        set _click(x) $x
1148        set _click(y) $y
1149        $itk_component(3dview) configure -cursor hand1
1150    }
1151    if { $option == "drag" || $option == "release" } {
1152        set dx [expr ($_click(x) - $x)/double($w)]
1153        set dy [expr ($_click(y) - $y)/double($h)]
1154        set _click(x) $x
1155        set _click(y) $y
1156        set _view(-xpan) [expr $_view(-xpan) - $dx]
1157        set _view(-ypan) [expr $_view(-ypan) - $dy]
1158        PanCamera
1159        set _settings(-xpan) $_view(-xpan)
1160        set _settings(-ypan) $_view(-ypan)
1161    }
1162    if { $option == "release" } {
1163        $itk_component(3dview) configure -cursor ""
1164    }
1165}
1166
1167# ----------------------------------------------------------------------
1168# USAGE: InitSettings <what> ?<value>?
1169#
1170# Used internally to update rendering settings whenever parameters
1171# change in the popup settings panel.  Sends the new settings off
1172# to the back end.
1173# ----------------------------------------------------------------------
1174itcl::body Rappture::NanovisViewer::InitSettings { args } {
1175    foreach arg $args {
1176        AdjustSetting $arg
1177    }
1178}
1179
1180# ----------------------------------------------------------------------
1181# USAGE: AdjustSetting <what> ?<value>?
1182#
1183# Used internally to update rendering settings whenever parameters
1184# change in the popup settings panel.  Sends the new settings off
1185# to the back end.
1186# ----------------------------------------------------------------------
1187itcl::body Rappture::NanovisViewer::AdjustSetting {what {value ""}} {
1188    if {![isconnected]} {
1189        return
1190    }
1191    switch -- $what {
1192        "-axesvisible" {
1193            SendCmd "axis visible $_settings($what)"
1194        }
1195        "-background" {
1196            set bgcolor [$itk_component(background) value]
1197            array set fgcolors {
1198                "black" "white"
1199                "white" "black"
1200                "grey"  "black"
1201            }
1202            configure -plotbackground $bgcolor \
1203                -plotforeground $fgcolors($bgcolor)
1204            DrawLegend $_current
1205        }
1206        "-colormap" {
1207            set color [$itk_component(colormap) value]
1208            set _settings($what) $color
1209            set _settings($_current${what}) $color
1210            ResetColormap $_current $color
1211        }
1212        "-current" {
1213            set cname [$itk_component(volcomponents) value]
1214            SwitchComponent $cname
1215        }
1216        "-cutplanesvisible" {
1217            set bool $_settings($what)
1218            # We only set cutplanes on the first dataset.
1219            set datasets [CurrentDatasets -cutplanes]
1220            set tag [lindex $datasets 0]
1221            SendCmd "cutplane visible $bool $tag"
1222        }
1223        "-gridvisible" {
1224            SendCmd "grid visible $_settings($what)"
1225        }
1226        "-isosurfaceshading" {
1227            set val $_settings($what)
1228            foreach tag [GetDatasetsWithComponent $_current] {
1229                SendCmd "volume shading isosurface $val $tag"
1230            }
1231        }
1232        "-legendvisible" {
1233            if { $_settings($what) } {
1234                blt::table $itk_component(plotarea) \
1235                    0,0 $itk_component(3dview) -fill both \
1236                    1,0 $itk_component(legend) -fill x
1237                blt::table configure $itk_component(plotarea) r1 -resize none
1238            } else {
1239                blt::table forget $itk_component(legend)
1240            }
1241        }
1242        "-light" {
1243            set _settings($_current${what}) $_settings($what)
1244            set val $_settings($what)
1245            set diffuse [expr {0.01*$val}]
1246            set ambient [expr {1.0-$diffuse}]
1247            set specularLevel 0.3
1248            set specularExp 90.0
1249            foreach tag [GetDatasetsWithComponent $_current] {
1250                SendCmd "volume shading ambient $ambient $tag"
1251                SendCmd "volume shading diffuse $diffuse $tag"
1252                SendCmd "volume shading specularLevel $specularLevel $tag"
1253                SendCmd "volume shading specularExp $specularExp $tag"
1254            }
1255        }
1256        "-light2side" {
1257            set _settings($_current${what}) $_settings($what)
1258            set val $_settings($what)
1259            foreach tag [GetDatasetsWithComponent $_current] {
1260                SendCmd "volume shading light2side $val $tag"
1261            }
1262        }
1263        "-opacity" {
1264            set _settings($_current${what}) $_settings($what)
1265            set val $_settings($what)
1266            set sval [expr { 0.01 * double($val) }]
1267            foreach tag [GetDatasetsWithComponent $_current] {
1268                SendCmd "volume shading opacity $sval $tag"
1269            }
1270        }
1271        "-outlinevisible" {
1272            SendCmd "volume outline state $_settings($what)"
1273        }
1274        "-thickness" {
1275            set val $_settings($what)
1276            set _settings($_current${what}) $val
1277            updateTransferFunctions
1278        }
1279        "-volume" {
1280            # This is the global volume visibility control.  It controls the
1281            # visibility of all the all volumes.  Whenever it's changed, you
1282            # have to synchronize each of the local controls (see below) with
1283            # this.
1284            set datasets [CurrentDatasets]
1285            set bool $_settings($what)
1286            SendCmd "volume data state $bool $datasets"
1287            foreach cname $_componentsList {
1288                set _settings($cname-volumevisible) $bool
1289            }
1290            set _settings(-volumevisible) $bool
1291        }
1292        "-volumevisible" {
1293            # This is the component specific control.  It changes the
1294            # visibility of only the current component.
1295            set _settings($_current${what}) $_settings($what)
1296            foreach tag [GetDatasetsWithComponent $_current] {
1297                SendCmd "volume data state $_settings($what) $tag"
1298            }
1299        }
1300        "-xcutplanevisible" - "-ycutplanevisible" - "-zcutplanevisible" {
1301            set axis [string range $what 1 1]
1302            set bool $_settings($what)
1303            # We only set cutplanes on the first dataset.
1304            set datasets [CurrentDatasets -cutplanes]
1305            set tag [lindex $datasets 0]
1306            SendCmd "cutplane state $bool $axis $tag"
1307            if { $bool } {
1308                $itk_component(${axis}CutScale) configure -state normal \
1309                    -troughcolor white
1310            } else {
1311                $itk_component(${axis}CutScale) configure -state disabled \
1312                    -troughcolor grey82
1313            }
1314        }
1315        default {
1316            error "don't know how to fix $what"
1317        }
1318    }
1319}
1320
1321# ----------------------------------------------------------------------
1322# USAGE: FixLegend
1323#
1324# Used internally to update the legend area whenever it changes size
1325# or when the field changes.  Asks the server to send a new legend
1326# for the current field.
1327# ----------------------------------------------------------------------
1328itcl::body Rappture::NanovisViewer::FixLegend {} {
1329    set _resizeLegendPending 0
1330    set lineht [font metrics $itk_option(-font) -linespace]
1331    set w [expr {$_width-20}]
1332    set h [expr {[winfo height $itk_component(legend)]-20-$lineht}]
1333    if {$w > 0 && $h > 0 && $_first != "" } {
1334        if { [info exists _cname2transferFunction($_current)] } {
1335            SendCmd "legend $_current $w $h"
1336        }
1337    }
1338}
1339
1340#
1341# NameTransferFunction --
1342#
1343#       Creates a transfer function name based on the <style> settings in the
1344#       library run.xml file. This placeholder will be used later to create
1345#       and send the actual transfer function once the data info has been sent
1346#       to us by the render server. [We won't know the volume limits until the
1347#       server parses the 3D data and sends back the limits via ReceiveData.]
1348#
1349itcl::body Rappture::NanovisViewer::NameTransferFunction { dataobj cname } {
1350    array set style {
1351        -color BCGYR
1352        -levels 6
1353        -markers ""
1354    }
1355    set tag $dataobj-$cname
1356    array set style [lindex [$dataobj components -style $cname] 0]
1357    if { ![info exists _cname2transferFunction($cname)] } {
1358        # Get the colormap right now, since it doesn't change with marker
1359        # changes.
1360        set cmap [ColorsToColormap $style(-color)]
1361        set amap [list 0.0 0.0 1.0 1.0]
1362        set _cname2transferFunction($cname) [list $cmap $amap]
1363        SendCmd [list transfunc define $cname $cmap $amap]
1364    }
1365    SendCmd "volume shading transfunc $cname $tag"
1366    if { ![info exists _transferFunctionEditors($cname)] } {
1367        set _transferFunctionEditors($cname) \
1368            [Rappture::TransferFunctionEditor ::\#auto $itk_component(legend) \
1369                 $cname \
1370                 -command [itcl::code $this updateTransferFunctions]]
1371    }
1372    return $cname
1373}
1374
1375#
1376# ComputeTransferFunction --
1377#
1378#       Computes and sends the transfer function to the render server.  It's
1379#       assumed that the volume data limits are known and that the global
1380#       transfer-functions slider values have been set up.  Both parts are
1381#       needed to compute the relative value (location) of the marker, and
1382#       the alpha map of the transfer function.
1383#
1384itcl::body Rappture::NanovisViewer::ComputeTransferFunction { cname } {
1385    foreach {cmap amap} $_cname2transferFunction($cname) break
1386
1387    # We have to parse the style attributes for a volume using this
1388    # transfer-function *once*.  This sets up the initial isomarkers for the
1389    # transfer function.  The user may add/delete markers, so we have to
1390    # maintain a list of markers for each transfer-function.  We use the one
1391    # of the volumes (the first in the list) using the transfer-function as a
1392    # reference.
1393    if { ![info exists _parsedFunction($cname)] } {
1394        array set style {
1395            -color BCGYR
1396            -levels 6
1397            -markers ""
1398        }
1399        # Accumulate the style from all the datasets using it.
1400        foreach tag [GetDatasetsWithComponent $cname] {
1401            foreach {dataobj cname} [split [lindex $tag 0] -] break
1402            array set style [lindex [$dataobj components -style $cname] 0]
1403        }
1404        eval $_transferFunctionEditors($cname) limits $_limits($cname)
1405        # Have to defer creation of isomarkers until we have data limits
1406        if { [info exists style(-markers)] &&
1407             [llength $style(-markers)] > 0 } {
1408            ParseMarkersOption $cname $style(-markers)
1409        } else {
1410            ParseLevelsOption $cname $style(-levels)
1411        }
1412
1413    }
1414    set amap [ComputeAlphamap $cname]
1415    set _cname2transferFunction($cname) [list $cmap $amap]
1416    SendCmd [list transfunc define $cname $cmap $amap]
1417}
1418
1419itcl::body Rappture::NanovisViewer::AddNewMarker { x y } {
1420    if { ![info exists _transferFunctionEditors($_current)] } {
1421        continue
1422    }
1423    # Add a new marker to the current transfer function
1424    $_transferFunctionEditors($_current) newMarker $x $y normal
1425    $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1426}
1427
1428itcl::body Rappture::NanovisViewer::RemoveMarker { x y } {
1429    if { ![info exists _transferFunctionEditors($_current)] } {
1430        continue
1431    }
1432    # Add a new marker to the current transfer function
1433    $_transferFunctionEditors($_current) deleteMarker $x $y
1434}
1435
1436# ----------------------------------------------------------------------
1437# CONFIGURATION OPTION: -plotbackground
1438# ----------------------------------------------------------------------
1439itcl::configbody Rappture::NanovisViewer::plotbackground {
1440    if { [isconnected] } {
1441        set color $itk_option(-plotbackground)
1442        set rgb [Color2RGB $color]
1443        SendCmd "screen bgcolor $rgb"
1444        $itk_component(legend) configure -background $color
1445    }
1446}
1447
1448# ----------------------------------------------------------------------
1449# CONFIGURATION OPTION: -plotforeground
1450# ----------------------------------------------------------------------
1451itcl::configbody Rappture::NanovisViewer::plotforeground {
1452    if { [isconnected] } {
1453        set color $itk_option(-plotforeground)
1454        set rgb [Color2RGB $color]
1455        SendCmd "volume outline color $rgb"
1456        SendCmd "grid axiscolor $rgb"
1457        SendCmd "grid linecolor $rgb"
1458        $itk_component(legend) itemconfigure labels -fill $color
1459        $itk_component(legend) itemconfigure limits -fill $color
1460    }
1461}
1462
1463# ----------------------------------------------------------------------
1464# CONFIGURATION OPTION: -plotoutline
1465# ----------------------------------------------------------------------
1466itcl::configbody Rappture::NanovisViewer::plotoutline {
1467    # Must check if we are connected because this routine is called from the
1468    # class body when the -plotoutline itk_option is defined.  At that point
1469    # the NanovisViewer class constructor hasn't been called, so we can't
1470    # start sending commands to visualization server.
1471    if { [isconnected] } {
1472        if {"" == $itk_option(-plotoutline)} {
1473            SendCmd "volume outline state off"
1474        } else {
1475            SendCmd "volume outline state on"
1476            SendCmd "volume outline color [Color2RGB $itk_option(-plotoutline)]"
1477        }
1478    }
1479}
1480
1481#
1482# The -levels option takes a single value that represents the number
1483# of evenly distributed markers based on the current data range. Each
1484# marker is a relative value from 0.0 to 1.0.
1485#
1486itcl::body Rappture::NanovisViewer::ParseLevelsOption { cname levels } {
1487    set c $itk_component(legend)
1488    set list {}
1489    regsub -all "," $levels " " levels
1490    if {[string is int $levels]} {
1491        for {set i 1} { $i <= $levels } {incr i} {
1492            lappend list [expr {double($i)/($levels+1)}]
1493        }
1494    } else {
1495        foreach x $levels {
1496            lappend list $x
1497        }
1498    }
1499    set _parsedFunction($cname) 1
1500    $_transferFunctionEditors($cname) addMarkers $list
1501    $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1502}
1503
1504#
1505# The -markers option takes a list of zero or more values (the values
1506# may be separated either by spaces or commas) that have the following
1507# format:
1508#
1509#   N%  Percent of current total data range.  Converted to
1510#       to a relative value between 0.0 and 1.0.
1511#   N   Absolute value of marker.  If the marker is outside of
1512#       the current range, it will be displayed on the outer
1513#       edge of the legends, but it range it represents will
1514#       not be seen.
1515#
1516itcl::body Rappture::NanovisViewer::ParseMarkersOption { cname markers } {
1517    set c $itk_component(legend)
1518    set list {}
1519    foreach { min max } $_limits($cname) break
1520    regsub -all "," $markers " " markers
1521    foreach marker $markers {
1522        set n [scan $marker "%g%s" value suffix]
1523        if { $n == 2 && $suffix == "%" } {
1524            # $n% : Set relative value (0..1).
1525            lappend list [expr {$value * 0.01}]
1526        } else {
1527            # $n : absolute value, compute relative
1528            lappend list  [expr {(double($value)-$min)/($max-$min)]}
1529        }
1530    }
1531    set _parsedFunction($cname) 1
1532    $_transferFunctionEditors($cname) addMarkers $list
1533    $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1534}
1535
1536itcl::body Rappture::NanovisViewer::updateTransferFunctions {} {
1537    $_dispatcher event -idle !send_transfunc
1538}
1539
1540itcl::body Rappture::NanovisViewer::BuildViewTab {} {
1541    set fg [option get $itk_component(hull) font Font]
1542    #set bfg [option get $itk_component(hull) boldFont Font]
1543
1544    set inner [$itk_component(main) insert end \
1545        -title "View Settings" \
1546        -icon [Rappture::icon wrench]]
1547    $inner configure -borderwidth 4
1548
1549    checkbutton $inner.axes \
1550        -text "Axes" \
1551        -variable [itcl::scope _settings(-axesvisible)] \
1552        -command [itcl::code $this AdjustSetting -axesvisible] \
1553        -font "Arial 9"
1554
1555    checkbutton $inner.grid \
1556        -text "Grid" \
1557        -variable [itcl::scope _settings(-gridvisible)] \
1558        -command [itcl::code $this AdjustSetting -gridvisible] \
1559        -font "Arial 9"
1560
1561    checkbutton $inner.outline \
1562        -text "Outline" \
1563        -variable [itcl::scope _settings(-outlinevisible)] \
1564        -command [itcl::code $this AdjustSetting -outlinevisible] \
1565        -font "Arial 9"
1566
1567    checkbutton $inner.legend \
1568        -text "Legend" \
1569        -variable [itcl::scope _settings(-legendvisible)] \
1570        -command [itcl::code $this AdjustSetting -legendvisible] \
1571        -font "Arial 9"
1572
1573    checkbutton $inner.volume \
1574        -text "Volume" \
1575        -variable [itcl::scope _settings(-volume)] \
1576        -command [itcl::code $this AdjustSetting -volume] \
1577        -font "Arial 9"
1578
1579    label $inner.background_l -text "Background" -font "Arial 9"
1580    itk_component add background {
1581        Rappture::Combobox $inner.background -width 10 -editable no
1582    }
1583    $inner.background choices insert end \
1584        "black" "black" \
1585        "white" "white" \
1586        "grey"  "grey"
1587
1588    $itk_component(background) value $_settings(-background)
1589    bind $inner.background <<Value>> \
1590        [itcl::code $this AdjustSetting -background]
1591
1592    blt::table $inner \
1593        0,0 $inner.axes -cspan 2 -anchor w \
1594        1,0 $inner.grid -cspan 2 -anchor w \
1595        2,0 $inner.outline -cspan 2 -anchor w \
1596        3,0 $inner.volume -cspan 2 -anchor w \
1597        4,0 $inner.legend -cspan 2 -anchor w \
1598        5,0 $inner.background_l -anchor e -pady 2 \
1599        5,1 $inner.background -fill x
1600
1601    blt::table configure $inner r* -resize none
1602    blt::table configure $inner r6 -resize expand
1603}
1604
1605itcl::body Rappture::NanovisViewer::BuildVolumeTab {} {
1606    set inner [$itk_component(main) insert end \
1607        -title "Volume Settings" \
1608        -icon [Rappture::icon volume-on]]
1609    $inner configure -borderwidth 4
1610
1611    set fg [option get $itk_component(hull) font Font]
1612    #set bfg [option get $itk_component(hull) boldFont Font]
1613
1614    label $inner.lighting_l \
1615        -text "Lighting / Material Properties" \
1616        -font "Arial 9 bold"
1617
1618    checkbutton $inner.isosurface -text "Isosurface shading" -font $fg \
1619        -variable [itcl::scope _settings(-isosurfaceshading)] \
1620        -command [itcl::code $this AdjustSetting -isosurfaceshading]
1621
1622    checkbutton $inner.light2side -text "Two-sided lighting" -font $fg \
1623        -variable [itcl::scope _settings(-light2side)] \
1624        -command [itcl::code $this AdjustSetting -light2side]
1625
1626    checkbutton $inner.visibility -text "Visible" -font $fg \
1627        -variable [itcl::scope _settings(-volumevisible)] \
1628        -command [itcl::code $this AdjustSetting -volumevisible]
1629
1630    label $inner.dim -text "Glow" -font $fg
1631    ::scale $inner.light -from 0 -to 100 -orient horizontal \
1632        -variable [itcl::scope _settings(-light)] \
1633        -showvalue off -command [itcl::code $this AdjustSetting -light] \
1634        -troughcolor grey92
1635    label $inner.bright -text "Surface" -font $fg
1636
1637    # Opacity
1638    label $inner.opacity_l -text "Opacity" -font $fg
1639    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1640        -variable [itcl::scope _settings(-opacity)] \
1641        -showvalue off -command [itcl::code $this AdjustSetting -opacity] \
1642        -troughcolor grey92
1643
1644    label $inner.transferfunction_l \
1645        -text "Transfer Function" -font "Arial 9 bold"
1646
1647    # Tooth thickness
1648    label $inner.thin -text "Thin" -font $fg
1649    ::scale $inner.thickness -from 0 -to 1000 -orient horizontal \
1650        -variable [itcl::scope _settings(-thickness)] \
1651        -showvalue off -command [itcl::code $this AdjustSetting -thickness] \
1652        -troughcolor grey92
1653    label $inner.thick -text "Thick" -font $fg
1654
1655    # Colormap
1656    label $inner.colormap_l -text "Colormap" -font $fg
1657    itk_component add colormap {
1658        Rappture::Combobox $inner.colormap -width 10 -editable no
1659    }
1660
1661    $inner.colormap choices insert end [GetColormapList -includeDefault -includeNone]
1662    bind $inner.colormap <<Value>> \
1663        [itcl::code $this AdjustSetting -colormap]
1664    $itk_component(colormap) value "default"
1665    set _settings(-colormap) "default"
1666
1667    # Component
1668    label $inner.volcomponents_l -text "Component" -font $fg
1669    itk_component add volcomponents {
1670        Rappture::Combobox $inner.volcomponents -editable no
1671    }
1672    bind $inner.volcomponents <<Value>> \
1673        [itcl::code $this AdjustSetting -current]
1674
1675    blt::table $inner \
1676        0,0 $inner.volcomponents_l -anchor e -cspan 2 \
1677        0,2 $inner.volcomponents -cspan 3 -fill x \
1678        1,1 $inner.lighting_l -anchor w -cspan 4 \
1679        2,1 $inner.dim -anchor e \
1680        2,2 $inner.light -cspan 2 -fill x \
1681        2,4 $inner.bright -anchor w \
1682        3,1 $inner.light2side -cspan 3 -anchor w \
1683        4,1 $inner.visibility -cspan 3 -anchor w \
1684        5,1 $inner.transferfunction_l -cspan 4 -anchor w \
1685        6,1 $inner.opacity_l -anchor e -pady 2 \
1686        6,2 $inner.opacity -cspan 3 -fill x \
1687        7,1 $inner.colormap_l -anchor e \
1688        7,2 $inner.colormap -padx 2 -cspan 3 -fill x \
1689        8,1 $inner.thin -anchor e \
1690        8,2 $inner.thickness -cspan 2 -fill x \
1691        8,4 $inner.thick -anchor w
1692
1693    blt::table configure $inner c* r* -resize none
1694    blt::table configure $inner r* -pady { 2 0 }
1695    blt::table configure $inner c2 c3 r9 -resize expand
1696    blt::table configure $inner c0 -width .1i
1697}
1698
1699itcl::body Rappture::NanovisViewer::BuildCutplanesTab {} {
1700    set inner [$itk_component(main) insert end \
1701        -title "Cutplane Settings" \
1702        -icon [Rappture::icon cutbutton]]
1703    $inner configure -borderwidth 4
1704
1705    checkbutton $inner.visible \
1706        -text "Show Cutplanes" \
1707        -variable [itcl::scope _settings(-cutplanesvisible)] \
1708        -command [itcl::code $this AdjustSetting -cutplanesvisible] \
1709        -font "Arial 9"
1710
1711    # X-value slicer...
1712    itk_component add xCutButton {
1713        Rappture::PushButton $inner.xbutton \
1714            -onimage [Rappture::icon x-cutplane] \
1715            -offimage [Rappture::icon x-cutplane] \
1716            -command [itcl::code $this AdjustSetting -xcutplanevisible] \
1717            -variable [itcl::scope _settings(-xcutplanevisible)]
1718    }
1719    Rappture::Tooltip::for $itk_component(xCutButton) \
1720        "Toggle the X cut plane on/off"
1721    $itk_component(xCutButton) select
1722
1723    itk_component add xCutScale {
1724        ::scale $inner.xval -from 100 -to 0 \
1725            -width 10 -orient vertical -showvalue off \
1726            -borderwidth 1 -highlightthickness 0 \
1727            -command [itcl::code $this Slice move x] \
1728            -variable [itcl::scope _settings(-xcutplaneposition)]
1729    } {
1730        usual
1731        ignore -borderwidth -highlightthickness
1732    }
1733    # Set the default cutplane value before disabling the scale.
1734    $itk_component(xCutScale) set 50
1735    $itk_component(xCutScale) configure -state disabled
1736    Rappture::Tooltip::for $itk_component(xCutScale) \
1737        "@[itcl::code $this SlicerTip x]"
1738
1739    # Y-value slicer...
1740    itk_component add yCutButton {
1741        Rappture::PushButton $inner.ybutton \
1742            -onimage [Rappture::icon y-cutplane] \
1743            -offimage [Rappture::icon y-cutplane] \
1744            -command [itcl::code $this AdjustSetting -ycutplanevisible] \
1745            -variable [itcl::scope _settings(-ycutplanevisible)]
1746    }
1747    Rappture::Tooltip::for $itk_component(yCutButton) \
1748        "Toggle the Y cut plane on/off"
1749    $itk_component(yCutButton) select
1750
1751    itk_component add yCutScale {
1752        ::scale $inner.yval -from 100 -to 0 \
1753            -width 10 -orient vertical -showvalue off \
1754            -borderwidth 1 -highlightthickness 0 \
1755            -command [itcl::code $this Slice move y] \
1756            -variable [itcl::scope _settings(-ycutplaneposition)]
1757    } {
1758        usual
1759        ignore -borderwidth -highlightthickness
1760    }
1761    Rappture::Tooltip::for $itk_component(yCutScale) \
1762        "@[itcl::code $this SlicerTip y]"
1763    # Set the default cutplane value before disabling the scale.
1764    $itk_component(yCutScale) set 50
1765    $itk_component(yCutScale) configure -state disabled
1766
1767    # Z-value slicer...
1768    itk_component add zCutButton {
1769        Rappture::PushButton $inner.zbutton \
1770            -onimage [Rappture::icon z-cutplane] \
1771            -offimage [Rappture::icon z-cutplane] \
1772            -command [itcl::code $this AdjustSetting -zcutplanevisible] \
1773            -variable [itcl::scope _settings(-zcutplanevisible)]
1774    }
1775    Rappture::Tooltip::for $itk_component(zCutButton) \
1776        "Toggle the Z cut plane on/off"
1777    $itk_component(zCutButton) select
1778
1779    itk_component add zCutScale {
1780        ::scale $inner.zval -from 100 -to 0 \
1781            -width 10 -orient vertical -showvalue off \
1782            -borderwidth 1 -highlightthickness 0 \
1783            -command [itcl::code $this Slice move z] \
1784            -variable [itcl::scope _settings(-zcutplaneposition)]
1785    } {
1786        usual
1787        ignore -borderwidth -highlightthickness
1788    }
1789    $itk_component(zCutScale) set 50
1790    $itk_component(zCutScale) configure -state disabled
1791    Rappture::Tooltip::for $itk_component(zCutScale) \
1792        "@[itcl::code $this SlicerTip z]"
1793
1794    blt::table $inner \
1795        0,1 $inner.visible -anchor w -pady 2 -cspan 4 \
1796        1,1 $itk_component(xCutScale) \
1797        1,2 $itk_component(yCutScale) \
1798        1,3 $itk_component(zCutScale) \
1799        2,1 $itk_component(xCutButton) \
1800        2,2 $itk_component(yCutButton) \
1801        2,3 $itk_component(zCutButton)
1802
1803    blt::table configure $inner r0 r1 r2 c* -resize none
1804    blt::table configure $inner r3 c4 -resize expand
1805    blt::table configure $inner c0 -width 2
1806    blt::table configure $inner c1 c2 c3 -padx 2
1807}
1808
1809itcl::body Rappture::NanovisViewer::BuildCameraTab {} {
1810    set inner [$itk_component(main) insert end \
1811        -title "Camera Settings" \
1812        -icon [Rappture::icon camera]]
1813    $inner configure -borderwidth 4
1814
1815    label $inner.view_l -text "view" -font "Arial 9"
1816    set f [frame $inner.view]
1817    foreach side { front back left right top bottom } {
1818        button $f.$side  -image [Rappture::icon view$side] \
1819            -command [itcl::code $this SetOrientation $side]
1820        Rappture::Tooltip::for $f.$side "Change the view to $side"
1821        pack $f.$side -side left
1822    }
1823
1824    blt::table $inner \
1825        0,0 $inner.view_l -anchor e -pady 2 \
1826        0,1 $inner.view -anchor w -pady 2
1827    blt::table configure $inner r0 -resize none
1828
1829    set row 1
1830    set labels { qw qx qy qz xpan ypan zoom }
1831    foreach tag $labels {
1832        label $inner.${tag}label -text $tag -font "Arial 9"
1833        entry $inner.${tag} -font "Arial 9"  -bg white \
1834            -textvariable [itcl::scope _settings(-$tag)]
1835        bind $inner.${tag} <Return> \
1836            [itcl::code $this camera set -${tag}]
1837        bind $inner.${tag} <KP_Enter> \
1838            [itcl::code $this camera set -${tag}]
1839        blt::table $inner \
1840            $row,0 $inner.${tag}label -anchor e -pady 2 \
1841            $row,1 $inner.${tag} -anchor w -pady 2
1842        blt::table configure $inner r$row -resize none
1843        incr row
1844    }
1845
1846    blt::table configure $inner c* -resize none
1847    blt::table configure $inner c2 -resize expand
1848    blt::table configure $inner r$row -resize expand
1849}
1850
1851# ----------------------------------------------------------------------
1852# USAGE: Slice move x|y|z <newval>
1853#
1854# Called automatically when the user drags the slider to move the
1855# cut plane that slices 3D data.  Gets the current value from the
1856# slider and moves the cut plane to the appropriate point in the
1857# data set.
1858# ----------------------------------------------------------------------
1859itcl::body Rappture::NanovisViewer::Slice {option args} {
1860    switch -- $option {
1861        move {
1862            if {[llength $args] != 2} {
1863                error "wrong # args: should be \"Slice move x|y|z newval\""
1864            }
1865            set axis [lindex $args 0]
1866            set newval [lindex $args 1]
1867
1868            set newpos [expr {0.01*$newval}]
1869            set datasets [CurrentDatasets -cutplanes]
1870            set tag [lindex $datasets 0]
1871            SendCmd "cutplane position $newpos $axis $tag"
1872        }
1873        default {
1874            error "bad option \"$option\": should be axis, move, or volume"
1875        }
1876    }
1877}
1878
1879# ----------------------------------------------------------------------
1880# USAGE: SlicerTip <axis>
1881#
1882# Used internally to generate a tooltip for the x/y/z slicer controls.
1883# Returns a message that includes the current slicer value.
1884# ----------------------------------------------------------------------
1885itcl::body Rappture::NanovisViewer::SlicerTip {axis} {
1886    set val [$itk_component(${axis}CutScale) get]
1887    return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
1888}
1889
1890itcl::body Rappture::NanovisViewer::DoResize {} {
1891    $_arcball resize $_width $_height
1892    SendCmd "screen size $_width $_height"
1893    set _resizePending 0
1894}
1895
1896itcl::body Rappture::NanovisViewer::EventuallyResize { w h } {
1897    set _width $w
1898    set _height $h
1899    $_arcball resize $w $h
1900    if { !$_resizePending } {
1901        $_dispatcher event -idle !resize
1902        set _resizePending 1
1903    }
1904}
1905
1906itcl::body Rappture::NanovisViewer::EventuallyRedrawLegend {} {
1907    if { !$_resizeLegendPending } {
1908        $_dispatcher event -idle !legend
1909        set _resizeLegendPending 1
1910    }
1911}
1912
1913#  camera --
1914#
1915itcl::body Rappture::NanovisViewer::camera {option args} {
1916    switch -- $option {
1917        "show" {
1918            puts [array get _view]
1919        }
1920        "set" {
1921            set what [lindex $args 0]
1922            set x $_settings($what)
1923            set code [catch { string is double $x } result]
1924            if { $code != 0 || !$result } {
1925                set _settings($what) $_view($what)
1926                return
1927            }
1928            switch -- $what {
1929                "-xpan" - "-ypan" {
1930                    set _view($what) $_settings($what)
1931                    PanCamera
1932                }
1933                "-qx" - "-qy" - "-qz" - "-qw" {
1934                    set _view($what) $_settings($what)
1935                    set q [ViewToQuaternion]
1936                    $_arcball quaternion $q
1937                    SendCmd "camera orient $q"
1938                }
1939                "-zoom" {
1940                    set _view($what) $_settings($what)
1941                    SendCmd "camera zoom $_view($what)"
1942                }
1943            }
1944        }
1945    }
1946}
1947
1948itcl::body Rappture::NanovisViewer::SetOrientation { side } {
1949    array set positions {
1950        front "1 0 0 0"
1951        back  "0 0 1 0"
1952        left  "0.707107 0 -0.707107 0"
1953        right "0.707107 0 0.707107 0"
1954        top   "0.707107 -0.707107 0 0"
1955        bottom "0.707107 0.707107 0 0"
1956    }
1957    foreach name { -qw -qx -qy -qz } value $positions($side) {
1958        set _view($name) $value
1959    }
1960    set q [ViewToQuaternion]
1961    $_arcball quaternion $q
1962    SendCmd "camera orient $q"
1963    SendCmd "camera reset"
1964    set _view(-xpan) 0
1965    set _view(-ypan) 0
1966    set _view(-zoom) 1.0
1967    set _settings(-xpan) $_view(-xpan)
1968    set _settings(-ypan) $_view(-ypan)
1969    set _settings(-zoom) $_view(-zoom)
1970}
1971
1972#
1973# InitComponentSettings --
1974#
1975#    Initializes the volume settings for a specific component. This should
1976#    match what's used as global settings above. This is called the first
1977#    time we try to switch to a given component in SwitchComponent below.
1978#
1979itcl::body Rappture::NanovisViewer::InitComponentSettings { cname } {
1980    foreach {key value} {
1981        -colormap          "default"
1982        -light             40
1983        -light2side        1
1984        -opacity           50
1985        -thickness         350
1986        -volumevisible     1
1987    } {
1988        if { ![info exists _settings($cname${key})] } {
1989            # Don't override existing component settings
1990            set _settings($cname${key}) $value
1991        }
1992    }
1993}
1994
1995#
1996# SwitchComponent --
1997#
1998#    This is called when the current component is changed by the dropdown
1999#    menu in the volume tab.  It synchronizes the global volume settings
2000#    with the settings of the new current component.
2001#
2002itcl::body Rappture::NanovisViewer::SwitchComponent { cname } {
2003    if { ![info exists _settings($cname-light)] } {
2004        InitComponentSettings $cname
2005    }
2006    # _settings variables change widgets, except for colormap
2007    set _settings(-colormap)         $_settings($cname-colormap)
2008    set _settings(-light)            $_settings($cname-light)
2009    set _settings(-light2side)       $_settings($cname-light2side)
2010    set _settings(-opacity)          $_settings($cname-opacity)
2011    set _settings(-thickness)        $_settings($cname-thickness)
2012    set _settings(-volumevisible)    $_settings($cname-volumevisible)
2013    $itk_component(colormap) value   $_settings($cname-colormap)
2014    set _current $cname;                # Reset the current component
2015}
2016
2017#
2018# BuildVolumeComponents --
2019#
2020#    This is called from the "scale" method which is called when a new
2021#    dataset is added or deleted.  It repopulates the dropdown menu of
2022#    volume component names.  It sets the current component to the first
2023#    component in the list (of components found).  Finally, if there is
2024#    only one component, don't display the label or the combobox in the
2025#    volume settings tab.
2026#
2027itcl::body Rappture::NanovisViewer::BuildVolumeComponents {} {
2028    $itk_component(volcomponents) choices delete 0 end
2029    foreach name $_componentsList {
2030        $itk_component(volcomponents) choices insert end $name $name
2031    }
2032    set _current [lindex $_componentsList 0]
2033    $itk_component(volcomponents) value $_current
2034    set parent [winfo parent $itk_component(volcomponents)]
2035    if { [llength $_componentsList] <= 1 } {
2036        # Unpack the components label and dropdown if there's only one
2037        # component.
2038        blt::table forget $parent.volcomponents_l $parent.volcomponents
2039    } else {
2040        # Pack the components label and dropdown into the table there's
2041        # more than one component to select.
2042        blt::table $parent \
2043            0,0 $parent.volcomponents_l -anchor e -cspan 2 \
2044            0,2 $parent.volcomponents -cspan 3 -fill x
2045    }
2046}
2047
2048#
2049# GetDatasetsWithComponents --
2050#
2051#    Returns a list of all the datasets (known by the combination of their
2052#    data object and component name) that match the given component name.
2053#    For example, this is used where we want to change the settings of
2054#    volumes that have the current component.
2055#
2056itcl::body Rappture::NanovisViewer::GetDatasetsWithComponent { cname } {
2057    if { ![info exists _volcomponents($cname)] } {
2058        return ""
2059    }
2060    set list ""
2061    foreach tag $_volcomponents($cname) {
2062        if { ![info exists _serverDatasets($tag)] } {
2063            continue
2064        }
2065        lappend list $tag
2066    }
2067    return $list
2068}
2069
2070#
2071# HideAllMarkers --
2072#
2073#    Hide all the markers in all the transfer functions.  Can't simply
2074#    delete and recreate markers from the <style> since the user may have
2075#    created, deleted, or moved markers.
2076#
2077itcl::body Rappture::NanovisViewer::HideAllMarkers {} {
2078    foreach cname [array names _transferFunctionEditors] {
2079        $_transferFunctionEditors($cname) hideMarkers
2080    }
2081}
2082
2083itcl::body Rappture::NanovisViewer::GetColormap { cname color } {
2084    if { $color == "default" } {
2085        return $_cname2defaultcolormap($cname)
2086    }
2087    return [ColorsToColormap $color]
2088}
2089
2090itcl::body Rappture::NanovisViewer::ResetColormap { cname color } {
2091    # Get the current transfer function
2092    if { ![info exists _cname2transferFunction($cname)] } {
2093        return
2094    }
2095    foreach { cmap amap } $_cname2transferFunction($cname) break
2096    set cmap [GetColormap $cname $color]
2097    set _cname2transferFunction($cname) [list $cmap $amap]
2098    SendCmd [list transfunc define $cname $cmap $amap]
2099    EventuallyRedrawLegend
2100}
2101
2102itcl::body Rappture::NanovisViewer::ComputeAlphamap { cname } {
2103    if { ![info exists _transferFunctionEditors($cname)] } {
2104        return [list 0.0 0.0 1.0 1.0]
2105    }
2106    if { ![info exists _settings($cname-light)] } {
2107        InitComponentSettings $cname
2108    }
2109
2110    set isovalues [$_transferFunctionEditors($cname) values]
2111
2112    # Transfer function should be normalized with [0,1] range
2113    # The volume shading opacity setting is used to scale opacity
2114    # in the volume shader.
2115    set max 1.0
2116
2117    # Use the component-wise thickness setting from the slider
2118    # settings widget
2119    # Scale values between 0.00001 and 0.01000
2120    set delta [expr {double($_settings($cname-thickness)) * 0.0001}]
2121
2122    set first [lindex $isovalues 0]
2123    set last [lindex $isovalues end]
2124    set amap ""
2125    if { $first == "" || $first != 0.0 } {
2126        lappend amap 0.0 0.0
2127    }
2128    foreach x $isovalues {
2129        set x1 [expr {$x-$delta-0.00001}]
2130        set x2 [expr {$x-$delta}]
2131        set x3 [expr {$x+$delta}]
2132        set x4 [expr {$x+$delta+0.00001}]
2133        if { $x1 < 0.0 } {
2134            set x1 0.0
2135        } elseif { $x1 > 1.0 } {
2136            set x1 1.0
2137        }
2138        if { $x2 < 0.0 } {
2139            set x2 0.0
2140        } elseif { $x2 > 1.0 } {
2141            set x2 1.0
2142        }
2143        if { $x3 < 0.0 } {
2144            set x3 0.0
2145        } elseif { $x3 > 1.0 } {
2146            set x3 1.0
2147        }
2148        if { $x4 < 0.0 } {
2149            set x4 0.0
2150        } elseif { $x4 > 1.0 } {
2151            set x4 1.0
2152        }
2153        # add spikes in the middle
2154        lappend amap $x1 0.0
2155        lappend amap $x2 $max
2156        lappend amap $x3 $max
2157        lappend amap $x4 0.0
2158    }
2159    if { $last == "" || $last != 1.0 } {
2160        lappend amap 1.0 0.0
2161    }
2162    return $amap
2163}
2164
2165itcl::body Rappture::NanovisViewer::SetObjectStyle { dataobj cname } {
2166    array set style {
2167        -opacity 0.5
2168    }
2169    array set style [lindex [$dataobj components -style $cname] 0]
2170    # Some tools erroneously set -opacity to 1 in style, so
2171    # override the requested opacity for now
2172    set style(-opacity) 0.5
2173    set _settings($cname-opacity) [expr $style(-opacity) * 100.0]
2174    set tag $dataobj-$cname
2175    SendCmd "volume shading opacity $style(-opacity) $tag"
2176    NameTransferFunction $dataobj $cname
2177}
Note: See TracBrowser for help on using the repository browser.