source: trunk/gui/scripts/nanovisviewer.tcl @ 5371

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

add cutplane position to AdjustSetting?

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