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

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

merge r5371 from trunk

File size: 77.6 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    set _first [lindex [get] 0]
918    # Outline seems to need to be reset every update.
919    InitSettings -outlinevisible -cutplanesvisible
920    if { $_reset } {
921        #
922        # Reset the camera and other view parameters
923        #
924        set _settings(-qw)    $_view(-qw)
925        set _settings(-qx)    $_view(-qx)
926        set _settings(-qy)    $_view(-qy)
927        set _settings(-qz)    $_view(-qz)
928        set _settings(-xpan)  $_view(-xpan)
929        set _settings(-ypan)  $_view(-ypan)
930        set _settings(-zoom)  $_view(-zoom)
931
932        set q [ViewToQuaternion]
933        $_arcball quaternion $q
934        SendCmd "camera orient $q"
935        SendCmd "camera reset"
936        PanCamera
937        SendCmd "camera zoom $_view(-zoom)"
938
939        # Turn off cutplanes for all volumes
940        foreach axis {x y z} {
941            SendCmd "cutplane state 0 $axis"
942        }
943
944        InitSettings -axesvisible -gridvisible \
945            -light2side -isosurfaceshading -opacity \
946            -light \
947            -xcutplanevisible -ycutplanevisible -zcutplanevisible \
948            -current
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        "-xcutplaneposition" - "-ycutplaneposition" - "-zcutplaneposition" {
1301            set axis [string range $what 1 1]
1302            set pos [expr $_settings($what) * 0.01]
1303            # We only set cutplanes on the first dataset.
1304            set datasets [CurrentDatasets -cutplanes]
1305            set tag [lindex $datasets 0]
1306            SendCmd "cutplane position $pos $axis $tag"
1307        }
1308        "-xcutplanevisible" - "-ycutplanevisible" - "-zcutplanevisible" {
1309            set axis [string range $what 1 1]
1310            set bool $_settings($what)
1311            # We only set cutplanes on the first dataset.
1312            set datasets [CurrentDatasets -cutplanes]
1313            set tag [lindex $datasets 0]
1314            SendCmd "cutplane state $bool $axis $tag"
1315            if { $bool } {
1316                $itk_component(${axis}CutScale) configure -state normal \
1317                    -troughcolor white
1318            } else {
1319                $itk_component(${axis}CutScale) configure -state disabled \
1320                    -troughcolor grey82
1321            }
1322        }
1323        default {
1324            error "don't know how to fix $what"
1325        }
1326    }
1327}
1328
1329# ----------------------------------------------------------------------
1330# USAGE: FixLegend
1331#
1332# Used internally to update the legend area whenever it changes size
1333# or when the field changes.  Asks the server to send a new legend
1334# for the current field.
1335# ----------------------------------------------------------------------
1336itcl::body Rappture::NanovisViewer::FixLegend {} {
1337    set _resizeLegendPending 0
1338    set lineht [font metrics $itk_option(-font) -linespace]
1339    set w [expr {$_width-20}]
1340    set h [expr {[winfo height $itk_component(legend)]-20-$lineht}]
1341    if {$w > 0 && $h > 0 && $_first != "" } {
1342        if { [info exists _cname2transferFunction($_current)] } {
1343            SendCmd "legend $_current $w $h"
1344        }
1345    }
1346}
1347
1348#
1349# NameTransferFunction --
1350#
1351#       Creates a transfer function name based on the <style> settings in the
1352#       library run.xml file. This placeholder will be used later to create
1353#       and send the actual transfer function once the data info has been sent
1354#       to us by the render server. [We won't know the volume limits until the
1355#       server parses the 3D data and sends back the limits via ReceiveData.]
1356#
1357itcl::body Rappture::NanovisViewer::NameTransferFunction { dataobj cname } {
1358    array set style {
1359        -color BCGYR
1360        -levels 6
1361        -markers ""
1362    }
1363    set tag $dataobj-$cname
1364    array set style [lindex [$dataobj components -style $cname] 0]
1365    if { ![info exists _cname2transferFunction($cname)] } {
1366        # Get the colormap right now, since it doesn't change with marker
1367        # changes.
1368        set cmap [ColorsToColormap $style(-color)]
1369        set amap [list 0.0 0.0 1.0 1.0]
1370        set _cname2transferFunction($cname) [list $cmap $amap]
1371        SendCmd [list transfunc define $cname $cmap $amap]
1372    }
1373    SendCmd "volume shading transfunc $cname $tag"
1374    if { ![info exists _transferFunctionEditors($cname)] } {
1375        set _transferFunctionEditors($cname) \
1376            [Rappture::TransferFunctionEditor ::\#auto $itk_component(legend) \
1377                 $cname \
1378                 -command [itcl::code $this updateTransferFunctions]]
1379    }
1380    return $cname
1381}
1382
1383#
1384# ComputeTransferFunction --
1385#
1386#       Computes and sends the transfer function to the render server.  It's
1387#       assumed that the volume data limits are known and that the global
1388#       transfer-functions slider values have been set up.  Both parts are
1389#       needed to compute the relative value (location) of the marker, and
1390#       the alpha map of the transfer function.
1391#
1392itcl::body Rappture::NanovisViewer::ComputeTransferFunction { cname } {
1393    foreach {cmap amap} $_cname2transferFunction($cname) break
1394
1395    # We have to parse the style attributes for a volume using this
1396    # transfer-function *once*.  This sets up the initial isomarkers for the
1397    # transfer function.  The user may add/delete markers, so we have to
1398    # maintain a list of markers for each transfer-function.  We use the one
1399    # of the volumes (the first in the list) using the transfer-function as a
1400    # reference.
1401    if { ![info exists _parsedFunction($cname)] } {
1402        array set style {
1403            -color BCGYR
1404            -levels 6
1405            -markers ""
1406        }
1407        # Accumulate the style from all the datasets using it.
1408        foreach tag [GetDatasetsWithComponent $cname] {
1409            foreach {dataobj cname} [split [lindex $tag 0] -] break
1410            array set style [lindex [$dataobj components -style $cname] 0]
1411        }
1412        eval $_transferFunctionEditors($cname) limits $_limits($cname)
1413        # Have to defer creation of isomarkers until we have data limits
1414        if { [info exists style(-markers)] &&
1415             [llength $style(-markers)] > 0 } {
1416            ParseMarkersOption $cname $style(-markers)
1417        } else {
1418            ParseLevelsOption $cname $style(-levels)
1419        }
1420
1421    }
1422    set amap [ComputeAlphamap $cname]
1423    set _cname2transferFunction($cname) [list $cmap $amap]
1424    SendCmd [list transfunc define $cname $cmap $amap]
1425}
1426
1427itcl::body Rappture::NanovisViewer::AddNewMarker { x y } {
1428    if { ![info exists _transferFunctionEditors($_current)] } {
1429        continue
1430    }
1431    # Add a new marker to the current transfer function
1432    $_transferFunctionEditors($_current) newMarker $x $y normal
1433    $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1434}
1435
1436itcl::body Rappture::NanovisViewer::RemoveMarker { x y } {
1437    if { ![info exists _transferFunctionEditors($_current)] } {
1438        continue
1439    }
1440    # Add a new marker to the current transfer function
1441    $_transferFunctionEditors($_current) deleteMarker $x $y
1442}
1443
1444# ----------------------------------------------------------------------
1445# CONFIGURATION OPTION: -plotbackground
1446# ----------------------------------------------------------------------
1447itcl::configbody Rappture::NanovisViewer::plotbackground {
1448    if { [isconnected] } {
1449        set color $itk_option(-plotbackground)
1450        set rgb [Color2RGB $color]
1451        SendCmd "screen bgcolor $rgb"
1452        $itk_component(legend) configure -background $color
1453    }
1454}
1455
1456# ----------------------------------------------------------------------
1457# CONFIGURATION OPTION: -plotforeground
1458# ----------------------------------------------------------------------
1459itcl::configbody Rappture::NanovisViewer::plotforeground {
1460    if { [isconnected] } {
1461        set color $itk_option(-plotforeground)
1462        set rgb [Color2RGB $color]
1463        SendCmd "volume outline color $rgb"
1464        SendCmd "grid axiscolor $rgb"
1465        SendCmd "grid linecolor $rgb"
1466        $itk_component(legend) itemconfigure labels -fill $color
1467        $itk_component(legend) itemconfigure limits -fill $color
1468    }
1469}
1470
1471# ----------------------------------------------------------------------
1472# CONFIGURATION OPTION: -plotoutline
1473# ----------------------------------------------------------------------
1474itcl::configbody Rappture::NanovisViewer::plotoutline {
1475    # Must check if we are connected because this routine is called from the
1476    # class body when the -plotoutline itk_option is defined.  At that point
1477    # the NanovisViewer class constructor hasn't been called, so we can't
1478    # start sending commands to visualization server.
1479    if { [isconnected] } {
1480        if {"" == $itk_option(-plotoutline)} {
1481            SendCmd "volume outline state off"
1482        } else {
1483            SendCmd "volume outline state on"
1484            SendCmd "volume outline color [Color2RGB $itk_option(-plotoutline)]"
1485        }
1486    }
1487}
1488
1489#
1490# The -levels option takes a single value that represents the number
1491# of evenly distributed markers based on the current data range. Each
1492# marker is a relative value from 0.0 to 1.0.
1493#
1494itcl::body Rappture::NanovisViewer::ParseLevelsOption { cname levels } {
1495    set c $itk_component(legend)
1496    set list {}
1497    regsub -all "," $levels " " levels
1498    if {[string is int $levels]} {
1499        for {set i 1} { $i <= $levels } {incr i} {
1500            lappend list [expr {double($i)/($levels+1)}]
1501        }
1502    } else {
1503        foreach x $levels {
1504            lappend list $x
1505        }
1506    }
1507    set _parsedFunction($cname) 1
1508    $_transferFunctionEditors($cname) addMarkers $list
1509    $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1510}
1511
1512#
1513# The -markers option takes a list of zero or more values (the values
1514# may be separated either by spaces or commas) that have the following
1515# format:
1516#
1517#   N%  Percent of current total data range.  Converted to
1518#       to a relative value between 0.0 and 1.0.
1519#   N   Absolute value of marker.  If the marker is outside of
1520#       the current range, it will be displayed on the outer
1521#       edge of the legends, but it range it represents will
1522#       not be seen.
1523#
1524itcl::body Rappture::NanovisViewer::ParseMarkersOption { cname markers } {
1525    set c $itk_component(legend)
1526    set list {}
1527    foreach { min max } $_limits($cname) break
1528    regsub -all "," $markers " " markers
1529    foreach marker $markers {
1530        set n [scan $marker "%g%s" value suffix]
1531        if { $n == 2 && $suffix == "%" } {
1532            # $n% : Set relative value (0..1).
1533            lappend list [expr {$value * 0.01}]
1534        } else {
1535            # $n : absolute value, compute relative
1536            lappend list  [expr {(double($value)-$min)/($max-$min)]}
1537        }
1538    }
1539    set _parsedFunction($cname) 1
1540    $_transferFunctionEditors($cname) addMarkers $list
1541    $itk_component(legend) itemconfigure labels -fill $itk_option(-plotforeground)
1542}
1543
1544itcl::body Rappture::NanovisViewer::updateTransferFunctions {} {
1545    $_dispatcher event -idle !send_transfunc
1546}
1547
1548itcl::body Rappture::NanovisViewer::BuildViewTab {} {
1549    set fg [option get $itk_component(hull) font Font]
1550    #set bfg [option get $itk_component(hull) boldFont Font]
1551
1552    set inner [$itk_component(main) insert end \
1553        -title "View Settings" \
1554        -icon [Rappture::icon wrench]]
1555    $inner configure -borderwidth 4
1556
1557    checkbutton $inner.axes \
1558        -text "Axes" \
1559        -variable [itcl::scope _settings(-axesvisible)] \
1560        -command [itcl::code $this AdjustSetting -axesvisible] \
1561        -font "Arial 9"
1562
1563    checkbutton $inner.grid \
1564        -text "Grid" \
1565        -variable [itcl::scope _settings(-gridvisible)] \
1566        -command [itcl::code $this AdjustSetting -gridvisible] \
1567        -font "Arial 9"
1568
1569    checkbutton $inner.outline \
1570        -text "Outline" \
1571        -variable [itcl::scope _settings(-outlinevisible)] \
1572        -command [itcl::code $this AdjustSetting -outlinevisible] \
1573        -font "Arial 9"
1574
1575    checkbutton $inner.legend \
1576        -text "Legend" \
1577        -variable [itcl::scope _settings(-legendvisible)] \
1578        -command [itcl::code $this AdjustSetting -legendvisible] \
1579        -font "Arial 9"
1580
1581    checkbutton $inner.volume \
1582        -text "Volume" \
1583        -variable [itcl::scope _settings(-volume)] \
1584        -command [itcl::code $this AdjustSetting -volume] \
1585        -font "Arial 9"
1586
1587    label $inner.background_l -text "Background" -font "Arial 9"
1588    itk_component add background {
1589        Rappture::Combobox $inner.background -width 10 -editable no
1590    }
1591    $inner.background choices insert end \
1592        "black" "black" \
1593        "white" "white" \
1594        "grey"  "grey"
1595
1596    $itk_component(background) value $_settings(-background)
1597    bind $inner.background <<Value>> \
1598        [itcl::code $this AdjustSetting -background]
1599
1600    blt::table $inner \
1601        0,0 $inner.axes -cspan 2 -anchor w \
1602        1,0 $inner.grid -cspan 2 -anchor w \
1603        2,0 $inner.outline -cspan 2 -anchor w \
1604        3,0 $inner.volume -cspan 2 -anchor w \
1605        4,0 $inner.legend -cspan 2 -anchor w \
1606        5,0 $inner.background_l -anchor e -pady 2 \
1607        5,1 $inner.background -fill x
1608
1609    blt::table configure $inner r* -resize none
1610    blt::table configure $inner r6 -resize expand
1611}
1612
1613itcl::body Rappture::NanovisViewer::BuildVolumeTab {} {
1614    set inner [$itk_component(main) insert end \
1615        -title "Volume Settings" \
1616        -icon [Rappture::icon volume-on]]
1617    $inner configure -borderwidth 4
1618
1619    set fg [option get $itk_component(hull) font Font]
1620    #set bfg [option get $itk_component(hull) boldFont Font]
1621
1622    label $inner.lighting_l \
1623        -text "Lighting / Material Properties" \
1624        -font "Arial 9 bold"
1625
1626    checkbutton $inner.isosurface -text "Isosurface shading" -font $fg \
1627        -variable [itcl::scope _settings(-isosurfaceshading)] \
1628        -command [itcl::code $this AdjustSetting -isosurfaceshading]
1629
1630    checkbutton $inner.light2side -text "Two-sided lighting" -font $fg \
1631        -variable [itcl::scope _settings(-light2side)] \
1632        -command [itcl::code $this AdjustSetting -light2side]
1633
1634    checkbutton $inner.visibility -text "Visible" -font $fg \
1635        -variable [itcl::scope _settings(-volumevisible)] \
1636        -command [itcl::code $this AdjustSetting -volumevisible]
1637
1638    label $inner.dim -text "Glow" -font $fg
1639    ::scale $inner.light -from 0 -to 100 -orient horizontal \
1640        -variable [itcl::scope _settings(-light)] \
1641        -showvalue off -command [itcl::code $this AdjustSetting -light] \
1642        -troughcolor grey92
1643    label $inner.bright -text "Surface" -font $fg
1644
1645    # Opacity
1646    label $inner.opacity_l -text "Opacity" -font $fg
1647    ::scale $inner.opacity -from 0 -to 100 -orient horizontal \
1648        -variable [itcl::scope _settings(-opacity)] \
1649        -showvalue off -command [itcl::code $this AdjustSetting -opacity] \
1650        -troughcolor grey92
1651
1652    label $inner.transferfunction_l \
1653        -text "Transfer Function" -font "Arial 9 bold"
1654
1655    # Tooth thickness
1656    label $inner.thin -text "Thin" -font $fg
1657    ::scale $inner.thickness -from 0 -to 1000 -orient horizontal \
1658        -variable [itcl::scope _settings(-thickness)] \
1659        -showvalue off -command [itcl::code $this AdjustSetting -thickness] \
1660        -troughcolor grey92
1661    label $inner.thick -text "Thick" -font $fg
1662
1663    # Colormap
1664    label $inner.colormap_l -text "Colormap" -font $fg
1665    itk_component add colormap {
1666        Rappture::Combobox $inner.colormap -width 10 -editable no
1667    }
1668
1669    $inner.colormap choices insert end [GetColormapList -includeDefault -includeNone]
1670    bind $inner.colormap <<Value>> \
1671        [itcl::code $this AdjustSetting -colormap]
1672    $itk_component(colormap) value "default"
1673    set _settings(-colormap) "default"
1674
1675    # Component
1676    label $inner.volcomponents_l -text "Component" -font $fg
1677    itk_component add volcomponents {
1678        Rappture::Combobox $inner.volcomponents -editable no
1679    }
1680    bind $inner.volcomponents <<Value>> \
1681        [itcl::code $this AdjustSetting -current]
1682
1683    blt::table $inner \
1684        0,0 $inner.volcomponents_l -anchor e -cspan 2 \
1685        0,2 $inner.volcomponents -cspan 3 -fill x \
1686        1,1 $inner.lighting_l -anchor w -cspan 4 \
1687        2,1 $inner.dim -anchor e \
1688        2,2 $inner.light -cspan 2 -fill x \
1689        2,4 $inner.bright -anchor w \
1690        3,1 $inner.light2side -cspan 3 -anchor w \
1691        4,1 $inner.visibility -cspan 3 -anchor w \
1692        5,1 $inner.transferfunction_l -cspan 4 -anchor w \
1693        6,1 $inner.opacity_l -anchor e -pady 2 \
1694        6,2 $inner.opacity -cspan 3 -fill x \
1695        7,1 $inner.colormap_l -anchor e \
1696        7,2 $inner.colormap -padx 2 -cspan 3 -fill x \
1697        8,1 $inner.thin -anchor e \
1698        8,2 $inner.thickness -cspan 2 -fill x \
1699        8,4 $inner.thick -anchor w
1700
1701    blt::table configure $inner c* r* -resize none
1702    blt::table configure $inner r* -pady { 2 0 }
1703    blt::table configure $inner c2 c3 r9 -resize expand
1704    blt::table configure $inner c0 -width .1i
1705}
1706
1707itcl::body Rappture::NanovisViewer::BuildCutplanesTab {} {
1708    set inner [$itk_component(main) insert end \
1709        -title "Cutplane Settings" \
1710        -icon [Rappture::icon cutbutton]]
1711    $inner configure -borderwidth 4
1712
1713    checkbutton $inner.visible \
1714        -text "Show Cutplanes" \
1715        -variable [itcl::scope _settings(-cutplanesvisible)] \
1716        -command [itcl::code $this AdjustSetting -cutplanesvisible] \
1717        -font "Arial 9"
1718
1719    # X-value slicer...
1720    itk_component add xCutButton {
1721        Rappture::PushButton $inner.xbutton \
1722            -onimage [Rappture::icon x-cutplane] \
1723            -offimage [Rappture::icon x-cutplane] \
1724            -command [itcl::code $this AdjustSetting -xcutplanevisible] \
1725            -variable [itcl::scope _settings(-xcutplanevisible)]
1726    }
1727    Rappture::Tooltip::for $itk_component(xCutButton) \
1728        "Toggle the X cut plane on/off"
1729    $itk_component(xCutButton) select
1730
1731    itk_component add xCutScale {
1732        ::scale $inner.xval -from 100 -to 0 \
1733            -width 10 -orient vertical -showvalue off \
1734            -borderwidth 1 -highlightthickness 0 \
1735            -command [itcl::code $this Slice move x] \
1736            -variable [itcl::scope _settings(-xcutplaneposition)]
1737    } {
1738        usual
1739        ignore -borderwidth -highlightthickness
1740    }
1741    # Set the default cutplane value before disabling the scale.
1742    $itk_component(xCutScale) set 50
1743    $itk_component(xCutScale) configure -state disabled
1744    Rappture::Tooltip::for $itk_component(xCutScale) \
1745        "@[itcl::code $this SlicerTip x]"
1746
1747    # Y-value slicer...
1748    itk_component add yCutButton {
1749        Rappture::PushButton $inner.ybutton \
1750            -onimage [Rappture::icon y-cutplane] \
1751            -offimage [Rappture::icon y-cutplane] \
1752            -command [itcl::code $this AdjustSetting -ycutplanevisible] \
1753            -variable [itcl::scope _settings(-ycutplanevisible)]
1754    }
1755    Rappture::Tooltip::for $itk_component(yCutButton) \
1756        "Toggle the Y cut plane on/off"
1757    $itk_component(yCutButton) select
1758
1759    itk_component add yCutScale {
1760        ::scale $inner.yval -from 100 -to 0 \
1761            -width 10 -orient vertical -showvalue off \
1762            -borderwidth 1 -highlightthickness 0 \
1763            -command [itcl::code $this Slice move y] \
1764            -variable [itcl::scope _settings(-ycutplaneposition)]
1765    } {
1766        usual
1767        ignore -borderwidth -highlightthickness
1768    }
1769    Rappture::Tooltip::for $itk_component(yCutScale) \
1770        "@[itcl::code $this SlicerTip y]"
1771    # Set the default cutplane value before disabling the scale.
1772    $itk_component(yCutScale) set 50
1773    $itk_component(yCutScale) configure -state disabled
1774
1775    # Z-value slicer...
1776    itk_component add zCutButton {
1777        Rappture::PushButton $inner.zbutton \
1778            -onimage [Rappture::icon z-cutplane] \
1779            -offimage [Rappture::icon z-cutplane] \
1780            -command [itcl::code $this AdjustSetting -zcutplanevisible] \
1781            -variable [itcl::scope _settings(-zcutplanevisible)]
1782    }
1783    Rappture::Tooltip::for $itk_component(zCutButton) \
1784        "Toggle the Z cut plane on/off"
1785    $itk_component(zCutButton) select
1786
1787    itk_component add zCutScale {
1788        ::scale $inner.zval -from 100 -to 0 \
1789            -width 10 -orient vertical -showvalue off \
1790            -borderwidth 1 -highlightthickness 0 \
1791            -command [itcl::code $this Slice move z] \
1792            -variable [itcl::scope _settings(-zcutplaneposition)]
1793    } {
1794        usual
1795        ignore -borderwidth -highlightthickness
1796    }
1797    $itk_component(zCutScale) set 50
1798    $itk_component(zCutScale) configure -state disabled
1799    Rappture::Tooltip::for $itk_component(zCutScale) \
1800        "@[itcl::code $this SlicerTip z]"
1801
1802    blt::table $inner \
1803        0,1 $inner.visible -anchor w -pady 2 -cspan 4 \
1804        1,1 $itk_component(xCutScale) \
1805        1,2 $itk_component(yCutScale) \
1806        1,3 $itk_component(zCutScale) \
1807        2,1 $itk_component(xCutButton) \
1808        2,2 $itk_component(yCutButton) \
1809        2,3 $itk_component(zCutButton)
1810
1811    blt::table configure $inner r0 r1 r2 c* -resize none
1812    blt::table configure $inner r3 c4 -resize expand
1813    blt::table configure $inner c0 -width 2
1814    blt::table configure $inner c1 c2 c3 -padx 2
1815}
1816
1817itcl::body Rappture::NanovisViewer::BuildCameraTab {} {
1818    set inner [$itk_component(main) insert end \
1819        -title "Camera Settings" \
1820        -icon [Rappture::icon camera]]
1821    $inner configure -borderwidth 4
1822
1823    label $inner.view_l -text "view" -font "Arial 9"
1824    set f [frame $inner.view]
1825    foreach side { front back left right top bottom } {
1826        button $f.$side  -image [Rappture::icon view$side] \
1827            -command [itcl::code $this SetOrientation $side]
1828        Rappture::Tooltip::for $f.$side "Change the view to $side"
1829        pack $f.$side -side left
1830    }
1831
1832    blt::table $inner \
1833        0,0 $inner.view_l -anchor e -pady 2 \
1834        0,1 $inner.view -anchor w -pady 2
1835    blt::table configure $inner r0 -resize none
1836
1837    set row 1
1838    set labels { qw qx qy qz xpan ypan zoom }
1839    foreach tag $labels {
1840        label $inner.${tag}label -text $tag -font "Arial 9"
1841        entry $inner.${tag} -font "Arial 9"  -bg white \
1842            -textvariable [itcl::scope _settings(-$tag)]
1843        bind $inner.${tag} <Return> \
1844            [itcl::code $this camera set -${tag}]
1845        bind $inner.${tag} <KP_Enter> \
1846            [itcl::code $this camera set -${tag}]
1847        blt::table $inner \
1848            $row,0 $inner.${tag}label -anchor e -pady 2 \
1849            $row,1 $inner.${tag} -anchor w -pady 2
1850        blt::table configure $inner r$row -resize none
1851        incr row
1852    }
1853
1854    blt::table configure $inner c* -resize none
1855    blt::table configure $inner c2 -resize expand
1856    blt::table configure $inner r$row -resize expand
1857}
1858
1859# ----------------------------------------------------------------------
1860# USAGE: Slice move x|y|z <newval>
1861#
1862# Called automatically when the user drags the slider to move the
1863# cut plane that slices 3D data.  Gets the current value from the
1864# slider and moves the cut plane to the appropriate point in the
1865# data set.
1866# ----------------------------------------------------------------------
1867itcl::body Rappture::NanovisViewer::Slice {option args} {
1868    switch -- $option {
1869        move {
1870            if {[llength $args] != 2} {
1871                error "wrong # args: should be \"Slice move x|y|z newval\""
1872            }
1873            set axis [lindex $args 0]
1874            set newval [lindex $args 1]
1875
1876            set newpos [expr {0.01*$newval}]
1877            set datasets [CurrentDatasets -cutplanes]
1878            set tag [lindex $datasets 0]
1879            SendCmd "cutplane position $newpos $axis $tag"
1880        }
1881        default {
1882            error "bad option \"$option\": should be axis, move, or volume"
1883        }
1884    }
1885}
1886
1887# ----------------------------------------------------------------------
1888# USAGE: SlicerTip <axis>
1889#
1890# Used internally to generate a tooltip for the x/y/z slicer controls.
1891# Returns a message that includes the current slicer value.
1892# ----------------------------------------------------------------------
1893itcl::body Rappture::NanovisViewer::SlicerTip {axis} {
1894    set val [$itk_component(${axis}CutScale) get]
1895    return "Move the [string toupper $axis] cut plane.\nCurrently:  $axis = $val%"
1896}
1897
1898itcl::body Rappture::NanovisViewer::DoResize {} {
1899    $_arcball resize $_width $_height
1900    SendCmd "screen size $_width $_height"
1901    set _resizePending 0
1902}
1903
1904itcl::body Rappture::NanovisViewer::EventuallyResize { w h } {
1905    set _width $w
1906    set _height $h
1907    $_arcball resize $w $h
1908    if { !$_resizePending } {
1909        $_dispatcher event -idle !resize
1910        set _resizePending 1
1911    }
1912}
1913
1914itcl::body Rappture::NanovisViewer::EventuallyRedrawLegend {} {
1915    if { !$_resizeLegendPending } {
1916        $_dispatcher event -idle !legend
1917        set _resizeLegendPending 1
1918    }
1919}
1920
1921#  camera --
1922#
1923itcl::body Rappture::NanovisViewer::camera {option args} {
1924    switch -- $option {
1925        "show" {
1926            puts [array get _view]
1927        }
1928        "set" {
1929            set what [lindex $args 0]
1930            set x $_settings($what)
1931            set code [catch { string is double $x } result]
1932            if { $code != 0 || !$result } {
1933                set _settings($what) $_view($what)
1934                return
1935            }
1936            switch -- $what {
1937                "-xpan" - "-ypan" {
1938                    set _view($what) $_settings($what)
1939                    PanCamera
1940                }
1941                "-qx" - "-qy" - "-qz" - "-qw" {
1942                    set _view($what) $_settings($what)
1943                    set q [ViewToQuaternion]
1944                    $_arcball quaternion $q
1945                    SendCmd "camera orient $q"
1946                }
1947                "-zoom" {
1948                    set _view($what) $_settings($what)
1949                    SendCmd "camera zoom $_view($what)"
1950                }
1951            }
1952        }
1953    }
1954}
1955
1956itcl::body Rappture::NanovisViewer::SetOrientation { side } {
1957    array set positions {
1958        front "1 0 0 0"
1959        back  "0 0 1 0"
1960        left  "0.707107 0 -0.707107 0"
1961        right "0.707107 0 0.707107 0"
1962        top   "0.707107 -0.707107 0 0"
1963        bottom "0.707107 0.707107 0 0"
1964    }
1965    foreach name { -qw -qx -qy -qz } value $positions($side) {
1966        set _view($name) $value
1967    }
1968    set q [ViewToQuaternion]
1969    $_arcball quaternion $q
1970    SendCmd "camera orient $q"
1971    SendCmd "camera reset"
1972    set _view(-xpan) 0
1973    set _view(-ypan) 0
1974    set _view(-zoom) 1.0
1975    set _settings(-xpan) $_view(-xpan)
1976    set _settings(-ypan) $_view(-ypan)
1977    set _settings(-zoom) $_view(-zoom)
1978}
1979
1980#
1981# InitComponentSettings --
1982#
1983#    Initializes the volume settings for a specific component. This should
1984#    match what's used as global settings above. This is called the first
1985#    time we try to switch to a given component in SwitchComponent below.
1986#
1987itcl::body Rappture::NanovisViewer::InitComponentSettings { cname } {
1988    foreach {key value} {
1989        -colormap          "default"
1990        -light             40
1991        -light2side        1
1992        -opacity           50
1993        -thickness         350
1994        -volumevisible     1
1995    } {
1996        if { ![info exists _settings($cname${key})] } {
1997            # Don't override existing component settings
1998            set _settings($cname${key}) $value
1999        }
2000    }
2001}
2002
2003#
2004# SwitchComponent --
2005#
2006#    This is called when the current component is changed by the dropdown
2007#    menu in the volume tab.  It synchronizes the global volume settings
2008#    with the settings of the new current component.
2009#
2010itcl::body Rappture::NanovisViewer::SwitchComponent { cname } {
2011    if { ![info exists _settings($cname-light)] } {
2012        InitComponentSettings $cname
2013    }
2014    # _settings variables change widgets, except for colormap
2015    set _settings(-colormap)         $_settings($cname-colormap)
2016    set _settings(-light)            $_settings($cname-light)
2017    set _settings(-light2side)       $_settings($cname-light2side)
2018    set _settings(-opacity)          $_settings($cname-opacity)
2019    set _settings(-thickness)        $_settings($cname-thickness)
2020    set _settings(-volumevisible)    $_settings($cname-volumevisible)
2021    $itk_component(colormap) value   $_settings($cname-colormap)
2022    set _current $cname;                # Reset the current component
2023}
2024
2025#
2026# BuildVolumeComponents --
2027#
2028#    This is called from the "scale" method which is called when a new
2029#    dataset is added or deleted.  It repopulates the dropdown menu of
2030#    volume component names.  It sets the current component to the first
2031#    component in the list (of components found).  Finally, if there is
2032#    only one component, don't display the label or the combobox in the
2033#    volume settings tab.
2034#
2035itcl::body Rappture::NanovisViewer::BuildVolumeComponents {} {
2036    $itk_component(volcomponents) choices delete 0 end
2037    foreach name $_componentsList {
2038        $itk_component(volcomponents) choices insert end $name $name
2039    }
2040    set _current [lindex $_componentsList 0]
2041    $itk_component(volcomponents) value $_current
2042    set parent [winfo parent $itk_component(volcomponents)]
2043    if { [llength $_componentsList] <= 1 } {
2044        # Unpack the components label and dropdown if there's only one
2045        # component.
2046        blt::table forget $parent.volcomponents_l $parent.volcomponents
2047    } else {
2048        # Pack the components label and dropdown into the table there's
2049        # more than one component to select.
2050        blt::table $parent \
2051            0,0 $parent.volcomponents_l -anchor e -cspan 2 \
2052            0,2 $parent.volcomponents -cspan 3 -fill x
2053    }
2054}
2055
2056#
2057# GetDatasetsWithComponents --
2058#
2059#    Returns a list of all the datasets (known by the combination of their
2060#    data object and component name) that match the given component name.
2061#    For example, this is used where we want to change the settings of
2062#    volumes that have the current component.
2063#
2064itcl::body Rappture::NanovisViewer::GetDatasetsWithComponent { cname } {
2065    if { ![info exists _volcomponents($cname)] } {
2066        return ""
2067    }
2068    set list ""
2069    foreach tag $_volcomponents($cname) {
2070        if { ![info exists _serverDatasets($tag)] } {
2071            continue
2072        }
2073        lappend list $tag
2074    }
2075    return $list
2076}
2077
2078#
2079# HideAllMarkers --
2080#
2081#    Hide all the markers in all the transfer functions.  Can't simply
2082#    delete and recreate markers from the <style> since the user may have
2083#    created, deleted, or moved markers.
2084#
2085itcl::body Rappture::NanovisViewer::HideAllMarkers {} {
2086    foreach cname [array names _transferFunctionEditors] {
2087        $_transferFunctionEditors($cname) hideMarkers
2088    }
2089}
2090
2091itcl::body Rappture::NanovisViewer::GetColormap { cname color } {
2092    if { $color == "default" } {
2093        return $_cname2defaultcolormap($cname)
2094    }
2095    return [ColorsToColormap $color]
2096}
2097
2098itcl::body Rappture::NanovisViewer::ResetColormap { cname color } {
2099    # Get the current transfer function
2100    if { ![info exists _cname2transferFunction($cname)] } {
2101        return
2102    }
2103    foreach { cmap amap } $_cname2transferFunction($cname) break
2104    set cmap [GetColormap $cname $color]
2105    set _cname2transferFunction($cname) [list $cmap $amap]
2106    SendCmd [list transfunc define $cname $cmap $amap]
2107    EventuallyRedrawLegend
2108}
2109
2110itcl::body Rappture::NanovisViewer::ComputeAlphamap { cname } {
2111    if { ![info exists _transferFunctionEditors($cname)] } {
2112        return [list 0.0 0.0 1.0 1.0]
2113    }
2114    if { ![info exists _settings($cname-light)] } {
2115        InitComponentSettings $cname
2116    }
2117
2118    set isovalues [$_transferFunctionEditors($cname) values]
2119
2120    # Transfer function should be normalized with [0,1] range
2121    # The volume shading opacity setting is used to scale opacity
2122    # in the volume shader.
2123    set max 1.0
2124
2125    # Use the component-wise thickness setting from the slider
2126    # settings widget
2127    # Scale values between 0.00001 and 0.01000
2128    set delta [expr {double($_settings($cname-thickness)) * 0.0001}]
2129
2130    set first [lindex $isovalues 0]
2131    set last [lindex $isovalues end]
2132    set amap ""
2133    if { $first == "" || $first != 0.0 } {
2134        lappend amap 0.0 0.0
2135    }
2136    foreach x $isovalues {
2137        set x1 [expr {$x-$delta-0.00001}]
2138        set x2 [expr {$x-$delta}]
2139        set x3 [expr {$x+$delta}]
2140        set x4 [expr {$x+$delta+0.00001}]
2141        if { $x1 < 0.0 } {
2142            set x1 0.0
2143        } elseif { $x1 > 1.0 } {
2144            set x1 1.0
2145        }
2146        if { $x2 < 0.0 } {
2147            set x2 0.0
2148        } elseif { $x2 > 1.0 } {
2149            set x2 1.0
2150        }
2151        if { $x3 < 0.0 } {
2152            set x3 0.0
2153        } elseif { $x3 > 1.0 } {
2154            set x3 1.0
2155        }
2156        if { $x4 < 0.0 } {
2157            set x4 0.0
2158        } elseif { $x4 > 1.0 } {
2159            set x4 1.0
2160        }
2161        # add spikes in the middle
2162        lappend amap $x1 0.0
2163        lappend amap $x2 $max
2164        lappend amap $x3 $max
2165        lappend amap $x4 0.0
2166    }
2167    if { $last == "" || $last != 1.0 } {
2168        lappend amap 1.0 0.0
2169    }
2170    return $amap
2171}
2172
2173itcl::body Rappture::NanovisViewer::SetObjectStyle { dataobj cname } {
2174    array set style {
2175        -opacity 0.5
2176    }
2177    array set style [lindex [$dataobj components -style $cname] 0]
2178    # Some tools erroneously set -opacity to 1 in style, so
2179    # override the requested opacity for now
2180    set style(-opacity) 0.5
2181    set _settings($cname-opacity) [expr $style(-opacity) * 100.0]
2182    set tag $dataobj-$cname
2183    SendCmd "volume shading opacity $style(-opacity) $tag"
2184    NameTransferFunction $dataobj $cname
2185}
Note: See TracBrowser for help on using the repository browser.