Manta Interactive Ray Tracer Development Mailing List

Text archives Help


[MANTA] r1176 - in trunk: . CMake Core/Geometry Interface Model/Cameras Model/Groups Model/Materials Model/Primitives Model/Readers SwigInterface fox fox/raytree_demo fox/raytree_demo/Core fox/raytree_demo/Core/RayTree fox/raytree_demo/Engine fox/raytree_demo/Engine/Renderers fox/raytree_demo/StandAlone histx scenes


Chronological Thread 
  • From: abe@sci.utah.edu
  • To: manta@sci.utah.edu
  • Subject: [MANTA] r1176 - in trunk: . CMake Core/Geometry Interface Model/Cameras Model/Groups Model/Materials Model/Primitives Model/Readers SwigInterface fox fox/raytree_demo fox/raytree_demo/Core fox/raytree_demo/Core/RayTree fox/raytree_demo/Engine fox/raytree_demo/Engine/Renderers fox/raytree_demo/StandAlone histx scenes
  • Date: Sun, 13 Aug 2006 22:22:49 -0600 (MDT)

Author: abe
Date: Sun Aug 13 22:22:40 2006
New Revision: 1176

Added:
   trunk/Model/Groups/Build_KDTreeDyn.cc
   trunk/Model/Groups/Build_KDTreeDyn.h
   trunk/Model/Groups/KDTreeDyn.cc
      - copied, changed from r1156, trunk/Model/Groups/KDTree2.cc
   trunk/Model/Groups/KDTreeDyn.h
      - copied, changed from r1156, trunk/Model/Groups/KDTree2.h
   trunk/Model/Groups/Load_IW_KDTreeDyn.cc
   trunk/Model/Groups/Load_OBJ_KDTreeDyn.cc
   trunk/Model/Groups/Load_OBJ_KDTreeDyn.h
   trunk/SwigInterface/KDTreeDynFrame.py
   trunk/SwigInterface/kdtreedyn.py
      - copied, changed from r1160, trunk/SwigInterface/runwxmanta.py
   trunk/SwigInterface/wxManta.cc
   trunk/SwigInterface/wxManta.h
   trunk/SwigInterface/wxManta_helper.i
   trunk/fox/raytree_demo/
   trunk/fox/raytree_demo/CMakeLists.txt
   trunk/fox/raytree_demo/Core/
   trunk/fox/raytree_demo/Core/RayTree/
   trunk/fox/raytree_demo/Core/RayTree/RayEntry.h
   trunk/fox/raytree_demo/Core/RayTree/RayStream.cc
   trunk/fox/raytree_demo/Core/RayTree/RayStream.h
   trunk/fox/raytree_demo/Engine/
   trunk/fox/raytree_demo/Engine/Renderers/
   trunk/fox/raytree_demo/Engine/Renderers/RayStreamRenderer.cc
      - copied, changed from r1130, trunk/Engine/Renderers/Raytracer.cc
   trunk/fox/raytree_demo/Engine/Renderers/RayStreamRenderer.h
      - copied, changed from r1130, trunk/Engine/Renderers/Raytracer.h
   trunk/fox/raytree_demo/StandAlone/
   trunk/fox/raytree_demo/StandAlone/record_stream.cc
      - copied, changed from r1130, trunk/StandAlone/manta.cc
Removed:
   trunk/Model/Readers/ObjReader.cc
   trunk/Model/Readers/ObjReader.h
   trunk/histx/
Modified:
   trunk/   (props changed)
   trunk/CMake/Macros.cmake
   trunk/Core/Geometry/Vector.h
   trunk/Interface/RayPacket.h
   trunk/Model/Cameras/PinholeCamera.cc
   trunk/Model/Groups/CMakeLists.txt
   trunk/Model/Groups/Group.h
   trunk/Model/Materials/Transparent.cc
   trunk/Model/Primitives/CMakeLists.txt
   trunk/Model/Primitives/Plane.h
   trunk/Model/Primitives/Triangle.h
   trunk/SwigInterface/CMakeLists.txt
   trunk/SwigInterface/manta.i
   trunk/SwigInterface/wxManta.py
   trunk/fox/CMakeLists.txt
   trunk/scenes/CMakeLists.txt
Log:


_M   .
M    CMake/Macros.cmake

Added accessor which returns a non-reference. This allows SWIG to
translate the return value into a python native type.
M    Core/Geometry/Vector.h

Modified wxManta to allow it to be easily called from other scripts
M    SwigInterface/manta.i
A    SwigInterface/wxManta.cc
A    SwigInterface/wxManta_helper.i
A    SwigInterface/wxManta.h
M    SwigInterface/wxManta.py
M    SwigInterface/CMakeLists.txt

Ray tree trace code.
A    fox/raytree_demo
A    fox/raytree_demo/Engine
A    fox/raytree_demo/Engine/Renderers
A    fox/raytree_demo/Engine/Renderers/RayStreamRenderer.cc
A    fox/raytree_demo/Engine/Renderers/RayStreamRenderer.h
A    fox/raytree_demo/Core
A    fox/raytree_demo/Core/RayTree
A    fox/raytree_demo/Core/RayTree/RayEntry.h
A    fox/raytree_demo/Core/RayTree/RayStream.cc
A    fox/raytree_demo/Core/RayTree/RayStream.h
A    fox/raytree_demo/StandAlone
A    fox/raytree_demo/StandAlone/record_stream.cc
A    fox/raytree_demo/CMakeLists.txt
M    fox/CMakeLists.txt

Deleted histx from top of trunk hasn't been touched since r537
D    histx

Added a kdtree implementation with build code. This is an unoptimized
C++ version of both the traversal (based on kdtree2) and build
A    Model/Groups/Build_KDTreeDyn.cc
A    Model/Groups/Load_OBJ_KDTreeDyn.h
A    Model/Groups/Load_IW_KDTreeDyn.cc
M    Model/Groups/CMakeLists.txt
A    Model/Groups/KDTreeDyn.cc
A    Model/Groups/KDTreeDyn.h
A    Model/Groups/Build_KDTreeDyn.h
A    Model/Groups/Load_OBJ_KDTreeDyn.cc

Added python script for kdtreedyn

python ../SwigInterface/kdtreedyn.py --file=/home/abe/models/defender-ext.obj 
--depth_threshold=30 -n 2

A    SwigInterface/kdtreedyn.py
A    SwigInterface/KDTreeDynFrame.py

Modifications for python integration
M    Model/Groups/Group.h
M    Model/Materials/Transparent.cc
M    Model/Primitives/Plane.h
M    Model/Primitives/CMakeLists.txt
M    Model/Primitives/Triangle.h
M    Model/Cameras/PinholeCamera.cc
M    Interface/RayPacket.h

More unused code. There are several places in the code that read obj
files and they all use glm.
D    Model/Readers/ObjReader.cc
D    Model/Readers/ObjReader.h


Modified: trunk/CMake/Macros.cmake
==============================================================================
--- trunk/CMake/Macros.cmake    (original)
+++ trunk/CMake/Macros.cmake    Sun Aug 13 22:22:40 2006
@@ -40,4 +40,26 @@
   IF(${VARIABLE})
     SUBDIRS(${DIRS})
   ENDIF(${VARIABLE})
-ENDMACRO(SUBDIRS_IF)
\ No newline at end of file
+ENDMACRO(SUBDIRS_IF)
+
+
+MACRO(PYTHON_POST_BUILD_COPY PY_FILE)
+   # Copy the python object to the lib directory.
+   ADD_CUSTOM_COMMAND(
+      POST_BUILD
+      OUTPUT       ${PROJECT_BINARY_DIR}/lib/${PY_FILE}
+      # DEPENDS must match the source file that will change.
+      DEPENDS      ${CMAKE_CURRENT_SOURCE_DIR}/${PY_FILE}
+      COMMAND      ${CMAKE_COMMAND}
+      ARGS -E copy ${CMAKE_CURRENT_SOURCE_DIR}/${PY_FILE}
+                   ${PROJECT_BINARY_DIR}/lib/${PY_FILE}
+      COMMENT "Copying ${PY_FILE} to ${PROJECT_BINARY_DIR}/lib/${PY_FILE}"
+      )  
+
+   ADD_CUSTOM_TARGET(
+      copy_${PY_FILE}
+      ALL
+      # DEPENDS Must match custom command OUTPUT.
+      DEPENDS ${PROJECT_BINARY_DIR}/lib/${PY_FILE} 
+      )
+ENDMACRO(PYTHON_POST_BUILD_COPY PY_FILE)
\ No newline at end of file

Modified: trunk/Core/Geometry/Vector.h
==============================================================================
--- trunk/Core/Geometry/Vector.h        (original)
+++ trunk/Core/Geometry/Vector.h        Sun Aug 13 22:22:40 2006
@@ -98,6 +98,9 @@
     Real z() const {
       return data[2];
     }
+    Real get(int i) const {
+      return data[i];
+    }
 
 #ifndef SWIG
     const Real& operator[] (int i) const {

Modified: trunk/Interface/RayPacket.h
==============================================================================
--- trunk/Interface/RayPacket.h (original)
+++ trunk/Interface/RayPacket.h Sun Aug 13 22:22:40 2006
@@ -2,6 +2,35 @@
 #ifndef Manta_Interface_RayPacket_h
 #define Manta_Interface_RayPacket_h
 
+/*
+  For more information, please see: http://software.sci.utah.edu
+
+  The MIT License
+
+  Copyright (c) 2005-2006
+  Scientific Computing and Imaging Institute, University of Utah
+
+  License for the specific language governing rights and limitations under
+  Permission is hereby granted, free of charge, to any person obtaining a
+  copy of this software and associated documentation files (the "Software"),
+  to deal in the Software without restriction, including without limitation
+  the rights to use, copy, modify, merge, publish, distribute, sublicense,
+  and/or sell copies of the Software, and to permit persons to whom the
+  Software is furnished to do so, subject to the following conditions:
+
+  The above copyright notice and this permission notice shall be included
+  in all copies or substantial portions of the Software.
+
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+  DEALINGS IN THE SOFTWARE.
+*/
+
+
 #include <Core/Color/Color.h>
 #include <Core/Geometry/Ray.h>
 #include <Core/Geometry/VectorT.h>
@@ -620,7 +649,7 @@
     int flags;
   };
 
-  typedef Color::ComponentType 
ColorArray[Color::NumComponents][RayPacket::MaxSize];
+  typedef MANTA_ALIGN(16) Color::ComponentType 
ColorArray[Color::NumComponents][RayPacket::MaxSize];
 
 } // end namespace Manta
 

Modified: trunk/Model/Cameras/PinholeCamera.cc
==============================================================================
--- trunk/Model/Cameras/PinholeCamera.cc        (original)
+++ trunk/Model/Cameras/PinholeCamera.cc        Sun Aug 13 22:22:40 2006
@@ -362,9 +362,10 @@
 
 void PinholeCamera::dolly(Real scale)
 {
+  // Better make sure the scale isn't exactly one.
   Vector d = (lookat - eye) * scale;
   eye    += d;
-        // lookat += d; // Maybe we need two types of dolly. // Maybe not.
+
   setup();
 }
 

Added: trunk/Model/Groups/Build_KDTreeDyn.cc
==============================================================================
--- (empty file)
+++ trunk/Model/Groups/Build_KDTreeDyn.cc       Sun Aug 13 22:22:40 2006
@@ -0,0 +1,486 @@
+/*
+  For more information, please see: http://software.sci.utah.edu
+
+  The MIT License
+
+  Copyright (c) 2005-2006
+  Scientific Computing and Imaging Institute, University of Utah
+
+  License for the specific language governing rights and limitations under
+  Permission is hereby granted, free of charge, to any person obtaining a
+  copy of this software and associated documentation files (the "Software"),
+  to deal in the Software without restriction, including without limitation
+  the rights to use, copy, modify, merge, publish, distribute, sublicense,
+  and/or sell copies of the Software, and to permit persons to whom the
+  Software is furnished to do so, subject to the following conditions:
+
+  The above copyright notice and this permission notice shall be included
+  in all copies or substantial portions of the Software.
+
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+  DEALINGS IN THE SOFTWARE.
+*/
+
+#include <Model/Groups/Build_KDTreeDyn.h>
+
+#include <SCIRun/Core/Math/MinMax.h>
+#include <SCIRun/Core/Thread/Time.h>
+
+
+#include <limits>
+#include <iostream>
+
+using namespace std;
+using namespace SCIRun;
+using namespace Manta;
+
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+// FIND SPLIT APPROX CC  FIND SPLIT APPROX CC  FIND SPLIT APPROX CC  FIND 
SPLIT
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+
+enum { MaxCandidates = 8 };
+
+int find_split_approx_cc( const BoundsList &geometry,
+                          const IndexList  &indices,
+
+                          const BBox &parent_bounds,
+                          const int dim,
+                           
+                          // Output arguments, 
+                          Real candidate[MaxCandidates],
+                          Real costs    [MaxCandidates],
+
+                          Integer left_size,
+                          Integer right_size )
+{
+
+  
/////////////////////////////////////////////////////////////////////////////
+  // Determine where the candidate split planes are.
+  const Vector extent = (parent_bounds[1] - parent_bounds[0]);
+  const Vector delta  = (parent_bounds[1] - parent_bounds[0]) * 
((Real)1.0)/((Real)MaxCandidates);
+
+  // Real candidates[MaxCandidates];
+  for (int i=0;i<MaxCandidates;++i) {
+    candidate[i] = parent_bounds[0][dim] + (delta[dim] * (Real)i);
+  }
+
+  // Initialize counters.
+  size_t left_side [MaxCandidates];
+  size_t right_side[MaxCandidates];
+
+  for (int i=0;i<MaxCandidates;++i) {
+    left_side[i]  = 0;
+    right_side[i] = 0;
+  }
+
+  
/////////////////////////////////////////////////////////////////////////////
+  // Iterate over the indices
+  for (size_t index=0;index<indices.size();++index) {
+
+    const BBox &bounds = geometry[ indices[index] ];
+    
+    // Iterate over the candidates.
+    for (int i=0;i<MaxCandidates;++i) {
+      
+      const Real &candidate_split = candidate[i];
+
+      // Check the left and right split candidates.
+      left_side[i]  += ((bounds.getMin()[dim] <= candidate_split));
+      right_side[i] += ((bounds.getMax()[dim] > candidate_split));
+    }
+  }
+
+  
/////////////////////////////////////////////////////////////////////////////
+  // Compute cost of each split candidate.
+  Real min_cost = std::numeric_limits<Real>::max();
+  int  min_candidate;
+
+  const int dim0 = (dim+1)%3;
+  const int dim1 = (dim+2)%3;
+
+  const Real ends_area = extent[dim0] * extent[dim1] * 2;
+  const Real cross_section  = (extent[dim0] + extent[dim1]) * 2;
+  
+  for (int i=0;i<MaxCandidates;++i) {
+
+    const Real left_area  = (candidate[i] - parent_bounds[0][dim]) * 
cross_section + ends_area;
+    const Real right_area = (parent_bounds[1][dim] - candidate[i]) * 
cross_section + ends_area;
+
+    costs[i] =
+      (Real)(left_side[i])*(left_area) +
+      (Real)(right_side[i])*(right_area);
+
+    if (min_cost > costs[i]) {
+      min_cost = costs[i];
+      min_candidate = i;
+    }
+  }
+
+  left_size = left_side[min_candidate];
+  right_size = right_side[min_candidate];
+  
+  return min_candidate;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+// SAH SPLIT  SAH SPLIT  SAH SPLIT  SAH SPLIT  SAH SPLIT  SAH SPLIT  SAH 
SPLIT 
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+
+#if 0
+
+// It would be better to sort split candidates:
+class Candidate {
+public:
+  Candidate( Real split_, size_t index_, int flags_ ) :
+    split( split_ ), index( index_ ), flags( flags_ ) { };
+  
+  Real   split;
+  unsigned int index;
+
+  // Flags to indicate if area of related triangle should be
+  // added/subtracted to left or right sum.
+  enum {LeftBound,Middle,RightBound};
+  int    flags;
+
+  inline bool operator < (const Candidate &c ) const { return split < 
c.split; }
+};
+
+
+void sah_find_candidates( TriangleList &geometry, IndexList axis[3] ) {
+
+  // Find candidates.
+  // for (int i=0;i<)
+
+  // Sort candidates.
+  start_time = Time::currentSeconds();
+  for (int i=0;i<3;++i) {
+    sort(axis[i].begin(),axis[i].end());
+  }
+  end_time = Time::currentSeconds();
+
+  // Eliminate duplicate candidates.
+  
+
+  std::cerr << "sah sort time " << (end_time-start_time) << std::endl;
+}
+
+void sah_split( const BBox &node_bounds, int dim ) {
+
+  // Precompute node surface area constants.
+  const Vector extent = (node_bounds[1] - node_bounds[0]);
+  const int dim0 = (dim+1)%3;
+  const int dim1 = (dim+2)%3;
+  
+  const Real ends_area = extent[dim0] * extent[dim1] * 2;
+  const Real cross_section = 2*(extent[dim0] + extent[dim1]);
+
+  // 
+
+  
+  for (int index=0;index<triangle_array.size();index+=delta) {
+
+    const Triangle & triangle = triangle_array[index];
+    
+    // Iterate over bounding box faces.
+      
+      Real candidate_split = triangle_array[index].bounds[0][dim];
+
+      Real left_side = 0;
+      Real right_side = 0;
+      
+      // Iterate over all triangles and sum up surface area.
+      for (int i=0;i<triangle_array.size();++i) {
+        if ((triangle_array[i].bounds[0][dim] <= candidate_split)) {
+          left_side += triangle_array[i].area;
+        }
+        if ((triangle_array[i].bounds[1][dim] > candidate_split)) {
+          right_side += triangle_array[i].area;
+        }
+      }
+
+      // Compute the node surface area      
+      const Real left_area  = (candidate_split - model_bounds[0][dim]) * 
cross_section + ends_area;
+      const Real right_area = (model_bounds[1][dim] - candidate_split) * 
cross_section + ends_area;
+      
+      const Real cost =
+        (Real)(left_side)*(left_area) +
+        (Real)(right_side)*(right_area);
+
+      // Output the candidate.
+      file << candidate_split << "\t"
+           << cost
+           << std::endl;
+
+  }
+  file.close();  
+}
+
+#endif 
+
+
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+// BUCKET SORT  BUCKET SORT  BUCKET SORT  BUCKET SORT  BUCKET SORT  BUCKET 
SORT
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+
+void bucket_sort_cc( const BoundsList  &geometry,
+                     
+                     const IndexList &source_indices,
+                     IndexList &left_indices,
+                     IndexList &right_indices,
+                     
+                     const Real split, const int dim )
+{
+  const int source_size = source_indices.size();
+  
+  left_indices.clear();
+  right_indices.clear();
+
+  
+  for (int i=0;i<source_size;++i) {
+
+    const Integer index = source_indices[i];
+    const BBox &bounds = geometry[index];
+
+    if (bounds[0][dim] < split) {
+      left_indices.push_back( index );
+    }
+    
+    if (bounds[1][dim] > split)
+      right_indices.push_back( index );
+  }
+
+}
+
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+// BUILD APPROX CC  BUILD APPROX CC  BUILD APPROX CC  BUILD APPROX CC  BUILD 
AP
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+
+
+void Approx_cc::build( KDTreeDyn *kdtree  ) {
+
+  Real start_time = Time::currentSeconds();
+  
+  const BoundsList &bounds_list = kdtree->bounds_list;
+  
+  Integer max_depth = 0;
+  Integer max_leaf_size = 0;
+  Integer total_nodes = 0;
+  Integer total_leaves = 0;
+  Integer total_indices = 0;
+  Integer heuristic_trigger = 0;
+
+  
/////////////////////////////////////////////////////////////////////////////
+  // Create a build_stack.
+  vector<Frame *> build_stack;
+  build_stack.reserve( 128 );
+  
+  
/////////////////////////////////////////////////////////////////////////////
+  // Add the root node to the build stack.
+  {
+    // Allocate the root node.
+    NodeOffset root_offset = kdtree->allocateNodePair();
+
+    // Allocate the root stack frame.
+    Frame *root_frame = new Frame( kdtree->bbox,
+                                   root_offset,
+                                   0 );
+
+    // Create initial index list in the root frame.
+    root_frame->array.resize( bounds_list.size() );
+
+    for (int i=0;i<bounds_list.size();++i)
+      root_frame->array[i] = i;
+    
+    // Push the root frame on the stack.
+    build_stack.push_back( root_frame );
+  }
+
+  
/////////////////////////////////////////////////////////////////////////////
+  // Initialize candidate arrays.
+  Real candidate[MaxCandidates];
+  Real costs    [MaxCandidates];
+
+  
/////////////////////////////////////////////////////////////////////////////
+  
/////////////////////////////////////////////////////////////////////////////
+  // Build Loop
+  
/////////////////////////////////////////////////////////////////////////////
+  
/////////////////////////////////////////////////////////////////////////////
+  while (build_stack.size()) {
+
+    // Get the next frame off the stack.
+    Frame *frame = build_stack.back();
+    build_stack.pop_back();
+
+    bool break_out = false;
+    
+    // Drill down until a leaf is found.
+    while (1) {
+
+      
///////////////////////////////////////////////////////////////////////////
+      // Check to see if this node is a leaf.
+      if ((frame->array.size() < leaf_threshold) || // Condition: Leaf 
threshold.
+          (frame->depth >= depth_threshold)      || // Condition: Depth 
threshold.
+          (break_out)
+          ) {
+          
+        
+        // How to check for heuristic performance?
+        
+        
///////////////////////////////////////////////////////////////////////
+        // Set leaf fields.
+        KDTreeType::Node &leaf = kdtree->getNode(frame->node);
+
+        // Copy the index list.
+        leaf.listBegin = kdtree->allocateLeafList( frame->array );
+        leaf.listLen   = frame->array.size();
+        leaf.type      = KDTreeType::LeafType;
+
+        // DEBUG
+        leaf.size      = leaf.listLen;
+
+        // Update stats
+        total_indices += frame->array.size();
+        max_leaf_size = SCIRun::Max( max_leaf_size, frame->array.size() );
+        ++total_leaves;
+
+        // Delete the frame.
+        delete frame;
+
+        break;
+      }
+      else {
+        
+        
///////////////////////////////////////////////////////////////////////////   
 
+        // Find best split.
+        Real min_split;
+        Real min_dim;
+        Real min_cost = std::numeric_limits<Real>::max();
+
+        Integer min_left_size;
+        Integer min_right_size;
+        
+        for (int d=0;d<3;++d) {
+
+          Integer left_size = 0;
+          Integer right_size = 0;
+          
+          const int initial = find_split_approx_cc( bounds_list,
+                                                    frame->array,
+                                                    frame->bounds,
+                                                    d,
+                                                    candidate,
+                                                    costs,
+                                                    left_size,
+                                                    right_size );
+
+          // *** Refinement step goes here ***
+
+          // Check for min cost.
+          if (costs[initial] < min_cost) {
+            min_cost  = costs[initial];
+            min_split = candidate[initial];
+            min_dim   = d;
+
+            min_left_size = left_size;
+            min_right_size = right_size;
+          }
+        }
+
+        // Check to see if the heuristic is improving anything.
+        if (min_left_size == min_right_size == frame->array.size()) {
+
+          heuristic_trigger++;
+          
+          break_out = true;
+          continue;          
+        }
+        
+        const Real split = min_split;
+        const int dim = min_dim;
+        
+        
///////////////////////////////////////////////////////////////////////
+        // Allocate two children.
+        NodeOffset left_child_offset = kdtree->allocateNodePair();
+
+        // Update parent pointer.
+        KDTreeType::Node &parent_node = kdtree->getNode( frame->node );
+        
+        parent_node.size  = frame->array.size();
+        parent_node.leftOffset = left_child_offset;
+
+        // Allocate a new Stack frame for the right child.
+        Frame *left_frame  = new Frame( frame->bounds, left_child_offset, 
frame->depth+1 );
+        Frame *right_frame = new Frame( frame->bounds, left_child_offset+1, 
frame->depth+1 );
+
+        
///////////////////////////////////////////////////////////////////////
+        // Use the existing frame for the left child and bucket sort.
+
+        // frame->array.reserve( min_left_size );
+        // right_frame->array.reserve( min_right_size );
+        
+        bucket_sort_cc( bounds_list,
+                        frame->array,
+                        left_frame->array,
+                        right_frame->array,
+                        split, dim );
+        
+        // Set the node split and axis fields.
+        parent_node.split = split;
+        parent_node.type  = dim;
+        
+        // Update the bounds of both child frames.
+        left_frame->bounds[1][dim] = split;
+        right_frame->bounds[0][dim] = split;
+
+        // Push the right frame on the stack.
+        build_stack.push_back( right_frame );
+
+        Frame *old = frame;
+        frame = left_frame;
+        delete old;
+        
+        // Update stats.
+        total_nodes += 2;
+        max_depth = SCIRun::Max( max_depth, frame->depth );
+      
+      } // End if leaf else.
+
+    } // End drill down until a leaf.
+    
+  } // End build stack loop.
+
+  Real end_time = Time::currentSeconds();
+
+  std::cerr << "Build information: " << std::endl
+            << "max_depth     " << max_depth     << " (threshold " << 
depth_threshold << ")" << std::endl
+            << "max_leaf_size " << max_leaf_size << " (threshold " << 
leaf_threshold  << ")" << std::endl
+            << "avg_leaf_size " << 
((Real)total_indices)/((Real)total_leaves) << std::endl
+            << "total_nodes   " << total_nodes   << std::endl
+            << "total_leaves  " << total_leaves  << std::endl
+            << "total_indices " << total_indices << std::endl
+            << "total faces   " << kdtree->triangles.size() << std::endl
+            << "heuristic     " << heuristic_trigger << std::endl
+            << "build time    " << (end_time-start_time) << "s" << std::endl;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+// TEMPLATES  TEMPLATES  TEMPLATES  TEMPLATES  TEMPLATES  TEMPLATES  
TEMPLATES 
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+
+
+

Added: trunk/Model/Groups/Build_KDTreeDyn.h
==============================================================================
--- (empty file)
+++ trunk/Model/Groups/Build_KDTreeDyn.h        Sun Aug 13 22:22:40 2006
@@ -0,0 +1,69 @@
+/*
+  For more information, please see: http://software.sci.utah.edu
+
+  The MIT License
+
+  Copyright (c) 2005-2006
+  Scientific Computing and Imaging Institute, University of Utah
+
+  License for the specific language governing rights and limitations under
+  Permission is hereby granted, free of charge, to any person obtaining a
+  copy of this software and associated documentation files (the "Software"),
+  to deal in the Software without restriction, including without limitation
+  the rights to use, copy, modify, merge, publish, distribute, sublicense,
+  and/or sell copies of the Software, and to permit persons to whom the
+  Software is furnished to do so, subject to the following conditions:
+
+  The above copyright notice and this permission notice shall be included
+  in all copies or substantial portions of the Software.
+
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+  DEALINGS IN THE SOFTWARE.
+*/
+
+#include <MantaTypes.h>
+#include <Core/Geometry/BBox.h>
+#include <Model/Groups/KDTreeDyn.h>
+#include <SCIRun/Core/Exceptions/Exception.h>
+
+
+namespace Manta {
+  
+  // Class containing build method.
+  class Approx_cc {
+  public:
+    typedef KDTreeDyn KDTreeType;
+    
+
+    enum { MaxCandidates = 8 };
+    
+    // Thresholds.
+    int leaf_threshold;
+    int depth_threshold;
+
+    // Build frame.
+    struct Frame {
+      Frame( const BBox &bounds_,  NodeOffset node_, Integer depth_ ) :
+        bounds( bounds_ ), node( node_ ), depth( depth_ ) { };
+      
+      IndexList  array;
+      BBox       bounds;
+      NodeOffset node;
+      Integer    depth;
+    };
+    
+    // Constructors.
+    Approx_cc( int leaf_threshold_, int depth_threshold_ ) :
+      leaf_threshold( leaf_threshold_ ),
+      depth_threshold( depth_threshold_ ) { }
+    
+    // Build methods.
+    void build( KDTreeType *kdtree ) throw(SCIRun::Exception&);
+  };
+};
+

Modified: trunk/Model/Groups/CMakeLists.txt
==============================================================================
--- trunk/Model/Groups/CMakeLists.txt   (original)
+++ trunk/Model/Groups/CMakeLists.txt   Sun Aug 13 22:22:40 2006
@@ -8,6 +8,10 @@
   
 
 SET (Manta_Groups_SRCS
+     Groups/Build_KDTreeDyn.h
+     Groups/Build_KDTreeDyn.cc
+     Groups/Load_OBJ_KDTreeDyn.h
+     Groups/Load_OBJ_KDTreeDyn.cc
      Groups/BVH.cc
      Groups/BVH.h
      Groups/DynBVH.h
@@ -18,6 +22,8 @@
      Groups/Group.h
      Groups/KDTree.cc
      Groups/KDTree.h
+     Groups/KDTreeDyn.cc
+     Groups/KDTreeDyn.h
      Groups/KDTreeLoader.cc
      Groups/KDTreeLoader.h
      Groups/KDTreeLoaderIW.cc

Modified: trunk/Model/Groups/Group.h
==============================================================================
--- trunk/Model/Groups/Group.h  (original)
+++ trunk/Model/Groups/Group.h  Sun Aug 13 22:22:40 2006
@@ -2,6 +2,35 @@
 #ifndef Manta_Model_Group_h
 #define Manta_Model_Group_h
 
+/*
+  For more information, please see: http://software.sci.utah.edu
+
+  The MIT License
+
+  Copyright (c) 2005-2006
+  Scientific Computing and Imaging Institute, University of Utah
+
+  License for the specific language governing rights and limitations under
+  Permission is hereby granted, free of charge, to any person obtaining a
+  copy of this software and associated documentation files (the "Software"),
+  to deal in the Software without restriction, including without limitation
+  the rights to use, copy, modify, merge, publish, distribute, sublicense,
+  and/or sell copies of the Software, and to permit persons to whom the
+  Software is furnished to do so, subject to the following conditions:
+
+  The above copyright notice and this permission notice shall be included
+  in all copies or substantial portions of the Software.
+
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+  DEALINGS IN THE SOFTWARE.
+*/
+
+
 #include <Interface/Object.h>
 #include <sgi_stl_warnings_off.h>
 #include <vector>
@@ -30,6 +59,7 @@
                                BBox& bbox) const;
 
     static Group* create(const vector<string>& args);
+
   protected:
     vector<Object*> objs;
   };

Copied: trunk/Model/Groups/KDTreeDyn.cc (from r1156, 
trunk/Model/Groups/KDTree2.cc)
==============================================================================
--- trunk/Model/Groups/KDTree2.cc       (original)
+++ trunk/Model/Groups/KDTreeDyn.cc     Sun Aug 13 22:22:40 2006
@@ -26,7 +26,7 @@
   DEALINGS IN THE SOFTWARE.
 */
 
-#include <Model/Groups/KDTree2.h>
+#include <Model/Groups/KDTreeDyn.h>
 #include <Interface/RayPacket.h>
 #include <Model/Intersections/AxisAlignedBox.h>
 #include <Core/Color/ColorSpace.h>
@@ -35,114 +35,30 @@
 
 #include <Core/Math/MiscMath.h>
 
-#include <stdlib.h>
+#include <Core/Geometry/Vector.h>
 
+#include <stdlib.h>
 #include <stack>
-
 #include <iostream>
 
 using namespace Manta;
 using namespace SCIRun;
 using namespace std;
 
-KDTree2::KDTree2(Material* material_in)
-  : PrimitiveCommon( material_in ),
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+// TRIANGLE IW  TRIANGLE IW  TRIANGLE IW  TRIANGLE IW  TRIANGLE IW  TRIANGLE 
IW
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
 
-    triangles(NULL), num_tris(0),
-    tri_indices(NULL), num_tri_indices(0),
-    group_ids(NULL),
-    group_colors(NULL), num_groups(0)
-{
-}
-
-int
-KDTree2::loadIW(IWObject* iw, IWTree* tree) {
-  // Allocate memory
-  reserveTriangles(iw->triangles.size());
-  reserveTriangleIndices(tree->num_tri_indices);
-  reserveGroupIDs();
-  reserveGroupColors(iw->shaders.size());
-  unsigned int num_nodes = tree->num_nodes + tree->num_empty_nodes;
-  Node* nodes = static_cast<Node*>(malloc(num_nodes*sizeof(Node)));
-  rootNode = nodes;
 
-  bbox.reset();
-  
-  // Load in the triangles
-  for(size_t ti = 0; ti < iw->triangles.size(); ++ti) {
-    Vector va(iw->va(ti));
-    Vector vb(iw->vb(ti));
-    Vector vc(iw->vc(ti));
-
-    // Do bounding box extension
-    bbox.extendByPoint(va);
-    bbox.extendByPoint(vb);
-    bbox.extendByPoint(vc);
-
-    // Create the triangle and copy it over
-    Triangle tri(va, vc, vb);
-    triangles[ti] = tri;
 
-    // Copy of the color id
-    group_ids[ti] = iw->triangles[ti][3];
-  }
-
-  // Load in the colors
-  for(size_t ci = 0; ci < iw->shaders.size(); ++ci) {
-    group_colors[ci] = iw->shaders[ci];
-  }
-
-  // Load in the kd-tree data
-  Node* current_node = nodes;
-  unsigned int current_node_index = 0;
-  unsigned int current_tri_index = 0;
-
-  IWNode* top = tree->head;
-  top->index = current_node_index++;
-  std::stack<IWNode*> nodestack;
-  nodestack.push(top);
-  while(!nodestack.empty()) {
-    Node& node = nodes[top->index];
-    if (top->isNode()) {
-      // Node
-      node.type = top->flags;
-      node.split = top->split;
-
-      // Assign the left and right nodes
-      node.leftChild = nodes + current_node_index;
-      // For relative references you can do this:
-      // node.leftChild = current_node_index - top->index;
-
-      ASSERT(top->left);
-      ASSERT(top->right);
-      top->left->index  = current_node_index++;
-      top->right->index = current_node_index++;
-
-      // Push the children on the stack
-      nodestack.push(top->right);
-      nodestack.push(top->left);
-      
-    } else {
-      // Leaf
-      node.type = 3;
-      node.listLen = top->num_tris;
-      node.listBegin = current_tri_index;
-      unsigned int* tri_ids_p = tri_indices + current_tri_index;
-      for(unsigned int i = 0; i < node.listLen; ++i) {
-        tri_ids_p[i] = top->tri_ids[i];
-      }
-      current_tri_index += node.listLen;
-    }
-    top = nodestack.top();
-    nodestack.pop();
-  }
 
-  return 0;
-}
+using SCIRun::Abs;
 
-KDTree2::Triangle::Triangle(const Vector& _p1,
-                            const Vector& _p2,
-                            const Vector& _p3)
+TriangleIW::TriangleIW( const Vector& _p1,
+                        const Vector& _p2,
+                        const Vector& _p3 )
 {
   Vector normal = Cross(_p2-_p1, _p3-_p1);
   normal.normalize();
@@ -190,9 +106,20 @@
   n_k = normal[k];
 }
 
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+// KDTREE DYN  KDTREE DYN  KDTREE DYN  KDTREE DYN  KDTREE DYN  KDTREE DYN  
KDTR
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+
+KDTreeDyn::KDTreeDyn(Material* material_in)
+  : PrimitiveCommon( material_in ), root_node( 0 ), root_offset( 0 )
+{
+}
+
 // Inherited from PrimitiveCommon
-void
-KDTree2::intersect(const RenderContext& context, RayPacket& rays) const {
+void KDTreeDyn::intersect(const RenderContext& context, RayPacket& rays) 
const {
+
   rays.normalizeDirections();
   rays.computeInverseDirections();
   rays.computeSigns();
@@ -213,7 +140,7 @@
         maxDist = SCIRun::Min( maxDist, rays.getMinT(i) );
         if (minDist > maxDist) continue;
 
-        intersect_node( rootNode,
+        intersect_node( &node_list[root_offset],
                         rays,
                         i,
                         (float)minDist,
@@ -223,9 +150,10 @@
   }
 }
 
-void
-KDTree2::intersect_node( Node* start_node, RayPacket& rays, int which,
+
+void KDTreeDyn::intersect_node( const Node* start_node, RayPacket& rays, int 
which,
                          float minDist, float maxDist ) const {
+
   float near = minDist;
   float far  = maxDist;
   
@@ -250,13 +178,13 @@
   const Node* node = const_cast<const Node*>(start_node);
 
   do {
-    while (node->type != 3 /* leaf */ ) {
+    while (node->type != LeafType) {
       const int axis = node->type;
 
       const float dist = (node->split - origin[axis]) * invDir[axis];
       
-      const Node* const nearChild = node->leftChild + ray_signs[axis];
-      const Node* const farChild  = node->leftChild + (1-ray_signs[axis]);
+      const Node* const nearChild = &node_list[node->leftOffset] + 
ray_signs[axis];
+      const Node* const farChild  = &node_list[node->leftOffset] + 
(1-ray_signs[axis]);
       
       if (dist > far) // if interval (far end) is infront of the plane
         {
@@ -284,53 +212,30 @@
     if (node->listLen > 0) {
       int hit_tri = -1;
       float minT = data->minT[which];
-//       fprintf(stderr, "node(%u): listBegin = %u, listLen = %u\n",
-//               (rootNode-node)/sizeof(Node), node->listBegin, 
node->listLen);
+
+      //       fprintf(stderr, "node(%u): listBegin = %u, listLen = %u\n",
+      //               (rootNode-node)/sizeof(Node), node->listBegin, 
node->listLen);
+
+      // Intersect the ray with each triangle.
       for (int tri_index=node->listBegin;
            tri_index<node->listBegin+node->listLen;
            ++tri_index) {
-        //            intersectTriangle(....); // with mailboxing
-        const Triangle& tri = triangles[tri_indices[tri_index]];
-        const int axis = tri.k;
-        const int ku = (axis==2)?0:axis+1;
-        const int kv = (axis==0)?2:axis-1;
-          
-        const float n_u    = tri.n_u;
-        const float n_v    = tri.n_v;
-        const float n_d    = tri.n_d;
-            
-        const float org_k  = origin[axis];
-        const float org_ku = origin[ku];
-        const float org_kv = origin[kv];
-        const float f0     = n_d - (org_k + n_u * org_ku + n_v * org_kv);
-
-        const float dir_k  = direction[axis];
-        const float dir_ku = direction[ku];
-        const float dir_kv = direction[kv];
-
-        const float nd0 = n_u * dir_ku + n_v * dir_kv + dir_k;
-        const float nd  = 1.f/nd0;
-
-        const float f = f0 * nd;
-        // plane test
-        if ( f < T_EPSILON || f > minT )
-          continue;
 
-        const float hu = org_ku + f*dir_ku;
-        const float hv = org_kv + f*dir_kv;
-        const float lambda = tri.b_d + hu*tri.b_nu + hv * tri.b_nv;
-
-        // barycentric test
-        if ( lambda < 0.f )
-          continue;
+        
////////////////////////////////////////////////////////////////////////
 
-        const float mue = tri.c_d + hu * tri.c_nu + hv * tri.c_nv;
-        if ( mue < 0.f || mue + lambda > 1.f )
+        const Triangle& tri = triangles[index_list[tri_index]];
+        
+        float f;        
+        if (!tri.intersect_single_ray( *(const Vector *)(origin),
+                                       *(const Vector *)(direction), minT, f 
)) {
           continue;
-
+        }
+        
+        
////////////////////////////////////////////////////////////////////////      
  
+        
         // Is this the nearest triangle?
         if (f < minT) {
-          hit_tri = tri_indices[tri_index];
+          hit_tri = index_list[tri_index];
           minT = f;
         }
       }
@@ -356,12 +261,17 @@
   } while (1);
 }
 
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+// TRIANGLE IW TEMPLATE  TRIANGLE IW TEMPLATE  TRIANGLE IW TEMPLATE  
TRIANGLE I
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
 
 void
-KDTree2::computeNormal(const RenderContext& context, RayPacket& rays) const {
+KDTreeDyn::computeNormal(const RenderContext& context, RayPacket& rays) 
const {
   RayPacketData* data = rays.data;
   for ( int ray = rays.begin(); ray < rays.end(); ray++ ) {
-    const Triangle& tri = 
triangles[rays.scratchpad<ScratchData>(ray).tri_index];
+    const TriangleIW& tri = 
triangles[rays.scratchpad<ScratchData>(ray).tri_index];
     
     const int axis = tri.k;
     const int ku   = (axis==2)?0:axis+1;
@@ -375,80 +285,22 @@
   rays.setFlag(RayPacket::HaveUnitNormals);
 }
 
-// Returns 0 on success
-int
-KDTree2::reserveTriangles(unsigned int num_tris_in) {
-  triangles = static_cast<Triangle*>(malloc(num_tris_in*sizeof(Triangle)));
-  if (triangles) {
-    num_tris = num_tris_in;
-    return 0;
-  } else {
-    return 1;
-  }
-}
-        
-// Returns 0 on success
-int
-KDTree2::reserveTriangleIndices(unsigned int num_tri_indices_in) {
-  tri_indices =
-    static_cast<unsigned int*>(malloc(num_tri_indices_in*sizeof(unsigned 
int)));
-  if (tri_indices) {
-    num_tri_indices = num_tri_indices_in;
-    return 0;
-  } else {
-    return 1;
-  }
-}
-
-// Returns 0 on success
-int
-KDTree2::reserveGroupIDs() {
-  if (!num_tris)
-    // Haven't said how many triangles yet
-    return 1;
-  group_ids = static_cast<unsigned int*>(malloc(num_tris*sizeof(unsigned 
int)));
-  if (!group_ids)
-    return 1;
-  return 0;
-}
 
-// Returns 0 on success
-int
-KDTree2::reserveGroupColors(unsigned int num_groups_in) {
-  group_colors = static_cast<Color*>(malloc(num_groups_in*sizeof(Color)));
-  if (group_colors) {
-    num_groups = num_groups_in;
-    return 0;
-  } else {
-    return 1;
-  }
-}
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+// TEXTURE  TEXTURE  TEXTURE  TEXTURE  TEXTURE  TEXTURE  TEXTURE  TEXTURE  
TEXT
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
 
 void
-KDTree2Texture::mapValues(Packet<Color>& results,
+KDTreeDynTexture::mapValues(Packet<Color>& results,
                            const RenderContext&,
                            RayPacket& rays) const
 {
-  if (kdtree->group_ids && kdtree->group_colors) {
-    // Have group ids and colors
-    const unsigned int* group_ids = kdtree->group_ids;
-    const Color* group_colors     = kdtree->group_colors;
-    
-    for ( int ray = rays.begin(); ray < rays.end(); ++ray) {
-      unsigned int tri_index = 
rays.scratchpad<KDTree2::ScratchData>(ray).tri_index;
-      const int group_id = group_ids[tri_index];
-      results.set(ray, group_colors[group_id]);
-    }
-  } else {
-    // No colors, so just assign something
-    Color default_color(RGBColor(0.7, 0.7, 0.7 ));
-    for ( int ray = rays.begin(); ray < rays.end(); ++ray) {
-      results.set(ray, default_color);
-    }
+  // No colors, so just assign something
+  Color default_color(RGBColor(0.7, 0.7, 0.7 ));
+  for ( int ray = rays.begin(); ray < rays.end(); ++ray) {
+    results.set(ray, default_color);
   }
-    
 }
-
-
-
 

Copied: trunk/Model/Groups/KDTreeDyn.h (from r1156, 
trunk/Model/Groups/KDTree2.h)
==============================================================================
--- trunk/Model/Groups/KDTree2.h        (original)
+++ trunk/Model/Groups/KDTreeDyn.h      Sun Aug 13 22:22:40 2006
@@ -26,8 +26,8 @@
   DEALINGS IN THE SOFTWARE.
 */
 
-#ifndef Manta_Groups_KDTree2_h
-#define Manta_Groups_KDTree2_h
+#ifndef Manta_Groups_KDTreeDyn_h
+#define Manta_Groups_KDTreeDyn_h
 
 #include <Model/Primitives/PrimitiveCommon.h>
 #include <Core/Geometry/Vector.h>
@@ -35,114 +35,247 @@
 #include <Core/Geometry/BBox.h>
 #include <Interface/Texture.h>
 
+#include <Interface/Parameters.h>
+#include <SCIRun/Core/Util/Assert.h>
+
+
+#include <vector>
+
 namespace Manta {
 
-  class IWObject;
-  class IWTree;
+  
/////////////////////////////////////////////////////////////////////////////
+  
/////////////////////////////////////////////////////////////////////////////
+  // TRIANGLE IW  TRIANGLE IW  TRIANGLE IW  TRIANGLE IW  TRIANGLE IW  
TRIANGLE 
+  
/////////////////////////////////////////////////////////////////////////////
+  
///////////////////////////////////////////////////////////////////////////// 
 
   
-  class KDTree2 : public PrimitiveCommon {
+  class TriangleIW {
   public:
+    
+    float n_u;
+    float n_v;
+    float n_d;
+    unsigned int k;
+    
+    float b_nu;
+    float b_nv;
+    float b_d;
+    float n_k;
+    
+    float c_nu;
+    float c_nv;
+    float c_d;
 
-    KDTree2(Material* material);
-    // Return 0 on success
-    int loadIW(IWObject*, IWTree*);
+    TriangleIW() {}
+    TriangleIW(const Vector& _p1, const Vector& _p2, const Vector& _p3);
     
-    enum {
-      MaxStackSize = 128
-    };
+    
///////////////////////////////////////////////////////////////////////////
+    // Single ray intersection.
+    // Returns true if the ray intersects the triangle, returns false 
otherwise.
+    // Mangles output parameter t in either case.
+    
///////////////////////////////////////////////////////////////////////////
+    inline
+    bool intersect_single_ray( // Input.
+                               const Vector &origin,
+                               const Vector &direction,
+                               const float &minT,
+
+                               // Output.
+                               float &t ) const {
+
+      int axis = k;
+      const int ku = (axis==2)?0:axis+1;
+      const int kv = (axis==0)?2:axis-1;
+            
+      const float org_k  = origin[axis];
+      const float org_ku = origin[ku];
+      const float org_kv = origin[kv];
+      const float f0     = n_d - (org_k + n_u * org_ku + n_v * org_kv);
+      
+      const float dir_k  = direction[axis];
+      const float dir_ku = direction[ku];
+      const float dir_kv = direction[kv];
+      
+      const float nd0 = n_u * dir_ku + n_v * dir_kv + dir_k;
+      const float nd  = 1.f/nd0;
+      
+      t = f0 * nd;
 
-    struct Node {
-      union {
-        Node *leftChild; // rigth_son = left_son+1;
-        int listBegin;
-      };
-      union {
-        float split; // internal
-        int listLen; // leaf
-      };
-      unsigned char type; // 0=x,1=y,z=2,leaf=3
-    };
+      // plane test
+      if ( t < T_EPSILON || t > minT )
+        return false;
+      
+      const float hu = org_ku + t*dir_ku;
+      const float hv = org_kv + t*dir_kv;
+      const float lambda = b_d + hu*b_nu + hv * b_nv;
+      
+      // barycentric test
+      if ( lambda < 0.f )
+        return false;
+      
+      const float mue = c_d + hu * c_nu + hv * c_nv;
+      if ( mue < 0.f || mue + lambda > 1.f )
+        return false;
+
+      return true;
+    }
+  };  
+  
+  
+  
/////////////////////////////////////////////////////////////////////////////
+  
/////////////////////////////////////////////////////////////////////////////
+  // KDTREE DYN  KDTREE DYN  KDTREE DYN  KDTREE DYN  KDTREE DYN  KDTREE DYN  
KD
+  
/////////////////////////////////////////////////////////////////////////////
+  
/////////////////////////////////////////////////////////////////////////////
+
+  
+  using std::vector;
+  
+  typedef unsigned int Integer;
+  typedef unsigned int NodeOffset;
+  typedef unsigned int IndexOffset;
+  
+  typedef vector<BBox>     BoundsList;
+  typedef vector<Integer>  IndexList;
+  
+  
/////////////////////////////////////////////////////////////////////////////
+  // Outside class definitions for SWIG
+  
/////////////////////////////////////////////////////////////////////////////
+
+  struct KDTreeDyn_Leaf {
+    IndexOffset listBegin;
+    Integer     listLen;
+  };
 
-    class Triangle {
-    public:
-      Triangle() {}
-      Triangle(const Vector& _p1, const Vector& _p2, const Vector& _p3);
-      
-      float n_u;
-      float n_v;
-      float n_d;
-      unsigned int k;
-
-      float b_nu;
-      float b_nv;
-      float b_d;
-      float n_k;
-
-      float c_nu;
-      float c_nv;
-      float c_d;
+  struct KDTreeDyn_Internal {
+    NodeOffset leftOffset;
+    float      split;
+  };
+  
+  struct KDTreeDyn_Node {
+    union {
+      NodeOffset  leftOffset; // Always even. Right child offset is 
leftOffset+1;
+      IndexOffset listBegin;
+    };
+    union {
+      float   split;          // internal
+      Integer listLen;        // leaf
     };
+    unsigned char type; // 0=x,1=y,z=2,leaf=3
+    
+    int size; // DEBUG ONLY!!!
+    
+    KDTreeDyn_Leaf &leaf()         { return *(KDTreeDyn_Leaf*)this; }
+    KDTreeDyn_Internal &internal() { return *(KDTreeDyn_Internal*)this; }
+  };
+
+  struct KDTreeDyn_ScratchData {
+    unsigned int tri_index;
+  };
 
-    struct ScratchData {
-      unsigned int tri_index;
+  
/////////////////////////////////////////////////////////////////////////////
+  // Class Definition
+  
/////////////////////////////////////////////////////////////////////////////
+  class KDTreeDyn : public PrimitiveCommon {
+  public:
+    typedef TriangleIW Triangle;
+    
+    enum {
+      MaxStackSize = 128,
+      LeafType     = 3
     };
     
-    // Inherited from PrimitiveCommon
-    virtual void computeBounds(const PreprocessContext& /*context*/,
-                               BBox& bbox_in) const
-    {
-      bbox_in.extendByBox(bbox);
+    typedef vector<Triangle> TriangleList;
+
+    typedef KDTreeDyn_Node        Node;
+    typedef KDTreeDyn_ScratchData ScratchData;
+    
+    
///////////////////////////////////////////////////////////////////////////
+    // Public Interface
+
+    KDTreeDyn(Material* material);
+
+    // Intersection interface.
+    virtual void computeBounds(const PreprocessContext&, BBox& bbox_in) 
const { bbox_in.extendByBox(bbox); }
+    virtual void intersect(const RenderContext& context, RayPacket& rays) 
const ;    
+    virtual void computeNormal(const RenderContext& context, RayPacket 
&rays) const;
+    
+    // Accessors.
+    void setRootOffset( NodeOffset offset_ ) { root_offset = offset_; }
+    NodeOffset getRootOffset() { return root_offset; }
+
+    Node &getNode( const NodeOffset &offset ) {
+
+      ASSERT( offset < node_list.size() );
+      return node_list[offset];
     }
-      
-    virtual void intersect(const RenderContext& context,
-                           RayPacket& rays) const ;
-    virtual void computeNormal(const RenderContext& context,
-                               RayPacket &rays) const;    
-
-    // Returns 0 on success
-    int reserveTriangles(unsigned int num_tris_in);
-    int reserveTriangleIndices(unsigned int num_tri_indices_in);
-    int reserveGroupIDs();
-    int reserveGroupColors(unsigned int num_groups_in);
-    
-    // Triangle list stuff
-    Triangle*     triangles;    // size == num_tris
-    unsigned int  num_tris;
-    unsigned int* tri_indices;  // size == num_tri_indices
-    unsigned int  num_tri_indices;
-
-    // Group
-    unsigned int* group_ids;    // size == num_tris;
-                                // group_ids[i] = [0,num_groups-1]
-    Color*        group_colors; // size == num_groups;
-    unsigned int  num_groups;
 
-    // Root node
-    Node* rootNode;
+    BBox bbox;                // Bounds of the whole kdtree.
+    
+#ifndef SWIG        
+    // Build interface.
+    void resetBuild()            { index_list.clear(); };
+    
+    NodeOffset  allocateNodePair() {
+
+      // Allocate another two nodes
+      NodeOffset offset = node_list.size();      
+      node_list.resize( offset+2 );
+
+      return offset;
+    }
+    
+    IndexOffset allocateLeafList( IndexList &array ) {
+
+      const Integer offset = index_list.size();
+
+      // Insert the indices.
+      index_list.insert( index_list.end(), array.begin(), array.end() );
+            
+      return offset;
+    };
+
+    
///////////////////////////////////////////////////////////////////////////
+    // Data Members.
     
-    BBox bbox;
+    // Intialized at construction/geometry update.
+    TriangleList triangles;
+    BoundsList   bounds_list; // Stored in the same order as the 
TriangleList.
+    
+    // Initialized at build time.
+    NodeOffset   root_offset;
+    Node *       root_node;
+    vector<Node> node_list;
+    IndexList    index_list;
+
 
+    
   protected:
-    void intersect_node(Node* start_node, RayPacket& rays, int which,
-                        float minDist, float maxDist) const;
+    void intersect_node( const Node* start_node, RayPacket& rays, int which,
+                         float minDist, float maxDist) const;
 
     struct Stack {
       const Node* node;
       float far;
     };
-  };
 
-  class KDTree2Texture: public Texture<Color> {
-  public:
-    KDTree2Texture(): kdtree(0) {}
+#endif // Swig    
+  };
     
+  
/////////////////////////////////////////////////////////////////////////////
+  // KDTREE DYN TEXTURE  KDTREE DYN TEXTURE  KDTREE DYN TEXTURE  KDTREE DYN 
TEX
+  
/////////////////////////////////////////////////////////////////////////////
+  
+  class KDTreeDynTexture: public Texture<Color> {
+  public:
     virtual void mapValues(Packet<Color>& results,
                            const RenderContext&,
                            RayPacket& rays) const;
 
-    KDTree2* kdtree;
   };
+
+
   
 } // end namespace Manta
 
-#endif // Manta_Groups_KDTree2_h
+#endif // Manta_Groups_KDTreeDyn_h

Added: trunk/Model/Groups/Load_IW_KDTreeDyn.cc
==============================================================================
--- (empty file)
+++ trunk/Model/Groups/Load_IW_KDTreeDyn.cc     Sun Aug 13 22:22:40 2006
@@ -0,0 +1,123 @@
+#include <Model/Groups/Load_IW_KDTreeDyn.h>
+
+#include <SCIRun/Core/Util/Assert.h>
+#include <Model/Readers/IW.h>
+
+#include <string>
+#include <iostream>
+#include <stack>
+
+using namespace Manta;
+using namespace std;
+using namespace SCIRun;
+
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+// IW LOADER  IW LOADER  IW LOADER  IW LOADER  IW LOADER  IW LOADER  IW 
LOADER 
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+
+void Manta::load_iw_KDTreeDyn( const string &file_name, 
KDTreeDyn<TriangleIW> &kdtree ) {
+
+  string iw_file_name = file_name  + ".iw";
+  string bsp_file_name = file_name + ".bsp";
+  
+  // Load the IW object.
+  IWObject* iw = IWObjectRead(iw_file_name.c_str());
+  if (!iw) {
+    cerr << "Error reading file : "<<iw_file_name<<".\n";
+    return;
+  }
+  
+  // Load the bsp tree.
+  IWTree* tree = IWTreeRead(bsp_file_name.c_str());
+  if (!tree) {
+    cerr << "Error reading file : "<<bsp_file_name<<".\n";
+    return;
+  }
+
+  // Call the actual loader.
+  return load_iw_KDTreeDyn( iw, tree, kdtree );
+}
+
+void Manta::load_iw_KDTreeDyn( IWObject* iw, IWTree* tree, 
KDTreeDyn<TriangleIW> &kdtree ) {
+
+  typedef KDTreeDyn<TriangleIW> KDTreeType;
+  
+  // Allocate memory for triangles.
+  kdtree.triangles.resize(iw->num_triangles);
+  
+  // Allocate memory for indices.
+  kdtree.index_list.resize(iw->num_indices);
+
+  // Allocate memory for nodes.
+  unsigned int num_nodes = tree->num_nodes + tree->num_empty_nodes;
+  kdtree.node_list 
+
+  // Set root node pointer.
+  kdtree.rootNode = nodes;
+  
+  // Load in the triangles
+  kdtree.bbox.reset();
+  for(size_t ti = 0; ti < iw->triangles.size(); ++ti) {
+    Vector va(iw->va(ti));
+    Vector vb(iw->vb(ti));
+    Vector vc(iw->vc(ti));
+
+    // Do bounding box extension
+    kdtree.bbox.extendByPoint(va);
+    kdtree.bbox.extendByPoint(vb);
+    kdtree.bbox.extendByPoint(vc);
+
+    // Create the triangle and copy it over
+    TriangleIW tri(va, vc, vb);
+    kdtree.triangles[ti] = tri;
+  }
+
+  // Load in the kd-tree data
+  KDTreeType::Node* current_node = nodes;
+  unsigned int current_node_index = 0;
+  unsigned int current_tri_index = 0;
+
+  // Copy the IWTree into the KDTreeType using a stack of nodes.
+  IWNode* top = tree->head;
+  top->index = current_node_index++;
+  std::stack<IWNode*> nodestack;
+  nodestack.push(top);
+
+  while(!nodestack.empty()) {
+    KDTreeType::Node& node = nodes[top->index];
+    if (top->isNode()) {
+      // Node
+      node.type = top->flags;
+      node.split = top->split;
+
+      // Assign the left and right nodes
+      node.leftChild = nodes + current_node_index;
+      // For relative references you can do this:
+      // node.leftChild = current_node_index - top->index;
+
+      ASSERT(top->left);
+      ASSERT(top->right);
+      top->left->index  = current_node_index++;
+      top->right->index = current_node_index++;
+
+      // Push the children on the stack
+      nodestack.push(top->right);
+      nodestack.push(top->left);
+      
+    } else {
+      // Leaf
+      node.type = 3;
+      node.listLen = top->num_tris;
+      node.listBegin = current_tri_index;
+      unsigned int* tri_ids_p = kdtree.tri_indices + current_tri_index;
+      for(unsigned int i = 0; i < node.listLen; ++i) {
+        tri_ids_p[i] = top->tri_ids[i];
+      }
+      current_tri_index += node.listLen;
+    }
+    top = nodestack.top();
+    nodestack.pop();
+  }
+}

Added: trunk/Model/Groups/Load_OBJ_KDTreeDyn.cc
==============================================================================
--- (empty file)
+++ trunk/Model/Groups/Load_OBJ_KDTreeDyn.cc    Sun Aug 13 22:22:40 2006
@@ -0,0 +1,61 @@
+
+#include <Model/Groups/Load_OBJ_KDTreeDyn.h>
+
+#include <Model/Groups/KDTreeDyn.h>
+
+#include <SCIRun/Core/Util/Assert.h>
+#include <SCIRun/Core/Exceptions/FileNotFound.h>
+#include <Model/Readers/glm/glm.h>
+
+#include <iostream>
+
+using namespace Manta;
+using namespace SCIRun;
+using namespace Glm;
+using namespace std;
+
+void Manta::load_obj_KDTreeDyn( const char *file_name , KDTreeDyn *kdtree ) {
+
+  // Read the model
+  GLMmodel *model = glmReadOBJ( file_name );
+  if (model == 0) {
+    throw FileNotFound( file_name, __FILE__, __LINE__ );
+  }
+  
+  // Allocate storage for triangles and bounds.
+  size_t total_faces = model->numtriangles;
+
+  kdtree->triangles.resize( total_faces );
+  kdtree->bounds_list.resize( total_faces );
+  
+  // Copy out triangles.
+  for (int triangle_index=0;triangle_index<total_faces;++triangle_index) {
+
+    Vector vertex[3];
+
+    BBox &bbox = kdtree->bounds_list[triangle_index];
+    
+    // Collect all the vertices in a triangle.
+    for (int v=0;v<3;++v) {
+      int    index = model->triangles[ triangle_index ].vindices[v];
+      float *f     = model->vertices+(index*3);
+
+      // Copy out the vertex.
+      vertex[v][0] = f[0];
+      vertex[v][1] = f[1];
+      vertex[v][2] = f[2];
+
+      bbox.extendByPoint( vertex[v] );
+    }
+
+    // Add the triangle.
+    kdtree->triangles[triangle_index] = TriangleIW( vertex[0], vertex[1], 
vertex[2] );
+    kdtree->bbox.extendByBox( bbox );
+  }
+
+  // Delete the glm data structure.
+  glmDelete( model );
+
+  std::cerr << "Loaded " << kdtree->triangles.size() << " faces." << 
std::endl;
+
+}

Added: trunk/Model/Groups/Load_OBJ_KDTreeDyn.h
==============================================================================
--- (empty file)
+++ trunk/Model/Groups/Load_OBJ_KDTreeDyn.h     Sun Aug 13 22:22:40 2006
@@ -0,0 +1,18 @@
+
+#ifndef MODEL_GROUPS_LOAD_OBJ_KDTREEDYN__H
+#define MODEL_GROUPS_LOAD_OBJ_KDTREEDYN__H
+
+
+#include <Model/Groups/KDTreeDyn.h>
+
+#include <Interface/Object.h>
+
+namespace Manta {
+
+  // Load a .obj file into the KDTreeDyn. The tree must be built before 
rendering.
+  void load_obj_KDTreeDyn( const char *file_name , KDTreeDyn *kdtree );
+
+
+};
+
+#endif

Modified: trunk/Model/Materials/Transparent.cc
==============================================================================
--- trunk/Model/Materials/Transparent.cc        (original)
+++ trunk/Model/Materials/Transparent.cc        Sun Aug 13 22:22:40 2006
@@ -69,7 +69,7 @@
   color->mapValues(diffuse, context, rays);
 
   // Compute ambient contributions for all rays
-  ColorArray totalLight;
+  MANTA_ALIGN(16) ColorArray totalLight;
   activeLights->getAmbientLight()->computeAmbient(context, rays, totalLight);
 
   // We normalized directions for proper dot product computation.

Modified: trunk/Model/Primitives/CMakeLists.txt
==============================================================================
--- trunk/Model/Primitives/CMakeLists.txt       (original)
+++ trunk/Model/Primitives/CMakeLists.txt       Sun Aug 13 22:22:40 2006
@@ -22,8 +22,6 @@
      Primitives/OctreeVolume.h
      Primitives/IsosurfaceGridVolume.cc
      Primitives/IsosurfaceGridVolume.h
-     Primitives/IsosurfaceOctreeVolume.cc
-     Primitives/IsosurfaceOctreeVolume.h
      Primitives/Parallelogram.cc
      Primitives/Parallelogram.h
      Primitives/ParticleBVH.cc
@@ -47,3 +45,14 @@
      Primitives/WaldTriangle.h
      Primitives/WaldTriangle.cc
 )
+
+# IsosurfaceOctreeVolume appears broken in icc 9.1
+IF(INTEL_COMPILER_VERSION LESS 9.1)
+  SET(Manta_Primitives_SRCS
+      ${Manta_Primitives_SRCS}
+      Primitives/IsosurfaceOctreeVolume.cc
+      Primitives/IsosurfaceOctreeVolume.h
+     )
+ENDIF(INTEL_COMPILER_VERSION LESS 9.1)
+
+

Modified: trunk/Model/Primitives/Plane.h
==============================================================================
--- trunk/Model/Primitives/Plane.h      (original)
+++ trunk/Model/Primitives/Plane.h      Sun Aug 13 22:22:40 2006
@@ -42,6 +42,10 @@
                                BBox& bbox) const;
     virtual void intersect(const RenderContext& context, RayPacket& rays) 
const;
     virtual void computeNormal(const RenderContext& context, RayPacket& 
rays) const;
+
+    void setNormal( const Vector &normal_ ) { normal = normal_; }
+    void setCenter( const Vector &center_ ) { center = center_; }
+    
   private:
     Vector normal;
     Vector center;

Modified: trunk/Model/Primitives/Triangle.h
==============================================================================
--- trunk/Model/Primitives/Triangle.h   (original)
+++ trunk/Model/Primitives/Triangle.h   Sun Aug 13 22:22:40 2006
@@ -24,7 +24,6 @@
     virtual void intersect(const RenderContext& context, RayPacket& rays) 
const ;
     virtual void computeNormal(const RenderContext& context, RayPacket 
&rays) const;    
     
-  protected:
     Vector p1, p2, p3;
   };
 }

Modified: trunk/SwigInterface/CMakeLists.txt
==============================================================================
--- trunk/SwigInterface/CMakeLists.txt  (original)
+++ trunk/SwigInterface/CMakeLists.txt  Sun Aug 13 22:22:40 2006
@@ -27,76 +27,54 @@
 # parameter.  You can't use a variable set to "", because that will
 # get replaced with a null string and the SET_SOURCE_FILES_PROPERTIES
 # macro will barf.
-SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES SWIG_FLAGS "`/bin/echo 
\"\"`")
-SWIG_ADD_MODULE(example python
-  example.i example.cc)
-SWIG_LINK_LIBRARIES(example ${PYTHON_LIBRARIES})
 
+# SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES SWIG_FLAGS "`echo \"\"`")
+# SWIG_ADD_MODULE(example python example.i example.cc)
+# SWIG_LINK_LIBRARIES(example ${PYTHON_LIBRARIES})
+
+############################################################
+# Manta Swig/Python
 SET_SOURCE_FILES_PROPERTIES(manta.i PROPERTIES CPLUSPLUS ON)
 SET_SOURCE_FILES_PROPERTIES(manta.i PROPERTIES SWIG_FLAGS 
"-Wall;-DSCI_NOPERSISTENT")
-
 SWIG_ADD_MODULE(manta python manta.i manta.cc manta.h)
 
 SWIG_LINK_LIBRARIES(manta
   ${PYTHON_LIBRARIES}
-  Manta_Engine
-  Manta_Factory
-  Manta_UserInterface
-  Manta_Model
-  Manta_Image
-  Manta_Interface
-  Manta_Core
-  SCIRun_Core
+  ${MANTA_TARGET_LINK_LIBRARIES}
   ${CMAKE_THREAD_LIBS_INIT}
   ${OPENGL_LIBRARIES}
   ${X11_LIBRARIES}
   -lm)
+ADD_DEPENDENCIES(_manta ${MANTA_TARGET_LINK_LIBRARIES})
+
+PYTHON_POST_BUILD_COPY(runmanta.py)
+
+############################################################
+# wxManta Swig/Python
+
+# SET_SOURCE_FILES_PROPERTIES(wxManta_helper.i PROPERTIES CPLUSPLUS ON)
+# SET_SOURCE_FILES_PROPERTIES(wxManta_helper.i PROPERTIES SWIG_FLAGS 
"-Wall;-DSCI_NOPERSISTENT")
+# SWIG_ADD_MODULE(wxmanta_helper python wxManta_helper.i wxManta.cc 
wxManta.h)
+
+PYTHON_POST_BUILD_COPY(wxManta.py)
+PYTHON_POST_BUILD_COPY(runwxmanta.py)
+PYTHON_POST_BUILD_COPY(FloatSpin.py)
 
 ############################################################
 # Python callback code
 SET_SOURCE_FILES_PROPERTIES(pycallback.i PROPERTIES CPLUSPLUS ON)
 SET_SOURCE_FILES_PROPERTIES(pycallback.i PROPERTIES SWIG_FLAGS "-Wall")
-SWIG_ADD_MODULE(pycallback python
-  pycallback.i pycallback.cc pycallback.h)
+SWIG_ADD_MODULE(pycallback python pycallback.i pycallback.cc pycallback.h)
 SWIG_LINK_LIBRARIES(pycallback ${PYTHON_LIBRARIES})
 
 
-MACRO(PYTHON_POST_BUILD_COPY PY_FILE)
 
-   # Copy the python object to the lib directory.
-   ADD_CUSTOM_COMMAND(
-      POST_BUILD
-      OUTPUT       ${PROJECT_BINARY_DIR}/lib/${PY_FILE}
-      # DEPENDS must match the source file that will change.
-      DEPENDS      ${CMAKE_CURRENT_SOURCE_DIR}/${PY_FILE}
-      COMMAND      ${CMAKE_COMMAND}
-      ARGS -E copy ${CMAKE_CURRENT_SOURCE_DIR}/${PY_FILE}
-                   ${PROJECT_BINARY_DIR}/lib/${PY_FILE}
-      COMMENT "Copying ${PY_FILE} to ${PROJECT_BINARY_DIR}/lib/${PY_FILE}"
-      )  
-
-   ADD_CUSTOM_TARGET(
-      copy_${PY_FILE}
-      ALL
-      # DEPENDS Must match custom command OUTPUT.
-      DEPENDS ${PROJECT_BINARY_DIR}/lib/${PY_FILE} 
-      )
-                     
-
-                      
-   
-                    
-ENDMACRO(PYTHON_POST_BUILD_COPY PY_FILE)
 
 
 
-PYTHON_POST_BUILD_COPY(FloatSpin.py)
-PYTHON_POST_BUILD_COPY(wxManta.py)
-PYTHON_POST_BUILD_COPY(runmanta.py)
-PYTHON_POST_BUILD_COPY(runwxmanta.py)
-###############################################################################
 
 
+###############################################################################
 ENDIF (SWIG_FOUND)
 ENDIF("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" GREATER 1.9)
 ENDIF(BUILD_SWIG_INTERFACE)

Added: trunk/SwigInterface/KDTreeDynFrame.py
==============================================================================
--- (empty file)
+++ trunk/SwigInterface/KDTreeDynFrame.py       Sun Aug 13 22:22:40 2006
@@ -0,0 +1,206 @@
+import wx
+import wxManta
+
+from manta import *
+from pycallback import *
+
+###############################################################################
+###############################################################################
+# LIGHT FRAME          LIGHT FRAME          LIGHT FRAME          LIGHT FRAME 
  
+###############################################################################
+###############################################################################
        
+
+class KDTreeDynFrame(wx.Frame):
+    def __init__(self, parent, engine, kdtree):
+        wx.Frame.__init__(self, parent=parent, title="KDTreeDyn Explorer")
+
+        self.engine = engine
+        self.kdtree = kdtree
+        self.node_stack = []
+
+        # Intialize material array.
+        self.material = [  manta_new( Transparent( Color(RGBColor( 1.0, 0.0, 
0.0 )), 0.5 ) ),
+                           manta_new( Transparent( Color(RGBColor( 0.0, 1.0, 
0.0 )), 0.5 ) ),
+                           manta_new( Transparent( Color(RGBColor( 0.0, 0.0, 
1.0 )), 0.5 ) ) ]
+
+        
+
+        panel = wx.Panel(self,-1)
+        sizer = wx.BoxSizer(wx.VERTICAL)
+
+        # Create buttons.
+        reset = wx.Button(panel, -1, "Reset Root")
+        sizer.Add(reset,0,wx.EXPAND)
+        self.Bind(wx.EVT_BUTTON, self.OnResetRoot, reset)
+        
+        self.parent = wx.Button(panel, -1, "Parent")
+        sizer.Add(self.parent,0,wx.EXPAND)
+        self.Bind(wx.EVT_BUTTON, self.OnSetParent, self.parent)
+        
+        self.left = wx.Button(panel, -1, "Left")
+        sizer.Add(self.left,0,wx.EXPAND)
+        self.Bind(wx.EVT_BUTTON, self.OnSetLeft, self.left)        
+        
+        self.right = wx.Button(panel, -1, "Right")
+        sizer.Add(self.right,0,wx.EXPAND)
+        self.Bind(wx.EVT_BUTTON, self.OnSetRight, self.right)        
+
+        # Create a status bar.
+        self.status = self.CreateStatusBar()
+        
+        panel.SetSizerAndFit(sizer)
+        self.SetClientSize((256,128))
+
+        # Add a plane group.
+        self.plane_group = manta_new( Group() )
+
+        # Place the plane group in the scene.
+        self.plane_group.add( self.engine.getScene().getObject() )
+        self.engine.getScene().setObject( self.plane_group )
+
+        # Update plane.
+        self.engine.addTransaction( "update plane",
+                                    manta_new( createMantaTransaction( 
self.UpdateFrame,
+                                                                        () 
)))        
+
+    def UpdateFrame(self):
+        
+        # Get the current root node.
+        node = self.kdtree.getNode( self.kdtree.getRootOffset() )
+
+        # Update text.
+        axis = ("x", "y", "z")
+        if (node.type == KDTreeDyn.LeafType):
+            self.status.SetStatusText( "Leaf Depth: " + 
str(len(self.node_stack)) +
+                                       " Size: " + str(node.leaf().listLen) )
+        else:
+            self.status.SetStatusText( "Size: " + str(node.size) + " Axis: " 
+ axis[node.type] +
+                                       " Split: " + 
str(node.internal().split) )
+
+        self.MantaUpdatePlane()
+
+    
###########################################################################
+    
###########################################################################
+    # Transaction callback.
+    
###########################################################################
+    
###########################################################################
+
+    def printv( self, v ):
+        print str(v.x()) + " " + str(v.y()) + " " + str(v.z())
+
+    def MantaUpdatePlane(self):
+
+        # Get the current root node.
+        node = self.kdtree.getNode( self.kdtree.getRootOffset() )
+
+        # Check to see if the node is a leaf.
+        if (node.type != KDTreeDyn.LeafType):
+        
+            # Move the cutting plane.
+            anchor = Vector(self.kdtree.bbox.getMin())
+            anchor[node.type] = node.internal().split
+            
+            amax = Vector(self.kdtree.bbox.getMax())
+            amax[node.type] = node.internal().split
+            
+            diag = amax - anchor
+            
+            v1i = (node.type+1)%3
+            v2i = (node.type+2)%3
+            
+            v1 = Vector(diag)
+            v2 = Vector(diag)
+
+            v1[v1i] = 0
+            v2[v2i] = 0
+
+            # Create the parallelogram
+            parallelogram = manta_new(Parallelogram( 
self.material[node.type],
+                                                     anchor, v1, v2 ))
+            
+            # Preprocess
+            context = PreprocessContext( self.engine, 
self.engine.getScene().getLights() )
+            parallelogram.preprocess( context )
+            
+            # Check to see if the plane group already has a parallelogram.
+            if (self.plane_group.getSize() == 2):
+                old = self.plane_group.get(1)
+                manta_delete( old )
+                self.plane_group.set(1,parallelogram)
+            else:
+                self.plane_group.add(parallelogram)
+                
+    
###########################################################################
+    
###########################################################################
+    ## Event Callbacks
+    
###########################################################################
+    
###########################################################################
+
+    def OnResetRoot(self, event):
+
+        # Check that we're not already at the root.
+        if (len(self.node_stack) > 0):
+
+            # Reset the node stack.
+            offset = self.node_stack[0]
+            self.node_stack = []
+            
+            
+            self.engine.addTransaction( "reset root",
+                                        manta_new( createMantaTransaction( 
self.kdtree.setRootOffset,
+                                                                       
(offset, ) )))
+            self.engine.addTransaction( "Update",
+                                        manta_new( createMantaTransaction( 
self.UpdateFrame, () )))
+    def OnSetParent(self, event):
+
+        if (len(self.node_stack) > 0):
+            offset = self.node_stack.pop()
+
+            self.engine.addTransaction( "set parent",
+                                        manta_new( createMantaTransaction( 
self.kdtree.setRootOffset,
+                                                                       
(offset, ) )))
+            self.engine.addTransaction( "Update",
+                                        manta_new( createMantaTransaction( 
self.UpdateFrame, () )))
+            
+    def OnSetLeft(self, event):
+
+        # Get the current node.
+        node = self.kdtree.getNode( self.kdtree.getRootOffset() )
+
+        if (node.type != KDTreeDyn.LeafType):
+
+            # Push on stack.
+            self.node_stack.append( self.kdtree.getRootOffset() )
+            
+            # Get the left node.
+            offset = node.internal().leftOffset;
+
+            self.engine.addTransaction( "set left",
+                                        manta_new( createMantaTransaction( 
self.kdtree.setRootOffset,
+                                                                       
(offset, ) )))
+            self.engine.addTransaction( "Update",
+                                        manta_new( createMantaTransaction( 
self.UpdateFrame, () )))            
+
+    def OnSetRight(self, event):
+        
+        # Get the current node.
+        node = self.kdtree.getNode( self.kdtree.getRootOffset() )
+
+        if (node.type != KDTreeDyn.LeafType):
+
+            # Push on stack.
+            self.node_stack.append( self.kdtree.getRootOffset() )
+            
+            # Get the left node.
+            offset = node.internal().leftOffset+1;
+
+            self.engine.addTransaction( "set left",
+                                        manta_new( createMantaTransaction( 
self.kdtree.setRootOffset,
+                                                                       
(offset, ) )))
+            self.engine.addTransaction( "Update",
+                                        manta_new( createMantaTransaction( 
self.UpdateFrame, () )))
+
+
+
+
+            

Copied: trunk/SwigInterface/kdtreedyn.py (from r1160, 
trunk/SwigInterface/runwxmanta.py)
==============================================================================
--- trunk/SwigInterface/runwxmanta.py   (original)
+++ trunk/SwigInterface/kdtreedyn.py    Sun Aug 13 22:22:40 2006
@@ -1,21 +1,121 @@
 
 import wxManta
+import wx
 import getopt, sys
 
+from manta import *
+
+from KDTreeDynFrame import *
+
+###############################################################################
+###############################################################################
+# Global Options
+###############################################################################
+###############################################################################
+
+# Remember to declare these are "global" when defining them.
+file_name = ""
+leaf_threshold = 4
+depth_threshold = 16
+
+###############################################################################
+###############################################################################
+# Create Scene
+###############################################################################
+###############################################################################
+
+def initialize_scene( frame, engine ):
+
+    global leaf_threshold, depth_threshold
+
+    
###########################################################################
+    # Create basic scene with background.
+    scene = manta_new( Scene() )
+    scene.getRenderParameters().maxDepth = 5
+    
scene.setBackground(manta_new(ConstantBackground(ColorDB.getNamedColor("FloralWhite"))))
+
+    # Create lights.
+    lights = manta_new(LightSet())
+    lights.add(manta_new(PointLight(Vector(0,5,8), 
Color(RGBColor(.6,.1,.1)))))
+    lights.add(manta_new(PointLight(Vector(5,0,8), 
Color(RGBColor(.1,.6,.1)))))
+    lights.add(manta_new(PointLight(Vector(5,5,2), 
Color(RGBColor(.2,.2,.2)))))
+    lights.setAmbientLight(manta_new(ConstantAmbient(Color.black())))
+    scene.setLights(lights)
+
+    
###########################################################################
+    # Load in the model data.
+
+    red = manta_new(Phong(Color(RGBColor(0.6, 0, 0)),
+                          Color(RGBColor(0.6,0.6,0.6)),
+                          32, 0.4))
+
+    flat = manta_new(Flat(manta_new(NormalTexture())))
+
+    kdtree = manta_new( KDTreeDyn( flat ))
+    load_obj_KDTreeDyn( file_name, kdtree )
+
+    
###########################################################################
+    # Build the kdtree.
+    builder = Approx_cc( leaf_threshold, depth_threshold )
+
+    # Add the kdtree to the scene.
+    world = manta_new( Group() )
+
+    try:
+        builder.build( kdtree )
+    except Exception,e:
+        print e.type() + " during kdtree build:"
+        print e.message()
+        return scene
+
+    # Add the kdtree to the scene.
+    world.add( kdtree )
+
+    # sphere = manta_new(Sphere(red, Vector(0,0,1.2), 1.0))
+    # world.add(sphere)
+
+    # Add the scene to manta.
+    scene.setObject( world )
+    engine.setScene( scene )
+
+    # Create the explorer.
+    # global explorer
+    explorer = KDTreeDynFrame( frame, frame.engine, kdtree )
+    explorer.Show()
+
+
+
+
+###############################################################################
+###############################################################################
+# Main
+###############################################################################
+###############################################################################
+    
 def usage():
-    print "Usage: python test.py [options]"
+    print "Usage: python " + sys.argv[0] + " [options]"
     print "Where options contains one or more of:"
     print "-n --np=<threads>"
+    print "-f --file=<file name>"
+    print "   --depth_threshold=<n>"
+    print "   --leaf_threshold=<n>"
 
 def main():
 
+    global file_name, leaf_threshold, depth_threshold
+
     # Default options.
     num_workers = 1
 
     # Parse command line options. Note these have to conform to getopt
     # So -np would be parsed as -n <space> p. Use --np=<threads> instead.
     try:
-        opts, args = getopt.getopt(sys.argv[1:], "n:", ["np="] )
+        opts, args = getopt.getopt(sys.argv[1:],
+                                   "n:f:",
+                                   ["np=",
+                                    "file=",
+                                    "leaf_threshold=",
+                                    "depth_threshold="] )
 
     except getopt.GetoptError:
         usage()
@@ -28,13 +128,21 @@
             except ValueError:
                 usage()
                 sys.exit(2)
+                
+        if o in ("-f", "--file"):
+            file_name = a;
+
+        if o in ("--leaf_threshold"):
+            leaf_threshold = int(a)
+
+        if o in ("--depth_threshold"):
+            depth_threshold = int(a)
 
         # Add additional command line args here.
         
-
     
###########################################################################
     # Create the application.
-    app = wxManta.MantaApp( wxManta.createDefaultScenePython,
+    app = wxManta.MantaApp( initialize_scene,
                             num_workers )
 
 

Modified: trunk/SwigInterface/manta.i
==============================================================================
--- trunk/SwigInterface/manta.i (original)
+++ trunk/SwigInterface/manta.i Sun Aug 13 22:22:40 2006
@@ -4,6 +4,7 @@
 %include "std_vector.i"
 %include "exception.i"
 
+
 %{
 #include <MantaTypes.h>
 #include <Core/Geometry/Vector.h>
@@ -28,12 +29,27 @@
 #include <Core/Exceptions/IllegalArgument.h>
 #include <Core/Exceptions/IllegalValue.h>
 #include <Core/Exceptions/BadPrimitive.h>
+#include <Core/Exceptions/InvalidState.h>
 %}
 
 %include <Core/Exceptions/share.h>
 %include <Core/Exceptions/Exception.h>
 %include <Core/Exceptions/IllegalArgument.h>
 %include <Core/Exceptions/BadPrimitive.h>
+%include <Core/Exceptions/InvalidState.h>
+
+%define %manta_Exception_exception(Function)
+%exception Function {
+  try {
+    $action
+  } catch(SCIRun::Exception& e) {
+    SWIG_exception(SWIG_ValueError, e.message());
+  } catch(...) { 
+    SWIG_exception(SWIG_RuntimeError, "Unknown exception");
+  }
+}
+%enddef
+
 
 %define %manta_IllegalArgument_exception(Function)
 %exception Function {
@@ -91,16 +107,42 @@
 }
 %enddef
 
+///////////////////////////////////////////////////////
+//
+
+%{
+#include <Core/Geometry/Ray.h>
+#include <Interface/Context.h>
+#include <Interface/Object.h>
+#include <Interface/Primitive.h>
+#include <Interface/TexCoordMapper.h>
+#include <Core/Util/Align.h>
+#include <Core/Util/About.h>
+#include <Interface/RayPacket.h>
+%}
+
+%include <Core/Geometry/Ray.h>
+%include <Interface/Context.h>
+%include <Interface/Object.h>
+%include <Interface/Primitive.h>
+%include <Interface/TexCoordMapper.h>
+%include <Core/Util/Align.h>
+%include <Core/Util/About.h>
+%include <Interface/RayPacket.h>
+
+
+
 %manta_IllegalArgument_exception(create);
 
 %{
-#include <Interface/MantaInterface.h>
+
 #include <Interface/UserInterface.h>
 #include <Interface/RenderParameters.h>
 #include <Interface/Scene.h>
 #include <Interface/CallbackHelpers.h>
 #include <Interface/Callback.h>
 #include <SwigInterface/manta.h>
+#include <Interface/MantaInterface.h>
 %}
 
 namespace std {
@@ -128,8 +170,8 @@
 %include <Interface/Transaction.h>
 %include <Interface/TValue.h>
 
-%include <Interface/MantaInterface.h>
 %include <SwigInterface/manta.h>
+%include <Interface/MantaInterface.h>
 
 namespace Manta {
   using namespace std;
@@ -252,8 +294,6 @@
 %include <Engine/Display/PureOpenGLDisplay.h>
 %include <Engine/Display/NullDisplay.h>
 
-
-
 ///////////////////////////////////////////////////////
 // UI
 %{
@@ -266,27 +306,6 @@
 %include <UserInterface/AutomatorUI.h>
 %include <UserInterface/SyncFrameAutomator.h>
 
-///////////////////////////////////////////////////////
-//
-
-%{
-#include <Core/Geometry/Ray.h>
-#include <Interface/Context.h>
-#include <Interface/Object.h>
-#include <Interface/Primitive.h>
-#include <Interface/TexCoordMapper.h>
-#include <Core/Util/Align.h>
-#include <Interface/RayPacket.h>
-%}
-
-%include <Core/Geometry/Ray.h>
-%include <Interface/Context.h>
-%include <Interface/Object.h>
-%include <Interface/Primitive.h>
-%include <Interface/TexCoordMapper.h>
-%include <Core/Util/Align.h>
-%include <Interface/RayPacket.h>
-
 
 ////////////////////////////////////////////////////////
 // Lights and backgrounds
@@ -385,18 +404,6 @@
   %template(ImageTexture_Color) ImageTexture<Manta::Color>;
 }
 
-%{
-#include <Model/Textures/NormalTexture.h>
-#include <Model/Groups/KDTree.h>
-%}
-
-%include <Model/Textures/NormalTexture.h>
-
-namespace Manta {
-  %template(WireframeTexture_Color) 
WireframeTexture<Manta::Kdtree::KDTree::ScratchPadInfo,Color>;
-  %template(WireframeTexture_ColorComponent) 
WireframeTexture<Manta::Kdtree::KDTree::ScratchPadInfo,Manta::ColorComponent>;
-}
-
 /////////////////////////////////////////////////////
 // Materials and Primitivs
 %{
@@ -407,6 +414,7 @@
 #include <Model/Materials/MetalMaterial.h>
 #include <Model/Materials/Dielectric.h>
 #include <Model/Materials/Flat.h>
+#include <Model/Materials/Transparent.h>
 #include <Model/Groups/Group.h>
 #include <Model/Primitives/PrimitiveCommon.h>
 #include <Interface/TexCoordMapper.h>
@@ -426,6 +434,7 @@
 %include <Model/Materials/MetalMaterial.h>
 %include <Model/Materials/Dielectric.h>
 %include <Model/Materials/Flat.h>
+%include <Model/Materials/Transparent.h>
 %include <Model/Groups/Group.h>
 %include <Model/Primitives/PrimitiveCommon.h>
 %include <Interface/TexCoordMapper.h>
@@ -437,6 +446,31 @@
 %include <Model/TexCoordMappers/UniformMapper.h>
 %include <Model/Groups/RealisticBvh.h>
 
+///////////////////////////////////////////////////////////////////////////////
+// Groups
+
+%{
+#include <Model/Textures/NormalTexture.h>
+#include <Model/Groups/KDTree.h>
+%}
+
+%include <Model/Textures/NormalTexture.h>
+
+namespace Manta {
+  %template(WireframeTexture_Color) 
WireframeTexture<Manta::Kdtree::KDTree::ScratchPadInfo,Color>;
+  %template(WireframeTexture_ColorComponent) 
WireframeTexture<Manta::Kdtree::KDTree::ScratchPadInfo,Manta::ColorComponent>;
+}
+
+%{
+#include <Model/Groups/KDTreeDyn.h>
+#include <Model/Groups/Load_OBJ_KDTreeDyn.h>
+#include <Model/Groups/Build_KDTreeDyn.h>
+%}
+
+%include <Model/Groups/KDTreeDyn.h>
+%include <Model/Groups/Load_OBJ_KDTreeDyn.h>
+%include <Model/Groups/Build_KDTreeDyn.h>
+
 /////////////////////////////////////////////////
 // GLM.
 %{
@@ -453,6 +487,16 @@
 %include <SCIRun/Core/Containers/Array1.h>
 
 %template(Array1_ObjectP) SCIRun::Array1<Manta::Object*>;
+
+///////////////////////////////////////////////////////
+// Engine Control
+%{
+#include <Engine/Control/RTRT.h>
+%}
+
+%include <Engine/Control/RTRT.h>
+
+
 
 ////////////////////////////////////////////////
 // Python specific code

Added: trunk/SwigInterface/wxManta.cc
==============================================================================
--- (empty file)
+++ trunk/SwigInterface/wxManta.cc      Sun Aug 13 22:22:40 2006
@@ -0,0 +1,25 @@
+
+#include <SwigInterface/wxManta.h>
+
+namespace Manta {
+
+  // Helper function to cast manta_interface to RTRT
+  void shootOneRay( MantaInterface *manta_interface,
+                    Color *result_color,
+                    RayPacket *result_rays,
+                    Real image_x,
+                    Real image_y,
+                    int channel_index ) {
+
+    // Check to see that the pointer is to an RTRT instance.
+    if ((rtrt = dynamic_cast<RTRT *>(manta_interface))) {
+
+      // Shoot the ray (in a very un-threadsafe manner)
+      rtrt->shootOneRay( *result_color, *result_rays, image_x, image_y, 
channel_index );
+    }
+    else {
+      throw InvalidState( "shootOneRay not passed RTRT instance", __FILE__, 
__LINE__ );
+    }
+  }
+};
+

Added: trunk/SwigInterface/wxManta.h
==============================================================================
--- (empty file)
+++ trunk/SwigInterface/wxManta.h       Sun Aug 13 22:22:40 2006
@@ -0,0 +1,20 @@
+
+#ifndef SWIGINTERFACE_WXMANTA__H
+#define SWIGINTERFACE_WXMANTA__H
+
+#include <MantaTypes.h>
+#include <Interface/MantaInterface.h>
+#include <Interface/RayPacket.h>
+#include <Core/Color/Color.h>
+
+
+namespace Manta {
+  void shootOneRay( MantaInterface *manta_interface,
+                    Color *result_color,
+                    RayPacket *result_rays,
+                    Real image_x,
+                    Real image_y,
+                    int channel_index );
+};
+
+#endif

Modified: trunk/SwigInterface/wxManta.py
==============================================================================
--- trunk/SwigInterface/wxManta.py      (original)
+++ trunk/SwigInterface/wxManta.py      Sun Aug 13 22:22:40 2006
@@ -21,8 +21,14 @@
 yres = 512
 
 
###############################################################################
+###############################################################################
 # Default Scene.
-def createDefaultScenePython():
+# Unlike make_scene, this function doesn't return anything. It must call
+# engine.setScene( ... ) explicitly.
+###############################################################################
+###############################################################################
+
+def createDefaultScenePython( frame, engine ):
     scene = manta_new(Scene())
     
scene.setBackground(manta_new(ConstantBackground(ColorDB.getNamedColor("SkyBlue3").scaled(0.5))))
     red = manta_new(Phong(Color(RGBColor(0.6, 0, 0)),
@@ -56,7 +62,8 @@
     #
     scene.setLights(lights)
     scene.getRenderParameters().maxDepth = 5
-    return scene
+
+    engine.setScene( scene )
 
 class DisplayThread(threading.Thread):
     """Display Thread that will trigger a display event when the manta 
pipeline is ready to display an image."""
@@ -270,7 +277,7 @@
 
###############################################################################
        
 class MantaFrame(wx.Frame):
     def __init__(self,
-                 make_scene,
+                 initialize_callback,
                  num_workers,
                  renderSize,
                  parent=None,
@@ -286,26 +293,26 @@
         self.statusbar = self.CreateStatusBar()
 
         # Create the menu
-        menuBar = wx.MenuBar()
+        self.menuBar = wx.MenuBar()
 
         manta_menu = wx.Menu()
         self.Bind(wx.EVT_MENU, self.OnAbout,
                   manta_menu.Append(wx.NewId(), "About Manta"))
         self.Bind(wx.EVT_MENU, self.OnCloseWindow,
                   manta_menu.Append(wx.NewId(), "&Quit Manta"))
-        menuBar.Append(manta_menu, "&Manta")
+        self.menuBar.Append(manta_menu, "&Manta")
 
         file_menu = wx.Menu()
         self.Bind(wx.EVT_MENU, self.OnImportPython,
                   file_menu.Append(wx.NewId(), "Import &Python"))
-        menuBar.Append(file_menu, "&File")
+        self.menuBar.Append(file_menu, "&File")
         
         view_menu = wx.Menu()
         self.Bind(wx.EVT_MENU, self.OnAutoView,
                   view_menu.Append(wx.NewId(), "&Auto View"))
-        menuBar.Append(view_menu, "&View")
+        self.menuBar.Append(view_menu, "&View")
 
-        self.SetMenuBar(menuBar)
+        self.SetMenuBar(self.menuBar)
 
         # Create the Main panel that will hold the renderer
         self.panel = wx.Panel(self, size=renderSize)
@@ -370,8 +377,14 @@
                                                     use_stereo, xres, yres )
 
         # Basic scene.
-        self.engine.setScene( make_scene() )
-        self.engine.beginRendering(False)
+        initialize_callback( self, self.engine ) 
+
+        try:
+            self.engine.beginRendering(False)
+            
+        except Exception, e:
+            print e.type() + " occurred starting Manta"
+            print e.message()
 
         
#######################################################################
         # Setup the UI events.
@@ -741,15 +754,15 @@
 
 class MantaApp(wx.App) :
     def __init__(self,
-                 make_scene_ = createDefaultScenePython,
+                 initialize_callback_ = createDefaultScenePython,
                  num_workers = 1,
                  renderSize  = wx.Size(xres,yres),
                  redirect=False,
                  filename=None):
         wx.App.__init__(self, redirect, filename)
 
-        # Create a manta frame with the given make_scene function.
-        self.frame = MantaFrame( make_scene_, num_workers, renderSize )
+        # Create a manta frame with the given initialize_callback function.
+        self.frame = MantaFrame( initialize_callback_, num_workers, 
renderSize )
         self.frame.Show()
 
 

Added: trunk/SwigInterface/wxManta_helper.i
==============================================================================
--- (empty file)
+++ trunk/SwigInterface/wxManta_helper.i        Sun Aug 13 22:22:40 2006
@@ -0,0 +1,25 @@
+
+
+%module wxManta_helper
+
+%include "std_string.i"
+%include "std_vector.i"
+%include "exception.i"
+
+%{
+#include <MantaTypes.h>
+#include <Interface/RayPacket.h>
+#include <Interface/MantaInterface.h>
+#include <Interface/CallbackHelpers.h>
+
+
+#include <SwigInterface/wxManta.h>
+%}
+
+%include <MantaTypes.h>
+%include <Interface/RayPacket.h>
+%include <Interface/CallbackHelpers.h>
+%include <Interface/MantaInterface.h>
+
+
+%include <SwigInterface/wxManta.h>
\ No newline at end of file

Modified: trunk/fox/CMakeLists.txt
==============================================================================
--- trunk/fox/CMakeLists.txt    (original)
+++ trunk/fox/CMakeLists.txt    Sun Aug 13 22:22:40 2006
@@ -5,6 +5,8 @@
 ## Abe Stephens 
 ##
 
+INCLUDE(${CMAKE_SOURCE_DIR}/CMake/FindFox.cmake)
+
 INCLUDE_DIRECTORIES(
   ${CMAKE_SOURCE_DIR}/fox
   ${FOUND_FOX_INCLUDE}

Added: trunk/fox/raytree_demo/CMakeLists.txt
==============================================================================
--- (empty file)
+++ trunk/fox/raytree_demo/CMakeLists.txt       Sun Aug 13 22:22:40 2006
@@ -0,0 +1,37 @@
+
+SET(BUILD_RAYTREE_DEMO 0 CACHE BOOL "Build Ray Tree Demo")
+IF(BUILD_RAYTREE_DEMO)
+
+  ##########################################################
+  # Add the disc_demo dependent code.
+
+  SET(RAYTREE_SRC
+
+    # Core
+    Core/RayTree/RayStream.cc
+    Core/RayTree/RayStream.h
+
+    # Engine
+    Engine/Renderers/RayStreamRenderer.cc
+    Engine/Renderers/RayStreamRenderer.h
+    
+    )
+
+  # Add root directory to include path.
+  INCLUDE_DIRECTORIES( ${CMAKE_SOURCE_DIR}/fox/raytree_demo )
+
+  # Add a library with the code.
+  ADD_LIBRARY( raytree_shared
+    ${RAYTREE_SRC}
+    )
+
+  TARGET_LINK_LIBRARIES( raytree_shared
+    ${MANTA_TARGET_LINK_LIBRARIES}
+    )
+
+  SUBDIRS(
+    StandAlone
+    scenes
+    )
+  
+ENDIF(BUILD_RAYTREE_DEMO)

Added: trunk/fox/raytree_demo/Core/RayTree/RayEntry.h
==============================================================================
--- (empty file)
+++ trunk/fox/raytree_demo/Core/RayTree/RayEntry.h      Sun Aug 13 22:22:40 
2006
@@ -0,0 +1,27 @@
+
+#ifndef CORE_RAYTREE_RAYENTRY__H
+#define CORE_RAYTREE_RAYENTRY__H
+
+namespace raytree {
+
+  ///////////////////////////////////////////////////////////////////////////
+  // This structure contains a ray that was intersected with geometry by the
+  // ray tracer. The RayEntry structure is used to stream ray information
+  // to disk.
+  struct RayEntry {
+    // Ray information.
+    float origin[3];
+    float direction[3];
+    unsigned int depth;
+
+    // Hit information.
+    float min_t;
+    unsigned long long hit_id;
+
+    enum { NotHit = 0 };
+  };
+
+
+};
+
+#endif

Added: trunk/fox/raytree_demo/Core/RayTree/RayStream.cc
==============================================================================
--- (empty file)
+++ trunk/fox/raytree_demo/Core/RayTree/RayStream.cc    Sun Aug 13 22:22:40 
2006
@@ -0,0 +1,102 @@
+
+#include <Core/RayTree/RayStream.h>
+
+#include <SCIRun/Core/Exceptions/ErrnoException.h>
+
+#include <errno.h>
+#include <stdio.h>
+
+using namespace raytree;
+using namespace SCIRun;
+
+
+///////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////
+// RAY STREAM  RAY STREAM  RAY STREAM  RAY STREAM  RAY STREAM  RAY STREAM  
+///////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////
+
+RayStream::~RayStream() {
+
+}
+
+void RayStream::flush() {
+
+  if (ptr != buffer.begin()) {
+
+    // Write the stream.
+    write_stream( &(*(buffer.begin())), buffer.size() );    
+  }
+}
+
+RayStream &RayStream::operator <<( const RayEntry &entry ) {
+       
+  // Check to see if the buffer is full.
+  if (ptr == buffer.end()) {
+           
+    // Write the stream.
+    write_stream( &(*(buffer.begin())), buffer.size() );
+
+    // Reset the pointer.
+    ptr = buffer.begin();
+  }
+
+  // Copy entry into the buffer.
+  *ptr = entry;
+  ++ptr;
+  ++total_rays;
+
+  return *this;
+}
+
+
+///////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////
+// FILE RAY STREAM  FILE RAY STREAM  FILE RAY STREAM  FILE RAY STREAM  FILE
+///////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////
+
+FileRayStream::FileRayStream( const string &filename, size_t buffer_size )
+  : RayStream( buffer_size ), in_file( 0 ), out_file( 0 )
+{
+  open(filename);
+}
+
+FileRayStream::~FileRayStream() {
+    
+  // Close the file if it is open.
+  close();
+}
+
+void FileRayStream::write_stream( const RayEntry * const stream, size_t size 
) {
+
+  // Write to the stream.
+  if (fwrite( stream, EntryBytes, size, out_file ) != size) {
+    throw ErrnoException( "Could not write RayEntry stream to file.", 
ferror(out_file), __FILE__, __LINE__ );
+  }
+}
+
+void FileRayStream::open( const string &filename ) {
+
+  // Attempt to open the file.
+  if ((out_file = fopen( filename.c_str(), "w" )) == 0) {
+    throw ErrnoException( "Could not open out file", errno, __FILE__, 
__LINE__ );
+  }
+
+  if ((in_file = fopen( filename.c_str(), "r" )) == 0) {
+    throw ErrnoException( "Could not open in file", errno, __FILE__, 
__LINE__ );
+  }
+}
+
+void FileRayStream::close() {
+
+  fclose( out_file );
+  fclose( in_file );
+  
+  out_file = 0;
+  in_file = 0;
+
+}
+
+
+

Added: trunk/fox/raytree_demo/Core/RayTree/RayStream.h
==============================================================================
--- (empty file)
+++ trunk/fox/raytree_demo/Core/RayTree/RayStream.h     Sun Aug 13 22:22:40 
2006
@@ -0,0 +1,74 @@
+
+
+
+#ifndef CORE_RAYTREE_RAYSTREAM__H
+#define CORE_RAYTREE_RAYSTREAM__H
+
+#include <Core/RayTree/RayEntry.h>
+
+#include <vector>
+#include <string>
+
+struct FILE;
+
+namespace raytree {
+
+  using std::string;
+  
+  ///////////////////////////////////////////////////////////////////////////
+  ///////////////////////////////////////////////////////////////////////////
+  // RAY STREAM  RAY STREAM  RAY STREAM  RAY STREAM  RAY STREAM  RAY STREAM  
+  ///////////////////////////////////////////////////////////////////////////
+  ///////////////////////////////////////////////////////////////////////////
+
+  class RayStream {
+  public:
+    RayStream( size_t buffer_size ) : 
+           buffer( buffer_size ), 
+           ptr( buffer.begin() ),
+      total_rays( 0 ) { };
+    virtual ~RayStream();
+       
+    // Stream serialization.
+    RayStream &operator << (const RayEntry &entry);
+
+    void flush();
+    
+    // These methods perform actual i/o.
+    virtual void write_stream( const RayEntry * const stream, size_t size ) 
= 0;
+
+    size_t getTotalRays() { return total_rays; }
+    
+  private:
+    typedef std::vector<RayEntry> StreamBuffer;
+    
+    // Stream buffer.
+    StreamBuffer buffer;
+    StreamBuffer::iterator ptr;
+
+    // Total number of rays.
+    size_t total_rays;
+  };
+
+  ///////////////////////////////////////////////////////////////////////////
+  ///////////////////////////////////////////////////////////////////////////
+  // FILE RAY STREAM  FILE RAY STREAM  FILE RAY STREAM  FILE RAY STREAM  FILE
+  ///////////////////////////////////////////////////////////////////////////
+  ///////////////////////////////////////////////////////////////////////////
+  class FileRayStream : public RayStream {
+  public:
+    FileRayStream( const string &filename, size_t buffer_size );
+    virtual ~FileRayStream();
+
+    virtual void write_stream( const RayEntry * const stream, size_t size );
+
+    void open( const string &filename );
+    void close();
+    
+  private:
+    enum { EntryBytes = sizeof( RayEntry ) };
+
+    FILE *out_file, *in_file;
+  };
+}
+#endif

Copied: trunk/fox/raytree_demo/Engine/Renderers/RayStreamRenderer.cc (from 
r1130, trunk/Engine/Renderers/Raytracer.cc)
==============================================================================
--- trunk/Engine/Renderers/Raytracer.cc (original)
+++ trunk/fox/raytree_demo/Engine/Renderers/RayStreamRenderer.cc        Sun 
Aug 13 22:22:40 2006
@@ -1,5 +1,5 @@
 
-#include <Engine/Renderers/Raytracer.h>
+#include <Engine/Renderers/RayStreamRenderer.h>
 #include <Interface/Background.h>
 #include <Interface/Camera.h>
 #include <Interface/Context.h>
@@ -8,37 +8,73 @@
 #include <Interface/RayPacket.h>
 #include <Interface/Scene.h>
 #include <Core/Util/Assert.h>
+#include <Core/Util/Args.h>
 #include <iostream>
 using namespace std;
 
+using namespace raytree;
 using namespace Manta;
 
-Renderer* Raytracer::create(const vector<string>& args)
+Renderer* RayStreamRenderer::create(const vector<string>& args)
 {
-  return new Raytracer(args);
+  string filename = "raystream.binary";
+  int buffer = 1024;
+
+  for (int i=0;i<args.size();++i) {
+    if (args[i] == "-file") {
+      getArg( i, args, filename );
+    }
+    else if (args[i] == "-buffer") {
+      getArg( i, args, buffer );
+    }
+  }
+
+  return new RayStreamRenderer( filename, buffer );  
 }
 
-Raytracer::Raytracer(const vector<string>& /*args*/)
+RayStreamRenderer::RayStreamRenderer(const string &filename_, size_t 
buffer_size_ )
+  : filename( filename_ ), buffer_size( buffer_size_ )
 {
+  
 }
 
-Raytracer::~Raytracer()
-{
+RayStreamRenderer::~RayStreamRenderer() {
+
+  size_t total_rays = 0;
+  
+  for (int i=0; i<stream.size();++i) {
+    total_rays += stream[i]->getTotalRays();
+
+    stream[i]->flush();
+    delete stream[i];
+  }
+
+  std::cerr << "Total rays recorded " << (total_rays) << std::endl;
 }
 
-void Raytracer::setupBegin(const SetupContext&, int)
+void RayStreamRenderer::setupBegin(const SetupContext& context, int 
numChannels )
 {
+  // Allocate streams.
+  stream.resize( context.numProcs );
+
+  for (int i=0;i<context.numProcs;++i) {
+
+    ostringstream os;
+    os << filename << "_thread" << i;
+    
+    stream[i] = new FileRayStream( os.str(), buffer_size);
+  }
 }
 
-void Raytracer::setupDisplayChannel(SetupContext&)
+void RayStreamRenderer::setupDisplayChannel(SetupContext&)
 {
 }
 
-void Raytracer::setupFrame(const RenderContext&)
+void RayStreamRenderer::setupFrame(const RenderContext&)
 {
 }
 
-void Raytracer::traceEyeRays(const RenderContext& context, RayPacket& rays)
+void RayStreamRenderer::traceEyeRays(const RenderContext& context, 
RayPacket& rays)
 {
   ASSERT(rays.getFlag(RayPacket::HaveImageCoordinates));
   context.camera->makeRays(rays);
@@ -46,11 +82,38 @@
   traceRays(context, rays);
 }
 
-void Raytracer::traceRays(const RenderContext& context, RayPacket& rays)
+void RayStreamRenderer::traceRays(const RenderContext& context, RayPacket& 
rays)
 {
   rays.resetHits();
   context.scene->getObject()->intersect(context, rays);
 
+  // Output rays to stream.
+  RayEntry entry;
+
+  entry.depth = rays.getDepth();
+
+  // Copy data from each ray.
+  for (int i=rays.begin();i<rays.end();++i) {
+    for (int j=0;j<3;++j) {
+      entry.origin[j] = rays.getOrigin(i,j);
+      entry.direction[j] = rays.getDirection(i,j);
+    }
+    entry.min_t = rays.getMinT( i );
+
+    // Access triangle id.
+    if (rays.wasHit(i)) {
+      entry.hit_id = (long long)rays.getHitPrimitive( i );
+    }
+    else {
+      entry.hit_id = RayEntry::NotHit;
+    }
+
+    // Write the entry to the stream;
+    *(stream[context.proc]) << entry;
+  }
+
+
+  
   // Go through the ray packet and shade them.  Group rays that hit the
   // same object and material to shade with a single shade call
   for(int i = rays.begin();i<rays.end();){

Copied: trunk/fox/raytree_demo/Engine/Renderers/RayStreamRenderer.h (from 
r1130, trunk/Engine/Renderers/Raytracer.h)
==============================================================================
--- trunk/Engine/Renderers/Raytracer.h  (original)
+++ trunk/fox/raytree_demo/Engine/Renderers/RayStreamRenderer.h Sun Aug 13 
22:22:40 2006
@@ -1,21 +1,22 @@
 
-#ifndef Manta_Engine_Raytracer_h
-#define Manta_Engine_Raytracer_h
+
+
+#ifndef CORE_RAYTREE_RAYTREERENDERER
+#define CORE_RAYTREE_RAYTREERENDERER
 
 #include <Interface/Renderer.h>
-#include <sgi_stl_warnings_off.h>
-#include <string>
-#include <vector>
-#include <sgi_stl_warnings_on.h>
+#include <Core/RayTree/RayStream.h>
 
-namespace Manta {
-  using namespace std;
-  class ShadowAlgorithm;
+namespace raytree {
 
-  class Raytracer : public Renderer {
+  using namespace Manta;
+  using namespace std;

+  class RayStreamRenderer : public Renderer {
   public:
-    Raytracer(const vector<string>& args);
-    virtual ~Raytracer();
+    RayStreamRenderer(const string &filename, size_t buffer_size );
+    virtual ~RayStreamRenderer();
+
     virtual void setupBegin(const SetupContext&, int numChannels);
     virtual void setupDisplayChannel(SetupContext&);
     virtual void setupFrame(const RenderContext& context);
@@ -24,9 +25,15 @@
     virtual void traceRays(const RenderContext&, RayPacket& rays);
 
     static Renderer* create(const vector<string>& args);
+    
   private:
-    Raytracer(const Raytracer&);
-    Raytracer& operator=(const Raytracer&);
+    vector<FileRayStream*> stream;
+
+    string filename;
+    size_t buffer_size; 
+    
+    RayStreamRenderer(const RayStreamRenderer&);
+    RayStreamRenderer& operator=(const RayStreamRenderer&);
   };
 }
 

Copied: trunk/fox/raytree_demo/StandAlone/record_stream.cc (from r1130, 
trunk/StandAlone/manta.cc)
==============================================================================
--- trunk/StandAlone/manta.cc   (original)
+++ trunk/fox/raytree_demo/StandAlone/record_stream.cc  Sun Aug 13 22:22:40 
2006
@@ -59,6 +59,9 @@
 #include <Model/TexCoordMappers/UniformMapper.h>
 #include <SCIRun/Core/Thread/Thread.h>
 
+#include <Engine/Renderers/RayStreamRenderer.h>
+using raytree::RayStreamRenderer;
+
 #include <strings.h>
 
 #include <sgi_stl_warnings_off.h>
@@ -179,6 +182,9 @@
     // Create Manta.
     MantaInterface* rtrt = createManta();
 
+    // Re-register the renderer command line option.
+    rtrt->registerComponent( "raytracer", RayStreamRenderer::create );
+    
     // Set the scene search path based on an env variable.
     if(getenv("MANTA_SCENEPATH"))
       rtrt->setScenePath(getenv("MANTA_SCENEPATH"));

Modified: trunk/scenes/CMakeLists.txt
==============================================================================




  • [MANTA] r1176 - in trunk: . CMake Core/Geometry Interface Model/Cameras Model/Groups Model/Materials Model/Primitives Model/Readers SwigInterface fox fox/raytree_demo fox/raytree_demo/Core fox/raytree_demo/Core/RayTree fox/raytree_demo/Engine fox/raytree_demo/Engine/Renderers fox/raytree_demo/StandAlone histx scenes, abe, 08/13/2006

Archive powered by MHonArc 2.6.16.

Top of page