source: branches/r9/gui/scripts/field.tcl @ 4988

Last change on this file since 4988 was 4919, checked in by gah, 9 years ago
File size: 59.6 KB
Line 
1# -*- mode: tcl; indent-tabs-mode: nil -*-
2# ----------------------------------------------------------------------
3#  COMPONENT: field - extracts data from an XML description of a field
4#
5#  This object represents one field in an XML description of a device.
6#  It simplifies the process of extracting data vectors that represent
7#  the field.
8# ======================================================================
9#  AUTHOR:  Michael McLennan, Purdue University
10#  Copyright (c) 2004-2012  HUBzero Foundation, LLC
11#
12#  See the file "license.terms" for information on usage and
13#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
14# ======================================================================
15
16# TODO:
17#    Vector field limits are wrong: need to compute magnitude limits and
18#    component-wise limits.
19
20#
21# Possible field dataset types:
22#
23# 2D Datasets
24#       vtk             (range of z-axis is zero).
25#       unirect2d       (deprecated)
26#       cloud           (x,y point coordinates) (deprecated)
27#       mesh
28# 3D Datasets
29#       vtk
30#       unirect3d       (deprecated)
31#       cloud           (x,y,z coordinates) (deprecated)
32#       mesh
33#       dx              (FIXME: make dx-to-vtk converter work)
34#       ucd avs
35#
36# Viewers:
37#       Format     Dim  Description                     Viewer          Server
38#       vtk         2   vtk file data.                  contour         vtkvis
39#       vtk         3   vtk file data.                  isosurface      vtkvis
40#       mesh        2   points-on-mesh                  heightmap       vtkvis
41#       mesh        3   points-on-mesh                  isosurface      vtkvis
42#       dx          3   DX                              volume          nanovis
43#       unirect2d   2   unirect3d + extents > 1 flow    flow            nanovis
44#       unirect3d   3   unirect2d + extents > 1 flow    flow            nanovis
45#       
46# With <views>, can specify which viewer for specific datasets.  So it's OK
47# for the same dataset to be viewed in more than one way.
48#  o Any 2D dataset can be viewed as a contour/heightmap.
49#  o Any 3D dataset can be viewed as a isosurface.
50#  o Any 2D dataset with vector data can be streamlines or flow. 
51#  o Any 3D uniform rectilinear dataset can be viewed as a volume.
52#  o Any 3D dataset with vector data can be streamlines or flow.
53#
54# Need <views> to properly do things like qdot: volume with a polydata
55# transparent shell.  The view will combine the two objects <field> and
56# <drawing> (??) into a single viewer.
57#
58package require Itcl
59package require BLT
60
61namespace eval Rappture {
62    # forward declaration
63}
64
65itcl::class Rappture::Field {
66    protected variable _dim 0;          # Dimension of the mesh
67    private variable _xmlobj "";        # ref to XML obj with field data
68    private variable _limits;           # maps axis name => {z0 z1} limits
69    private variable _field ""
70    private variable _comp2fldName ;    # cname => field names.
71    private variable _comp2type ;       # cname => type (e.g. "vectors")
72    private variable _comp2size ;       # cname => # of components in element
73    private variable _comp2assoc;       # cname => association (e.g. pointdata)
74    private variable _fld2Components;   # field name => number of components
75    private variable _fld2Label;        # field name => label
76    private variable _fld2Units;        # field name => units
77    private variable _hints
78    private variable _viewer "";        # Hints which viewer to use
79    private variable _xv "";            # For 1D meshes only.  Holds the points
80    private variable _isValid 0;        # Indicates if the field contains
81                                        # valid data.
82    private variable _isValidComponent; #  Array of valid components found
83    private variable _alwaysConvertDX 0;
84
85    constructor {xmlobj path} {
86        # defined below
87    }
88    destructor {
89        # defined below
90    }
91    public method blob { cname }
92    public method components {args}
93    public method controls {option args}
94    public method extents {{cname -overall}}
95    public method numComponents {cname}
96    public method fieldlimits {}
97    public method valueLimits { cname }
98    public method flowhints { cname }
99    public method hints {{key ""}}
100    public method isunirect2d {}
101    public method isunirect3d {}
102    public method limits {axis}
103    public method mesh {{cname -overall}}
104    public method style { cname }
105    public method type {}
106    public method values { cname }
107    public method vtkdata {cname}
108    public method xErrorValues { cname } {
109    }
110    public method yErrorValues { cname } {
111    }
112
113    public method fieldnames { cname } {
114        if { ![info exists _comp2fldName($cname)] } {
115            return ""
116        }
117        return $_comp2fldName($cname)
118    }
119    public method fieldinfo { fname } {
120        lappend out $_fld2Label($fname)
121        lappend out $_fld2Units($fname)
122        lappend out $_fld2Components($fname)
123        return $out
124    }
125    public method isvalid {} {
126        return $_isValid
127    }
128    public method viewer {} {
129        return $_viewer
130    }
131    protected method Build {}
132    protected method _getValue {expr}
133
134    private variable _path "";          # Path of this object in the XML
135    private variable _units ""   ;      # system of units for this field
136    private variable _zmax 0     ;# length of the device
137
138    private variable _comp2dims  ;# maps component name => dimensionality
139    private variable _comp2xy    ;# maps component name => x,y vectors
140    private variable _comp2vtk   ;# maps component name => vtk file data
141    private variable _comp2dx    ;# maps component name => OpenDX data
142    private variable _comp2unirect2d ;# maps component name => unirect2d obj
143    private variable _comp2unirect3d ;# maps component name => unirect3d obj
144    private variable _comp2style ;# maps component name => style settings
145    private variable _comp2cntls ;# maps component name => x,y control points
146    private variable _comp2extents
147    private variable _comp2limits;      #  Array of limits per component
148    private variable _type ""
149    private variable _comp2flowhints
150    private variable _comp2mesh
151    private common _counter 0    ;# counter for unique vector names
152
153    private method AvsToVtk { cname contents }
154    private method DicomToVtk { cname contents }
155    private method BuildPointsOnMesh { cname }
156    protected method GetAssociation { cname }
157    protected method GetTypeAndSize { cname }
158    protected method ReadVtkDataSet { cname contents }
159    private method InitHints {}
160
161    private method VerifyVtkDataSet { contents }
162    private method VectorLimits { vector vectorsize {comp -1} }
163    private variable _values ""
164}
165
166# ----------------------------------------------------------------------
167# CONSTRUCTOR
168# ----------------------------------------------------------------------
169itcl::body Rappture::Field::constructor {xmlobj path} {
170    package require vtk
171    if {![Rappture::library isvalid $xmlobj]} {
172        error "bad value \"$xmlobj\": should be Rappture::library"
173    }
174    set _xmlobj $xmlobj
175    set _path $path
176    set _field [$xmlobj element -as object $path]
177    set _units [$_field get units]
178
179    set xunits [$xmlobj get units]
180    if {"" == $xunits || "arbitrary" == $xunits} {
181        set xunits "um"
182    }
183
184    # determine the overall size of the device
185    set z0 [set z1 0]
186    foreach elem [$_xmlobj children components] {
187        switch -glob -- $elem {
188            box* {
189                if {![regexp {[0-9]$} $elem]} {
190                    set elem "${elem}0"
191                }
192                set z0 [$_xmlobj get components.$elem.corner0]
193                set z0 [Rappture::Units::convert $z0 \
194                    -context $xunits -to $xunits -units off]
195
196                set z1 [$_xmlobj get components.$elem.corner1]
197                set z1 [Rappture::Units::convert $z1 \
198                    -context $xunits -to $xunits -units off]
199
200                set _limits($elem) [list $z0 $z1]
201            }
202        }
203    }
204    set _zmax $z1
205
206    # build up vectors for various components of the field
207    Build
208    InitHints
209}
210
211# ----------------------------------------------------------------------
212# DESTRUCTOR
213# ----------------------------------------------------------------------
214itcl::body Rappture::Field::destructor {} {
215    itcl::delete object $_field
216    # don't destroy the _xmlobj! we don't own it!
217
218    foreach name [array names _comp2xy] {
219        eval blt::vector destroy $_comp2xy($name)
220    }
221    foreach name [array names _comp2unirect2d] {
222        itcl::delete object $_comp2unirect2d($name)
223    }
224    foreach name [array names _comp2unirect3d] {
225        itcl::delete object $_comp2unirect3d($name)
226    }
227    foreach name [array names _comp2flowhints] {
228        itcl::delete object $_comp2flowhints($name)
229    }
230    foreach name [array names _comp2mesh] {
231        # Data is in the form of a mesh and a vector.
232        foreach { mesh vector } $_comp2mesh($name) break
233        # Release the mesh (may be shared)
234        set class [$mesh info class]
235        ${class}::release $mesh
236        # Destroy the vector
237        blt::vector destroy $vector
238    }
239}
240
241# ----------------------------------------------------------------------
242# USAGE: components ?-name|-dimensions|-style? ?<pattern>?
243#
244# Returns a list of names or types for the various components of
245# this field.  If the optional glob-style <pattern> is specified,
246# then it returns only the components with names matching the pattern.
247# ----------------------------------------------------------------------
248itcl::body Rappture::Field::components {args} {
249    Rappture::getopts args params {
250        flag what -name default
251        flag what -dimensions
252        flag what -style
253        flag what -particles
254        flag what -flow
255        flag what -box
256    }
257
258    set pattern *
259    if {[llength $args] > 0} {
260        set pattern [lindex $args 0]
261        set args [lrange $args 1 end]
262    }
263    if {[llength $args] > 0} {
264        error "wrong # args: should be \"components ?switches? ?pattern?\""
265    }
266
267    # There's only one dimension of the field.  Components can't have
268    # different dimensions in the same field.  They would by definition be
269    # using different meshes and viewers.
270    if { $params(what) == "-dimensions" } {
271        return "${_dim}D"
272    }
273    # BE CAREFUL: return component names in proper order
274    set rlist ""
275    set components {}
276    # First compile a list of valid components that match the pattern
277    foreach cname [$_field children -type component] {
278        if { ![info exists _isValidComponent($cname)] } {
279            continue
280        }
281        if { [string match $pattern $cname] } {
282            lappend components $cname
283        }
284    }
285    # Now handle the tests.
286    switch -- $params(what) {
287        -name {
288            set rlist $components
289        }
290        -style {
291            foreach cname $components {
292                if { [info exists _comp2style($cname)] } {
293                    lappend rlist $_comp2style($cname)
294                }
295            }
296        }
297    }
298    return $rlist
299}
300
301# ----------------------------------------------------------------------
302# USAGE: mesh ?<name>?
303#
304# Returns a list {xvec yvec} for the specified field component <name>.
305# If the name is not specified, then it returns the vectors for the
306# overall field (sum of all components).
307# ----------------------------------------------------------------------
308itcl::body Rappture::Field::mesh {{cname -overall}} {
309    if {$cname == "-overall" || $cname == "component0"} {
310        set cname [lindex [components -name] 0]
311    }
312    if {[info exists _comp2xy($cname)]} {
313        return [lindex $_comp2xy($cname) 0]  ;# return xv
314    }
315    if { [info exists _comp2vtk($cname)] } {
316        # FIXME: extract mesh from VTK file data.
317        if { $_comp2dims($cname) == "1D" } {
318            return $_xv
319        }
320        error "method \"mesh\" is not implemented for VTK file data"
321    }
322    if {[info exists _comp2dx($cname)]} {
323        return ""  ;# no mesh -- it's embedded in the blob data
324    }
325    if {[info exists _comp2mesh($cname)]} {
326        return ""  ;# no mesh -- it's embedded in the value data
327    }
328    if {[info exists _comp2unirect2d($cname)]} {
329        set mobj [lindex $_comp2unirect2d($cname) 0]
330        return [$mobj mesh]
331    }
332    if {[info exists _comp2unirect3d($cname)]} {
333        set mobj [lindex $_comp2unirect3d($cname) 0]
334        return [$mobj mesh]
335    }
336    error "can't get field mesh: Unknown component \"$cname\": should be one of [join [lsort [array names _comp2dims]] {, }]"
337}
338
339# ----------------------------------------------------------------------
340# USAGE: values ?<name>?
341#
342# Returns a list {xvec yvec} for the specified field component <name>.
343# If the name is not specified, then it returns the vectors for the
344# overall field (sum of all components).
345# ----------------------------------------------------------------------
346itcl::body Rappture::Field::values {cname} {
347    if {$cname == "component0"} {
348        set cname "component"
349    }
350    if {[info exists _comp2xy($cname)]} {
351        return [lindex $_comp2xy($cname) 1]  ;# return yv
352    }
353    # VTK file data
354    if { [info exists _comp2vtk($cname)] } {
355        # FIXME: extract the values from the VTK file data
356        if { $_comp2dims($cname) == "1D" } {
357            return $_values
358        }
359        error "method \"values\" is not implemented for vtk file data"
360    }
361    # Points-on-mesh
362    if { [info exists _comp2mesh($cname)] } {
363        set vector [lindex $_comp2mesh($cname) 1]
364        return [$vector range 0 end]
365    }
366    if {[info exists _comp2dx($cname)]} {
367        error "method \"values\" is not implemented for dx file data"
368    }
369    if {[info exists _comp2unirect2d($cname)]} {
370        return $_values
371    }
372    if {[info exists _comp2unirect3d($cname)]} {
373        return [$_comp2unirect3d($cname) blob]
374    }
375    error "can't get field values. Unknown component \"$cname\": should be [join [lsort [array names _comp2dims]] {, }]"
376}
377
378# ----------------------------------------------------------------------
379# USAGE: blob ?<name>?
380#
381# Returns a string representing the blob of data for the mesh and values.
382# ----------------------------------------------------------------------
383itcl::body Rappture::Field::blob {cname} {
384    if {$cname == "component0"} {
385        set cname "component"
386    }
387    if {[info exists _comp2xy($cname)]} {
388        return ""
389    }
390    if { [info exists _comp2vtk($cname)] } {
391        error "blob not implemented for VTK file data"
392    }
393    if {[info exists _comp2dx($cname)]} {
394        return $_comp2dx($cname)  ;# return gzipped, base64-encoded DX data
395    }
396    if {[info exists _comp2unirect2d($cname)]} {
397        set blob [$_comp2unirect2d($cname) blob]
398        lappend blob "values" $_values
399        return $blob
400    }
401    if {[info exists _comp2unirect3d($cname)]} {
402        return [$_comp2unirect3d($cname) blob]
403    }
404    error "can't get field blob: Unknown component \"$cname\": should be one of [join [lsort [array names _comp2dims]] {, }]"
405}
406
407# ----------------------------------------------------------------------
408# USAGE: valueLimits <cname>
409#
410# Returns an array for the requested component with a list {min max}
411# representing the limits for each axis.
412# ----------------------------------------------------------------------
413itcl::body Rappture::Field::valueLimits { cname } {
414    if { [info exists _comp2limits($cname)] } {
415        return $_comp2limits($cname)
416    }
417    return ""
418}
419
420# ----------------------------------------------------------------------
421# USAGE: limits <axis>
422#
423# Returns a list {min max} representing the limits for the specified
424# axis.
425# ----------------------------------------------------------------------
426itcl::body Rappture::Field::limits {which} {
427    set min ""
428    set max ""
429
430    foreach cname [array names _comp2dims] {
431        switch -- $_comp2dims($cname) {
432            1D {
433                switch -- $which {
434                    x - xlin {
435                        set pos 0; set log 0; set axis x
436                    }
437                    xlog {
438                        set pos 0; set log 1; set axis x
439                    }
440                    y - ylin - v - vlin {
441                        set pos 1; set log 0; set axis y
442                    }
443                    ylog - vlog {
444                        set pos 1; set log 1; set axis y
445                    }
446                    default {
447                        error "bad axis \"$which\": should be x, xlin, xlog, y, ylin, ylog, v, vlin, vlog"
448                    }
449                }
450
451                set vname [lindex $_comp2xy($cname) $pos]
452
453                if {$log} {
454                    blt::vector tmp zero
455                    # on a log scale, use abs value and ignore zeros
456                    $vname dup tmp
457                    $vname dup zero
458                    zero expr {tmp == 0}            ;# find the zeros
459                    tmp expr {abs(tmp)}             ;# get the abs value
460                    tmp expr {tmp + zero*max(tmp)}  ;# replace 0s with abs max
461                    set axisMin [blt::vector expr min(tmp)]
462                    set axisMax [blt::vector expr max(tmp)]
463                    blt::vector destroy tmp zero
464                } else {
465                    set axisMin [$vname min]
466                    set axisMax [$vname max]
467                }
468
469                if {"" == $min} {
470                    set min $axisMin
471                } elseif {$axisMin < $min} {
472                    set min $axisMin
473                }
474                if {"" == $max} {
475                    set max $axisMax
476                } elseif {$axisMax > $max} {
477                    set max $axisMax
478                }
479            }
480            default {
481                if {[info exists _comp2limits($cname)]} {
482                    array set limits $_comp2limits($cname)
483                    switch -- $which {
484                        x - xlin - xlog {
485                            set axis x
486                            foreach {axisMin axisMax} $limits(x) break
487                        }
488                        y - ylin - ylog {
489                            set axis y
490                            foreach {axisMin axisMax} $limits(y) break
491                        }
492                        z - zlin - zlog {
493                            set axis z
494                            foreach {axisMin axisMax} $limits(z) break
495                        }
496                        v - vlin - vlog {
497                            set axis v
498                            foreach {axisMin axisMax} $limits(v) break
499                        }
500                        default {
501                            if { ![info exists limits($which)] } {
502                                error "limits: unknown axis \"$which\""
503                            }
504                            set axis v
505                            foreach {axisMin axisMax} $limits($which) break
506                        }
507                    }
508                } else {
509                    set axisMin 0  ;# HACK ALERT! must be OpenDX data
510                    set axisMax 1
511                    set axis v
512                }
513            }
514        }
515        if { "" == $min || $axisMin < $min } {
516            set min $axisMin
517        }
518        if { "" == $max || $axisMax > $max } {
519            set max $axisMax
520        }
521    }
522    set val [$_field get "${axis}axis.min"]
523    if {"" != $val && "" != $min} {
524        if {$val > $min} {
525            # tool specified this min -- don't go any lower
526            set min $val
527        }
528    }
529    set val [$_field get "${axis}axis.max"]
530    if {"" != $val && "" != $max} {
531        if {$val < $max} {
532            # tool specified this max -- don't go any higher
533            set max $val
534        }
535    }
536    return [list $min $max]
537}
538
539# ----------------------------------------------------------------------
540# USAGE: fieldlimits
541#
542# Returns a list {min max} representing the limits for the specified
543# axis.
544# ----------------------------------------------------------------------
545itcl::body Rappture::Field::fieldlimits {} {
546    foreach cname [array names _comp2limits] {
547        array set limits $_comp2limits($cname)
548        foreach fname [fieldnames $cname] {
549            if { ![info exists limits($fname)] } {
550                puts stderr "ERROR: field \"$fname\" unknown in \"$cname\""
551                continue
552            }
553            foreach {min max} $limits($fname) break
554            if { ![info exists overall($fname)] } {
555                set overall($fname) $limits($fname)
556                continue
557            }
558            foreach {omin omax} $overall($fname) break
559            if { $min < $omin } {
560                set omin $min
561            }
562            if { $max > $omax } {
563                set omax $max
564            }
565            set overall($fname) [list $min $max]
566        }
567    }
568    if { [info exists overall] } {
569        return [array get overall]
570    }
571    return ""
572}
573 
574# ----------------------------------------------------------------------
575# USAGE: controls get ?<name>?
576# USAGE: controls validate <path> <value>
577# USAGE: controls put <path> <value>
578#
579# Returns a list {path1 x1 y1 val1  path2 x2 y2 val2 ...} representing
580# control points for the specified field component <name>.
581# ----------------------------------------------------------------------
582itcl::body Rappture::Field::controls {option args} {
583    switch -- $option {
584        get {
585            set cname [lindex $args 0]
586            if {[info exists _comp2cntls($cname)]} {
587                return $_comp2cntls($cname)
588            }
589            return ""
590        }
591        validate {
592            set path [lindex $args 0]
593            set value [lindex $args 1]
594            set units [$_xmlobj get $path.units]
595
596            if {"" != $units} {
597                set nv [Rappture::Units::convert \
598                    $value -context $units -to $units -units off]
599            } else {
600                set nv $value
601            }
602            if {![string is double $nv]
603                  || [regexp -nocase {^(inf|nan)$} $nv]} {
604                error "Value out of range"
605            }
606
607            set rawmin [$_xmlobj get $path.min]
608            if {"" != $rawmin} {
609                set minv $rawmin
610                if {"" != $units} {
611                    set minv [Rappture::Units::convert \
612                        $minv -context $units -to $units -units off]
613                    set nv [Rappture::Units::convert \
614                        $value -context $units -to $units -units off]
615                }
616                # fix for the case when the user tries to
617                # compare values like minv=-500 nv=-0600
618                set nv [format "%g" $nv]
619                set minv [format "%g" $minv]
620
621                if {$nv < $minv} {
622                    error "Minimum value allowed here is $rawmin"
623                }
624            }
625
626            set rawmax [$_xmlobj get $path.max]
627            if {"" != $rawmax} {
628                set maxv $rawmax
629                if {"" != $units} {
630                    set maxv [Rappture::Units::convert \
631                        $maxv -context $units -to $units -units off]
632                    set nv [Rappture::Units::convert \
633                        $value -context $units -to $units -units off]
634                }
635                # fix for the case when the user tries to
636                # compare values like maxv=-500 nv=-0600
637                set nv [format "%g" $nv]
638                set maxv [format "%g" $maxv]
639
640                if {$nv > $maxv} {
641                    error "Maximum value allowed here is $rawmax"
642                }
643            }
644
645            return "ok"
646        }
647        put {
648            set path [lindex $args 0]
649            set value [lindex $args 1]
650            $_xmlobj put $path.current $value
651            Build
652        }
653        default {
654            error "bad field controls option \"$option\": should be get or put"
655        }
656    }
657}
658
659# ----------------------------------------------------------------------
660# USAGE: hints ?<keyword>?
661#
662# Returns a list of key/value pairs for various hints about plotting
663# this field.  If a particular <keyword> is specified, then it returns
664# the hint for that <keyword>, if it exists.
665# ----------------------------------------------------------------------
666itcl::body Rappture::Field::hints {{keyword ""}} {
667    if { $keyword != "" } {
668        if {[info exists _hints($keyword)]} {
669            return $_hints($keyword)
670        }
671        return ""
672    }
673    return [array get _hints]
674}
675
676
677# ----------------------------------------------------------------------
678# USAGE: InitHints
679#
680# Returns a list of key/value pairs for various hints about plotting
681# this field.  If a particular <keyword> is specified, then it returns
682# the hint for that <keyword>, if it exists.
683# ----------------------------------------------------------------------
684itcl::body Rappture::Field::InitHints {} {
685    foreach {key path} {
686        camera          camera.position
687        color           about.color
688        default         about.default
689        group           about.group
690        label           about.label
691        scale           about.scale
692        seeds           about.seeds
693        style           about.style
694        type            about.type
695        xlabel          about.xaxis.label
696        ylabel          about.yaxis.label
697        zlabel          about.zaxis.label
698        xunits          about.xaxis.units
699        yunits          about.yaxis.units
700        zunits          about.zaxis.units
701        units           units
702        updir           updir
703        vectors         about.vectors
704    } {
705        set str [$_field get $path]
706        if { "" != $str } {
707            set _hints($key) $str
708        }
709    }
710    foreach cname [components] {
711        if { ![info exists _comp2mesh($cname)] } {
712            continue
713        }
714        set mesh [lindex $_comp2mesh($cname) 0]
715        foreach axis {x y z} {
716            if { ![info exists _hints(${axis}units)] } {
717                set _hints(${axis}units) [$mesh units $axis]
718            }
719            if { ![info exists _hints(${axis}label)] } {
720                set _hints(${axis}label) [$mesh label $axis]
721            }
722        }
723    }
724    foreach {key path} {
725        toolid          tool.id
726        toolname        tool.name
727        toolcommand     tool.execute
728        tooltitle       tool.title
729        toolrevision    tool.version.application.revision
730    } {
731        set str [$_xmlobj get $path]
732        if { "" != $str } {
733            set _hints($key) $str
734        }
735    }
736    # Set toolip and path hints
737    set _hints(path) $_path
738    if { [info exists _hints(group)] && [info exists _hints(label)] } {
739        # pop-up help for each curve
740        set _hints(tooltip) $_hints(label)
741    }
742}
743
744# ----------------------------------------------------------------------
745# USAGE: Build
746#
747# Used internally to build up the vector representation for the
748# field when the object is first constructed, or whenever the field
749# data changes.  Discards any existing vectors and builds everything
750# from scratch.
751# ----------------------------------------------------------------------
752itcl::body Rappture::Field::Build {} {
753
754    # Discard any existing data
755    foreach name [array names _comp2xy] {
756        eval blt::vector destroy $_comp2xy($name)
757    }
758    array unset _comp2vtk
759    foreach name [array names _comp2unirect2d] {
760        eval itcl::delete object $_comp2unirect2d($name)
761    }
762    foreach name [array names _comp2unirect3d] {
763        eval itcl::delete object $_comp2unirect3d($name)
764    }
765    catch {unset _comp2xy}
766    catch {unset _comp2dx}
767    catch {unset _comp2dims}
768    catch {unset _comp2style}
769    array unset _comp2unirect2d
770    array unset _comp2unirect3d
771    array unset _comp2extents
772    array unset _dataobj2type
773    #
774    # Scan through the components of the field and create
775    # vectors for each part.
776    #
777    array unset _isValidComponent
778    foreach cname [$_field children -type component] {
779        set type ""
780        if { ([$_field element $cname.constant] != "" &&
781              [$_field element $cname.domain] != "") ||
782              [$_field element $cname.xy] != "" } {
783            set type "1D"
784        } elseif { [$_field element $cname.mesh] != "" &&
785                   [$_field element $cname.values] != ""} {
786            set type "points-on-mesh"
787        } elseif { [$_field element $cname.vtk] != ""} {
788            set type "vtk"
789            set viewer [$_field get "about.view"]
790            if { $viewer != "" } {
791                set _viewer $viewer
792            }
793        } elseif {[$_field element $cname.opendx] != ""} {
794            global env
795            if { [info exists env(VTKVOLUME)] } {
796                set _viewer "vtkvolume"
797            }
798            set type "opendx"
799        } elseif {[$_field element $cname.dx] != ""} {
800            global env
801            if { [info exists env(VTKVOLUME)] } {
802                set _viewer "vtkvolume"
803            }
804            set type "dx"
805        } elseif {[$_field element $cname.ucd] != ""} {
806            set type "ucd"
807        } elseif {[$_field element $cname.dicom] != ""} {
808            set type "dicom"
809        }
810        set _comp2style($cname) ""
811        if { $type == "" } {
812            puts stderr "WARNING: Ignoring field component \"$_path.$cname\": no data found."
813            continue
814        }
815        # Save the extents of the component
816        if { [$_field element $cname.extents] != "" } {
817            set extents [$_field get $cname.extents]
818        } else {
819            set extents 1
820        }
821        set _comp2extents($cname) $extents
822        set _type $type
823
824        GetTypeAndSize $cname
825        GetAssociation $cname
826        if { $_comp2size($cname) > 1 } {
827            set viewer [$_field get "about.view"]
828            if { $viewer == "" } {
829                set _viewer "glyphs"
830            }
831        }
832        if {$type == "1D"} {
833            #
834            # 1D data can be represented as 2 BLT vectors,
835            # one for x and the other for y.
836            #
837            set xv ""
838            set yv ""
839            set _dim 1
840            set val [$_field get $cname.constant]
841            if {$val != ""} {
842                set domain [$_field get $cname.domain]
843                if {$domain == "" || ![info exists _limits($domain)]} {
844                    set z0 0
845                    set z1 $_zmax
846                } else {
847                    foreach {z0 z1} $_limits($domain) { break }
848                }
849                set xv [blt::vector create x$_counter]
850                $xv append $z0 $z1
851
852                foreach {val pcomp} [_getValue $val] break
853                set yv [blt::vector create y$_counter]
854                $yv append $val $val
855
856                if {$pcomp != ""} {
857                    set zm [expr {0.5*($z0+$z1)}]
858                    set _comp2cntls($cname) \
859                        [list $pcomp $zm $val "$val$_units"]
860                }
861            } else {
862                set xydata [$_field get $cname.xy]
863                if {"" != $xydata} {
864                    set xv [blt::vector create x$_counter]
865                    set yv [blt::vector create y$_counter]
866                    set tmp [blt::vector create \#auto]
867                    $tmp set $xydata
868                    $tmp split $xv $yv
869                    blt::vector destroy $tmp
870                }
871            }
872
873            if {$xv != "" && $yv != ""} {
874                # sort x-coords in increasing order
875                $xv sort $yv
876                set _dim 1
877                set _comp2dims($cname) "1D"
878                set _comp2xy($cname) [list $xv $yv]
879                incr _counter
880            }
881        } elseif {$type == "points-on-mesh"} {
882            if { ![BuildPointsOnMesh $cname] } {
883                continue;               # Ignore this component
884            }
885        } elseif {$type == "vtk"} {
886            set contents [$_field get $cname.vtk]
887            if { $contents == "" } {
888                puts stderr "WARNING: No data for \"$_path.$cname.vtk\""
889                continue;               # Ignore this component
890            }
891            ReadVtkDataSet $cname $contents
892            set _comp2vtk($cname) $contents
893            set _comp2style($cname) [$_field get $cname.style]
894            incr _counter
895        } elseif {$type == "dx" || $type == "opendx" } {
896            #
897            # HACK ALERT!  Extract gzipped, base64-encoded OpenDX
898            # data.  Assume that it's 3D.  Pass it straight
899            # off to the NanoVis visualizer.
900            #
901            set viewer [$_field get "about.view"]
902            if { $viewer != "" } {
903                set _viewer $viewer
904            }
905            if { $_viewer == "" } {
906                if {[$_field element $cname.flow] != ""} {
907                    set _viewer "flowvis"
908                } else {
909                    set _viewer "nanovis"
910                }
911            }
912            set _dim 3
913            set _comp2dims($cname) "3D"
914            set data [$_field get -decode no $cname.$type]
915            set contents [Rappture::encoding::decode -as zb64 $data]
916            if { $contents == "" } {
917                puts stderr "WARNING: No data for \"$_path.$cname.$type\""
918                continue;               # Ignore this component
919            }
920            if 0 {
921                set f [open /tmp/$_path.$cname.dx "w"]
922                puts -nonewline $f $contents
923                close $f
924            }
925            if { [catch { Rappture::DxToVtk $contents } vtkdata] == 0 } {
926                ReadVtkDataSet $cname $vtkdata
927                if 0 {
928                    set f [open /tmp/$_path.$cname.vtk "w"]
929                    puts -nonewline $f $vtkdata
930                    close $f
931                }
932            } else {
933                puts stderr "Can't parse dx data: $vtkdata"
934            }
935            if { $_alwaysConvertDX ||
936                 ($_viewer != "nanovis" && $_viewer != "flowvis") } {
937                set _type "vtk"
938                set _comp2vtk($cname) $vtkdata
939            } else {
940                set _type "dx"
941                set _comp2dx($cname) $data
942            }
943            set _comp2style($cname) [$_field get $cname.style]
944            if {[$_field element $cname.flow] != ""} {
945                set _comp2flowhints($cname) \
946                    [Rappture::FlowHints ::\#auto $_field $cname $_units]
947            }
948            incr _counter
949        } elseif { $type == "dicom"} {
950            set contents [$_field get $cname.dicom]
951            if { $contents == "" } {
952                continue;               # Ignore this component
953            }
954            set viewer [$_field get "about.view"]
955            if { $viewer != "" } {
956                set _viewer $viewer
957            }
958            set vtkdata [DicomToVtk $cname $contents]
959            if { $_viewer == "" } {
960                set _viewer [expr {($_dim == 3) ? "vtkvolume" : "vtkimage"}]
961            }
962            set _comp2vtk($cname) $vtkdata
963            set _comp2style($cname) [$_field get $cname.style]
964            incr _counter
965        } elseif { $type == "ucd"} {
966            set contents [$_field get $cname.ucd]
967            if { $contents == "" } {
968                continue;               # Ignore this component
969            }
970            set vtkdata [AvsToVtk $cname $contents]
971            ReadVtkDataSet $cname $vtkdata
972            set _comp2vtk($cname) $vtkdata
973            set _comp2style($cname) [$_field get $cname.style]
974            incr _counter
975        }
976        set _isValidComponent($cname) 1
977        #puts stderr "Field $cname type is: $_type"
978    }
979    if { [array size _isValidComponent] == 0 } {
980        puts stderr "ERROR: All components of field \"$_path\" are invalid."
981        return 0
982    }
983    # Sanity check.  Verify that all components of the field have the same
984    # dimension.
985    set dim ""
986    foreach cname [array names _comp2dims] {
987        if { $dim == "" } {
988            set dim $_comp2dims($cname)
989            continue
990        }
991        if { $dim != $_comp2dims($cname) } {
992            puts stderr "WARNING: A field can't have components of different dimensions: [join [array get _comp2dims] ,]"
993            return 0
994        }
995    }
996
997    # FIXME: about.scalars and about.vectors are temporary.  With views
998    #        the label and units for each field will be specified there.
999    #
1000    # FIXME: Test that every <field><component> has the same field names,
1001    #        units, components.
1002    #
1003    # Override what we found in the VTK file with names that the user
1004    # selected.  We override the field label and units.
1005    foreach { fname label units } [$_field get about.scalars] {
1006        if { ![info exists _fld2Name($fname)] } {
1007            set _fld2Name($fname) $fname
1008            set _fld2Components($fname) 1
1009        }
1010        set _fld2Label($fname) $label
1011        set _fld2Units($fname) $units
1012    }
1013    foreach { fname label units } [$_field get about.vectors] {
1014        if { ![info exists _fld2Name($fname)] } {
1015            set _fld2Name($fname) $fname
1016            # We're just marking the field as vector (> 1) for now.
1017            set _fld2Components($fname) 3
1018        }
1019        set _fld2Label($fname) $label
1020        set _fld2Units($fname) $units
1021    }
1022    set _isValid 1
1023    return 1
1024}
1025
1026# ----------------------------------------------------------------------
1027# USAGE: _getValue <expr>
1028#
1029# Used internally to get the value for an expression <expr>.  Returns
1030# a list of the form {val parameterPath}, where val is the numeric
1031# value of the expression, and parameterPath is the XML path to the
1032# parameter representing the value, or "" if the <expr> does not
1033# depend on any parameters.
1034# ----------------------------------------------------------------------
1035itcl::body Rappture::Field::_getValue {expr} {
1036    #
1037    # First, look for the expression among the <parameter>'s
1038    # associated with the device.
1039    #
1040    set found 0
1041    foreach pcomp [$_xmlobj children parameters] {
1042        set id [$_xmlobj element -as id parameters.$pcomp]
1043        if {[string equal $id $expr]} {
1044            set val [$_xmlobj get parameters.$pcomp.current]
1045            if {"" == $val} {
1046                set val [$_xmlobj get parameters.$pcomp.default]
1047            }
1048            if {"" != $val} {
1049                set expr $val
1050                set found 1
1051                break
1052            }
1053        }
1054    }
1055    if {$found} {
1056        set pcomp "parameters.$pcomp"
1057    } else {
1058        set pcomp ""
1059    }
1060
1061    if {$_units != ""} {
1062        set expr [Rappture::Units::convert $expr \
1063            -context $_units -to $_units -units off]
1064    }
1065
1066    return [list $expr $pcomp]
1067}
1068
1069#
1070# isunirect2d  --
1071#
1072# Returns if the field is a unirect2d object. 
1073#
1074itcl::body Rappture::Field::isunirect2d { } {
1075    return [expr [array size _comp2unirect2d] > 0]
1076}
1077
1078#
1079# isunirect3d  --
1080#
1081# Returns if the field is a unirect3d object. 
1082#
1083itcl::body Rappture::Field::isunirect3d { } {
1084    return [expr [array size _comp2unirect3d] > 0]
1085}
1086
1087#
1088# flowhints  --
1089#
1090# Returns the hints associated with a flow vector field. 
1091#
1092itcl::body Rappture::Field::flowhints { cname } {
1093    if { [info exists _comp2flowhints($cname)] } {
1094        return $_comp2flowhints($cname)
1095    }
1096    return ""
1097}
1098
1099#
1100# style  --
1101#
1102# Returns the style associated with a component of the field. 
1103#
1104itcl::body Rappture::Field::style { cname } {
1105    if { [info exists _comp2style($cname)] } {
1106        return $_comp2style($cname)
1107    }
1108    return ""
1109}
1110
1111#
1112# type  --
1113#
1114# Returns the data storage type of the field.
1115#
1116# FIXME: What are the valid types?
1117#
1118itcl::body Rappture::Field::type {} {
1119    return $_type
1120}
1121
1122#
1123# numComponents --
1124#
1125# Returns the number of components in the field component.
1126#
1127itcl::body Rappture::Field::numComponents {cname} {
1128    set name $cname
1129    regsub -all { } $name {_} name
1130    if {[info exists _fld2Components($name)] } {
1131        return $_fld2Components($name)
1132    }
1133    return 1;                           # Default to scalar.
1134}
1135
1136#
1137# extents --
1138#
1139# Returns if the field is a unirect2d object. 
1140#
1141itcl::body Rappture::Field::extents {{cname -overall}} {
1142    if {$cname == "-overall" } {
1143        set max 0
1144        foreach cname [$_field children -type component] {
1145            if { ![info exists _comp2unirect3d($cname)] &&
1146                 ![info exists _comp2extents($cname)] } {
1147                continue
1148            }
1149            set value $_comp2extents($cname)
1150            if { $max < $value } {
1151                set max $value
1152            }
1153        }
1154        return $max
1155    }
1156    if { $cname == "component0"} {
1157        set cname [lindex [components -name] 0]
1158    }
1159    return $_comp2extents($cname)
1160}
1161
1162itcl::body Rappture::Field::VerifyVtkDataSet { contents } {
1163    package require vtk
1164
1165    set reader $this-datasetreader
1166    vtkDataSetReader $reader
1167
1168    # Write the contents to a file just in case it's binary.
1169    set tmpfile file[pid].vtk
1170    set f [open "$tmpfile" "w"]
1171    fconfigure $f -translation binary -encoding binary
1172    puts $f $contents
1173    close $f
1174
1175    $reader SetFileName $tmpfile
1176    $reader ReadAllNormalsOn
1177    $reader ReadAllTCoordsOn
1178    $reader ReadAllScalarsOn
1179    $reader ReadAllColorScalarsOn
1180    $reader ReadAllVectorsOn
1181    $reader ReadAllTensorsOn
1182    $reader ReadAllFieldsOn
1183    $reader Update
1184    file delete $tmpfile
1185
1186    set dataset [$reader GetOutput]
1187    set dataAttrs [$dataset GetPointData]
1188    if { $dataAttrs == ""} {
1189        puts stderr "WARNING: No point data found in \"$_path\""
1190        rename $reader ""
1191        return 0
1192    }
1193    rename $reader ""
1194}
1195
1196itcl::body Rappture::Field::ReadVtkDataSet { cname contents } {
1197    package require vtk
1198
1199    set reader $this-datasetreader
1200    vtkDataSetReader $reader
1201
1202    # Write the contents to a file just in case it's binary.
1203    set tmpfile file[pid].vtk
1204    set f [open "$tmpfile" "w"]
1205    fconfigure $f -translation binary -encoding binary
1206    puts $f $contents
1207    close $f
1208
1209    $reader SetFileName $tmpfile
1210    $reader ReadAllNormalsOn
1211    $reader ReadAllTCoordsOn
1212    $reader ReadAllScalarsOn
1213    $reader ReadAllColorScalarsOn
1214    $reader ReadAllVectorsOn
1215    $reader ReadAllTensorsOn
1216    $reader ReadAllFieldsOn
1217    $reader Update
1218    file delete $tmpfile
1219
1220    set dataset [$reader GetOutput]
1221    set limits {}
1222    foreach {xmin xmax ymin ymax zmin zmax} [$dataset GetBounds] break
1223    # Figure out the dimension of the mesh from the bounds.
1224    set _dim 0
1225    if { $xmax > $xmin } {
1226        incr _dim
1227    }
1228    if { $ymax > $ymin } {
1229        incr _dim
1230    }
1231    if { $zmax > $zmin } {
1232        incr _dim
1233    }
1234    if { $_viewer == "" } {
1235        if { $_dim == 2 } {
1236            set _viewer contour
1237        } else {
1238            set _viewer isosurface
1239        }
1240    }
1241    set _comp2dims($cname) ${_dim}D
1242    if { $_dim < 2 } {
1243        set numPoints [$dataset GetNumberOfPoints]
1244        set xv [blt::vector create \#auto]
1245        for { set i 0 } { $i < $numPoints } { incr i } {
1246            set point [$dataset GetPoint $i]
1247            $xv append [lindex $point 0]
1248        }
1249        set yv [blt::vector create \#auto]
1250        set dataAttrs [$dataset GetPointData]
1251        if { $dataAttrs == ""} {
1252            puts stderr "WARNING: No point data found in \"$_path\""
1253            rename $reader ""
1254            return 0
1255        }
1256        set array [$dataAttrs GetScalars]
1257        if { $array == ""} {
1258            puts stderr "WARNING: No scalar point data found in \"$_path\""
1259            rename $reader ""
1260            return 0
1261        }
1262        set numTuples [$array GetNumberOfTuples]
1263        for { set i 0 } { $i < $numTuples } { incr i } {
1264            $yv append [$array GetComponent $i 0]
1265        }
1266        $xv sort $yv
1267        set _comp2xy($cname) [list $xv $yv]
1268    }
1269    lappend limits x [list $xmin $xmax]
1270    lappend limits y [list $ymin $ymax]
1271    lappend limits z [list $zmin $zmax]
1272    set dataAttrs [$dataset GetPointData]
1273    if { $dataAttrs == ""} {
1274        puts stderr "WARNING: No point data found in \"$_path\""
1275        rename $reader ""
1276        return 0
1277    }
1278    set vmin 0
1279    set vmax 1
1280    set numArrays [$dataAttrs GetNumberOfArrays]
1281    if { $numArrays > 0 } {
1282        for {set i 0} {$i < [$dataAttrs GetNumberOfArrays] } {incr i} {
1283            set array [$dataAttrs GetArray $i]
1284            set fname  [$dataAttrs GetArrayName $i]
1285            foreach {min max} [$array GetRange -1] break
1286            if {$i == 0} {
1287                set vmin $min
1288                set vmax $max
1289            }
1290            lappend limits $fname [list $min $max]
1291            set _fld2Units($fname) ""
1292            set _fld2Label($fname) $fname
1293            # Let the VTK file override the <type> designated.
1294            set _fld2Components($fname) [$array GetNumberOfComponents]
1295            lappend _comp2fldName($cname) $fname
1296        }
1297    }
1298   
1299    lappend limits v [list $vmin $vmax]
1300    set _comp2limits($cname) $limits
1301
1302    rename $reader ""
1303}
1304
1305#
1306# vtkdata --
1307#
1308#       Returns a string representing the mesh and field data for a specific
1309#       component in the legacy VTK file format.
1310#
1311itcl::body Rappture::Field::vtkdata {cname} {
1312    if {$cname == "component0"} {
1313        set cname "component"
1314    }
1315    # DX: Convert DX to VTK
1316    if {[info exists _comp2dx($cname)]} {
1317        set data $_comp2dx($cname)
1318        set data [Rappture::encoding::decode $data]
1319        return [Rappture::DxToVtk $data]
1320    }
1321    # Unirect3d: isosurface
1322    if {[info exists _comp2unirect3d($cname)]} {
1323        return [$_comp2unirect3d($cname) vtkdata]
1324    }
1325    # VTK file data:
1326    if { [info exists _comp2vtk($cname)] } {
1327        return $_comp2vtk($cname)
1328    }
1329    # Points on mesh:  Construct VTK file output.
1330    if { [info exists _comp2mesh($cname)] } {
1331        # Data is in the form mesh and vector
1332        foreach {mesh vector} $_comp2mesh($cname) break
1333        set label $cname
1334        regsub -all { } $label {_} label
1335        append out "# vtk DataFile Version 3.0\n"
1336        append out "[hints label]\n"
1337        append out "ASCII\n"
1338        append out [$mesh vtkdata]
1339
1340        if { $_comp2assoc($cname) == "pointdata" } {
1341            set vtkassoc "POINT_DATA"
1342        } elseif { $_comp2assoc($cname) == "celldata" } {
1343            set vtkassoc "CELL_DATA"
1344        } elseif { $_comp2assoc($cname) == "fielddata" } {
1345            set vtkassoc "FIELD"
1346        } else {
1347            error "unknown association \"$_comp2assoc($cname)\""
1348        }
1349        set elemSize [numComponents $cname]
1350        set numValues [expr [$vector length] / $elemSize]
1351        if { $_comp2assoc($cname) == "fielddata" } {
1352            append out "$vtkassoc FieldData 1\n"
1353            append out "$label $elemSize $numValues double\n"
1354        } else {
1355            append out "$vtkassoc $numValues\n"
1356            if { $_comp2type($cname) == "colorscalars" } {
1357                # Must be float for ASCII, unsigned char for BINARY
1358                append out "COLOR_SCALARS $label $elemSize\n"
1359            } elseif { $_comp2type($cname) == "normals" } {
1360                # elemSize must equal 3
1361                append out "NORMALS $label double\n"
1362            } elseif { $_comp2type($cname) == "scalars" } {
1363                # elemSize can be 1, 2, 3 or 4
1364                append out "SCALARS $label double $elemSize\n"
1365                append out "LOOKUP_TABLE default\n"
1366            } elseif { $_comp2type($cname) == "tcoords" } {
1367                # elemSize must be 1, 2, or 3
1368                append out "TEXTURE_COORDINATES $label $elemSize double\n"
1369            } elseif { $_comp2type($cname) == "tensors" } {
1370                # elemSize must equal 9
1371                append out "TENSORS $label double\n"
1372            } elseif { $_comp2type($cname) == "vectors" } {
1373                # elemSize must equal 3
1374                append out "VECTORS $label double\n"
1375            } else {
1376                error "unknown element type \"$_comp2type($cname)\""
1377            }
1378        }
1379        append out [$vector range 0 end]
1380        append out "\n"
1381        if 0 {
1382            VerifyVtkDataSet $out
1383        }
1384        return $out
1385    }
1386    error "can't find vtkdata for $cname. This method should only be called by the vtkheightmap widget"
1387}
1388
1389#
1390# BuildPointsOnMesh --
1391#
1392#       Parses the field XML description to build a mesh and values vector
1393#       representing the field.  Right now we handle the deprecated types
1394#       of "cloud", "unirect2d", and "unirect3d" (mostly for flows).
1395#
1396itcl::body Rappture::Field::BuildPointsOnMesh {cname} {
1397    #
1398    # More complex 2D/3D data is represented by a mesh
1399    # object and an associated vector for field values.
1400    #
1401    set path [$_field get $cname.mesh]
1402    if {[$_xmlobj element $path] == ""} {
1403        # Unknown mesh designated.
1404        return 0
1405    }
1406    set viewer [$_field get "about.view"]
1407    if { $viewer != "" } {
1408        set _viewer $viewer
1409    }
1410    set element [$_xmlobj element -as type $path]
1411    set name $cname
1412    regsub -all { } $name {_} name
1413    set _fld2Label($name) $name
1414    set label [hints zlabel]
1415    if { $label != "" } {
1416        set _fld2Label($name) $label
1417    }
1418    set _fld2Units($name) [hints zunits]
1419    set _fld2Components($name) $_comp2size($cname)
1420    lappend _comp2fldName($cname) $name
1421
1422    # Handle bizarre cases that hopefully will be deprecated.
1423    if { $element == "unirect3d" } {
1424        # Special case: unirect3d (should be deprecated) + flow.
1425        if { [$_field element $cname.extents] != "" } {
1426            set vectorsize [$_field get $cname.extents]
1427        } else {
1428            set vectorsize 1
1429        }
1430        set _type unirect3d
1431        set _dim 3
1432        if { $_viewer == "" } {
1433            set _viewer flowvis
1434        }
1435        set _comp2dims($cname) "3D"
1436        set _comp2unirect3d($cname) \
1437            [Rappture::Unirect3d \#auto $_xmlobj $_field $cname $vectorsize]
1438        set _comp2style($cname) [$_field get $cname.style]
1439        set limits {}
1440        foreach axis { x y z } {
1441            lappend limits $axis [$_comp2unirect3d($cname) limits $axis]
1442        }
1443        # Get the data limits
1444        set vector [$_comp2unirect3d($cname) valuesObj]
1445        set minmax [VectorLimits $vector $vectorsize]
1446        lappend limits $cname $minmax
1447        lappend limits v      $minmax
1448        set _comp2limits($cname) $limits
1449        if {[$_field element $cname.flow] != ""} {
1450            set _comp2flowhints($cname) \
1451                [Rappture::FlowHints ::\#auto $_field $cname $_units]
1452        }
1453        incr _counter
1454        return 1
1455    }
1456    if { $element == "unirect2d" && [$_field element $cname.flow] != "" } {
1457        # Special case: unirect2d (normally deprecated) + flow.
1458        if { [$_field element $cname.extents] != "" } {
1459            set vectorsize [$_field get $cname.extents]
1460        } else {
1461            set vectorsize 1
1462        }
1463        set _type unirect2d
1464        set _dim 2
1465        if { $_viewer == "" } {
1466            set _viewer "flowvis"
1467        }
1468        set _comp2dims($cname) "2D"
1469        set _comp2unirect2d($cname) \
1470            [Rappture::Unirect2d \#auto $_xmlobj $path]
1471        set _comp2style($cname) [$_field get $cname.style]
1472        set _comp2flowhints($cname) \
1473            [Rappture::FlowHints ::\#auto $_field $cname $_units]
1474        set _values [$_field get $cname.values]
1475        set limits {}
1476        foreach axis { x y z } {
1477            lappend limits $axis [$_comp2unirect2d($cname) limits $axis]
1478        }
1479        set xv [blt::vector create \#auto]
1480        $xv set $_values
1481        set minmax [VectorLimits $xv $vectorsize]
1482        lappend limits $cname $minmax
1483        lappend limits v $minmax
1484        blt::vector destroy $xv
1485        set _comp2limits($cname) $limits
1486        incr _counter
1487        return 1
1488    }
1489    switch -- $element {
1490        "cloud" {
1491            set mesh [Rappture::Cloud::fetch $_xmlobj $path]
1492            set _type cloud
1493        }
1494        "mesh" {
1495            set mesh [Rappture::Mesh::fetch $_xmlobj $path]
1496            set _type mesh
1497        }           
1498        "unirect2d" {
1499            if { $_viewer == "" } {
1500                set _viewer "heightmap"
1501            }
1502            set mesh [Rappture::Unirect2d::fetch $_xmlobj $path]
1503            set _type unirect2d
1504        }
1505    }
1506    if { ![$mesh isvalid] } {
1507        puts stderr "Mesh is invalid"
1508        return 0
1509    }
1510    set _dim [$mesh dimensions]
1511    if { $_dim == 3 } {
1512        set dim 0
1513        foreach axis {x y z} {
1514            foreach {min max} [$mesh limits $axis] {
1515                if { $min < $max } {
1516                    incr dim
1517                }
1518            }
1519        }
1520        if { $dim != 3 } {
1521            set _dim $dim
1522        }
1523    }
1524
1525    if {$_dim == 1} {
1526        # 1D data: Create vectors for graph widget.
1527        # Is this used anywhere?
1528        #
1529        # OOPS!  This is 1D data
1530        # Forget the cloud/field -- store BLT vectors
1531        #
1532        # Is there a natural growth path in generating output from 1D to
1533        # higher dimensions?  If there isn't, let's kill this in favor
1534        # or explicitly using a <curve> instead.  Otherwise, the features
1535        # (methods such as xmarkers) or the <curve> need to be added
1536        # to the <field>.
1537        #
1538        set xv [blt::vector create x$_counter]
1539        set yv [blt::vector create y$_counter]
1540       
1541        $yv set [$mesh points]
1542        $xv seq 0 1 [$yv length]
1543        # sort x-coords in increasing order
1544        $xv sort $yv
1545        set _comp2dims($cname) "1D"
1546        set _comp2xy($cname) [list $xv $yv]
1547        incr _counter
1548        return 1
1549    }
1550    if {$_dim == 2} {
1551        # 2D data: By default surface or contour plot using heightmap widget.
1552        set v [blt::vector create \#auto]
1553        $v set [$_field get $cname.values]
1554        if { [$v length] == 0 } {
1555            return 0
1556        }
1557        if { $_viewer == "" } {
1558            set _viewer "contour"
1559        }
1560        set numFieldValues [$v length]
1561        set numComponentsPerTuple [numComponents $cname]
1562        if { [expr $numFieldValues % $numComponentsPerTuple] != 0 } {
1563            puts stderr "ERROR: Number of field values ($numFieldValues) not divisble by elemsize ($numComponentsPerTuple)"
1564            return 0
1565        }
1566        set numFieldTuples [expr $numFieldValues / $numComponentsPerTuple]
1567        if { $_comp2assoc($cname) == "pointdata" } {
1568            set numPoints [$mesh numpoints]
1569            if { $numPoints != $numFieldTuples } {
1570                puts stderr "ERROR: Number of points in mesh ($numPoints) and number of field tuples ($numFieldTuples) don't agree"
1571                return 0
1572            }
1573        } elseif { $_comp2assoc($cname) == "celldata" } {
1574            set numCells [$mesh numcells]
1575            if { $numCells != $numFieldTuples } {
1576                puts stderr "ERROR: Number of cells in mesh ($numCells) and number of field tuples ($numFieldTuples) don't agree"
1577                return 0
1578            }
1579        }
1580        set _comp2dims($cname) "[$mesh dimensions]D"
1581        set _comp2mesh($cname) [list $mesh $v]
1582        set _comp2style($cname) [$_field get $cname.style]
1583        if {[$_field element $cname.flow] != ""} {
1584            set _comp2flowhints($cname) \
1585                [Rappture::FlowHints ::\#auto $_field $cname $_units]
1586        }
1587        incr _counter
1588        array unset _comp2limits $cname
1589        foreach axis { x y z } {
1590            lappend _comp2limits($cname) $axis [$mesh limits $axis]
1591        }
1592        set minmax [VectorLimits $v $_comp2size($cname)]
1593        lappend _comp2limits($cname) $cname $minmax
1594        lappend _comp2limits($cname) v $minmax
1595        return 1
1596    }
1597    if {$_dim == 3} {
1598        # 3D data: By default isosurfaces plot using isosurface widget.
1599        if { $_viewer == "" } {
1600            set _viewer "isosurface"
1601        }
1602        set v [blt::vector create \#auto]
1603        $v set [$_field get $cname.values]
1604        if { [$v length] == 0 } {
1605            return 0
1606        }
1607        set numFieldValues [$v length]
1608        set numComponentsPerTuple [numComponents $cname]
1609        if { [expr $numFieldValues % $numComponentsPerTuple] != 0 } {
1610            puts stderr "ERROR: Number of field values ($numFieldValues) not divisble by elemsize ($numComponentsPerTuple)"
1611            return 0
1612        }
1613        set numFieldTuples [expr $numFieldValues / $numComponentsPerTuple]
1614        if { $_comp2assoc($cname) == "pointdata" } {
1615            set numPoints [$mesh numpoints]
1616            if { $numPoints != $numFieldTuples } {
1617                puts stderr "ERROR: Number of points in mesh ($numPoints) and number of field tuples ($numFieldTuples) don't agree"
1618                return 0
1619            }
1620        } elseif { $_comp2assoc($cname) == "celldata" } {
1621            set numCells [$mesh numcells]
1622            if { $numCells != $numFieldTuples } {
1623                puts stderr "ERROR: Number of cells in mesh ($numCells) and number of field tuples ($numFieldTuples) don't agree"
1624                return 0
1625            }
1626        }
1627        set _comp2dims($cname) "[$mesh dimensions]D"
1628        set _comp2mesh($cname) [list $mesh $v]
1629        set _comp2style($cname) [$_field get $cname.style]
1630        if {[$_field element $cname.flow] != ""} {
1631            set _comp2flowhints($cname) \
1632                [Rappture::FlowHints ::\#auto $_field $cname $_units]
1633        }
1634        incr _counter
1635        foreach axis { x y z } {
1636            lappend _comp2limits($cname) $axis [$mesh limits $axis]
1637        }
1638        set minmax [VectorLimits $v $_comp2size($cname)]
1639        lappend _comp2limits($cname) $cname $minmax
1640        lappend _comp2limits($cname) v $minmax
1641        return 1
1642    }
1643    error "unhandled case in field dim=$_dim element=$element"
1644}
1645
1646itcl::body Rappture::Field::AvsToVtk { cname contents } {
1647    package require vtk
1648
1649    set reader $this-datasetreader
1650    vtkAVSucdReader $reader
1651
1652    # Write the contents to a file just in case it's binary.
1653    set tmpfile $cname[pid].ucd
1654    set f [open "$tmpfile" "w"]
1655    fconfigure $f -translation binary -encoding binary
1656    puts $f $contents
1657    close $f
1658    $reader SetFileName $tmpfile
1659    $reader Update
1660    file delete $tmpfile
1661
1662    set tmpfile $cname[pid].vtk
1663    set writer $this-datasetwriter
1664    vtkDataSetWriter $writer
1665    $writer SetInputConnection [$reader GetOutputPort]
1666    $writer SetFileName $tmpfile
1667    $writer Write
1668    rename $reader ""
1669    rename $writer ""
1670
1671    set f [open "$tmpfile" "r"]
1672    fconfigure $f -translation binary -encoding binary
1673    set vtkdata [read $f]
1674    close $f
1675    file delete $tmpfile
1676    return $vtkdata
1677}
1678
1679itcl::body Rappture::Field::DicomToVtk { cname path } {
1680    package require vtk
1681
1682    if { ![file exists $path] } {
1683        puts stderr "path \"$path\" doesn't exist."
1684        return 0
1685    }
1686
1687    if { [file isdir $path] } {
1688        set files [glob -nocomplain $path/*.dcm]
1689        if { [llength $files] == 0 } {
1690            set files [glob -nocomplain $path/*]
1691            if { [llength $files] == 0 } {
1692                puts stderr "no dicom files found in \"$path\""
1693                return 0
1694            }
1695        }
1696
1697        #array set data [Rappture::DicomToVtk files $files]
1698        array set data [Rappture::DicomToVtk dir $path]
1699    } else {
1700        array set data [Rappture::DicomToVtk files [list $path]]
1701    }
1702
1703    if 0 {
1704        foreach key [array names data] {
1705            if {$key == "vtkdata"} {
1706                if 0 {
1707                    set f [open /tmp/$cname.vtk "w"]
1708                    fconfigure $f -translation binary -encoding binary
1709                    puts -nonewline $f $data(vtkdata)
1710                    close $f
1711                }
1712            } else {
1713                puts stderr "$key = \"$data($key)\""
1714            }
1715        }
1716    }
1717
1718    # Save viewer choice
1719    set viewer $_viewer
1720    ReadVtkDataSet $cname $data(vtkdata)
1721    # Restore viewer choice (ReadVtkDataSet wants to set it to contour/isosurface)
1722    set _viewer $viewer
1723    return $data(vtkdata)
1724}
1725
1726itcl::body Rappture::Field::GetTypeAndSize { cname } {
1727    array set type2components {
1728        "colorscalars"         4
1729        "normals"              3
1730        "scalars"              1
1731        "tcoords"              2
1732        "tensors"              9
1733        "vectors"              3
1734    }
1735    set type [$_field get $cname.elemtype]
1736    if { $type == "" } {
1737        set type "scalars"
1738    }
1739    if { ![info exists type2components($type)] } {
1740        error "unknown <elemtype> \"$type\" in field"
1741    }
1742    set size [$_field get $cname.elemsize]
1743    if { $size == "" } {
1744        set size $type2components($type)
1745    }
1746    set _comp2type($cname) $type
1747    set _comp2size($cname) $size
1748}
1749
1750itcl::body Rappture::Field::GetAssociation { cname } {
1751    set assoc [$_field get $cname.association]
1752    if { $assoc == "" } {
1753        set _comp2assoc($cname) "pointdata"
1754        return
1755    }
1756    switch -- $assoc {
1757        "pointdata" - "celldata" - "fielddata" {
1758            set _comp2assoc($cname) $assoc
1759            return
1760        }
1761        default {
1762            error "unknown field association \"$assoc\""
1763        }
1764    }
1765}
1766
1767#
1768# Compute the per-component limits or limits of vector magnitudes
1769#
1770itcl::body Rappture::Field::VectorLimits {vector vectorsize {comp -1}} {
1771    if {$vectorsize == 1} {
1772        set minmax [$vector limits]
1773    } else {
1774        set len [$vector length]
1775        if {[expr $len % $vectorsize] != 0} {
1776            error "Invalid vectorsize: $vectorsize"
1777        }
1778        if {$comp > $vectorsize-1} {
1779            error "Invalid vector component: $comp"
1780        }
1781        set numTuples [expr ($len/$vectorsize)]
1782        for {set i 0} {$i < $numTuples} {incr i} {
1783            if {$comp >= 0} {
1784                set idx [expr ($i * $vectorsize + $comp)]
1785                set val [$vector index $idx]
1786            } else {
1787                set idx [expr ($i * $vectorsize)]
1788                set mag 0
1789                for {set j 0} {$j < $vectorsize} {incr j} {
1790                    set val [$vector index $idx]
1791                    set mag [expr ($mag + $val * $val)]
1792                    incr idx
1793                }
1794                set val [expr (sqrt($mag))]
1795            }
1796            if (![info exists minmax]) {
1797                set minmax [list $val $val]
1798            } else {
1799                if {$val < [lindex $minmax 0]} {
1800                    lset minmax 0 $val
1801                }
1802                if {$val > [lindex $minmax 1]} {
1803                    lset minmax 1 $val
1804                }
1805            }
1806        }
1807    }
1808    return $minmax
1809}
Note: See TracBrowser for help on using the repository browser.