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

Last change on this file since 6527 was 6360, checked in by ldelgass, 8 years ago

Init settings fix for nano/flowvis

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