source: branches/blt4/gui/scripts/nanovisviewer.tcl @ 1719

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