Procedurally generated geometry tutorial

From Horde3D Wiki
Jump to: navigation, search

Work in progress - Due to the current changes in the Horde API this tutorial will be delayed


Important notes

  • The code used here has been tested with Horde3D 1.0.0 beta2 and beta3 and will NOT work with the latest release (beta4)


Overview

Basic approach

To create and display a procedurally generated mesh that, instead of being loaded from a Horde3D Scene node and a geoemtry file(*.scene.xml, *.geo), will be created in-memory by some algorithm, you have to create a mesh first and then "fake" the .geo-file and the scene node itself and pass it to the engine.

To do that you have to create your procedural geometry first. This is easy for simple shapes like single triangles, squares or triangle-strips, but will become way more difficult when we try to generate complex meshes, e.g. when we have a cloud of points in 3D space and have to describe which points make triangles, and which don't (calculating the triangle indices, texture coordinates and normals).

When we have calculated the geometry itself we need to create a char-stream to make Horde believe the geometry has been read from a file and pass it to Horde as a geometry Resource. The final step is to create a Horde3D Scene Node from our procedurally generated mesh and render it into our scene.

StreamGenerator

These classes are only for creating the character stream that will contain the geometry resource.

StreamGenerator.h
  1. #pragma once
    
  2. #include <sstream>
    
  3. #include <string>
    
  4. #include <iostream>
    
  5.  
    
  6. class StreamGenerator 
    
  7. {
    
  8. public:
    
  9.         StreamGenerator();
    
  10.         virtual ~StreamGenerator();
    
  11.         virtual const char* getStream() = 0;
    
  12.         virtual const int getStreamSize() = 0;
    
  13. };
    
StreamGenerator.cpp
  1. #include "StreamGenerator.h"
    
  2.  
    
  3. StreamGenerator::StreamGenerator() 
    
  4. {
    
  5. }
    
  6.  
    
  7. StreamGenerator::~StreamGenerator()
    
  8. {
    
  9. }
    
GeometryStreamGenerator.h
  1. #pragma once
    
  2. #include "StreamGenerator.h"
    
  3. #include "CustomGeometry.h"
    
  4.  
    
  5. class GeometryStreamGenerator : public StreamGenerator
    
  6. {
    
  7. private:
    
  8.         std::stringstream* ss;
    
  9.         void generate();
    
  10.         int numVertices, numTriangleIndices;
    
  11.         char* _stream;
    
  12.         CustomGeometry* _geom;
    
  13.  
    
  14. public:
    
  15.         GeometryStreamGenerator(CustomGeometry* geom_);
    
  16.         ~GeometryStreamGenerator();
    
  17.         const char* getStream();
    
  18.         const std::stringstream* getStringStream() { return ss; };
    
  19.         const int getStreamSize();
    
  20.         const int getNumVertices();
    
  21.         const int getNumTriangleIndices();
    
  22.         void release();
    
  23. };
    
GeometryStreamGenerator.cpp
  1. #include "GeometryStreamGenerator.h"
    
  2. #include "time.h"
    
  3. #include "utMath.h"
    
  4.  
    
  5. GeometryStreamGenerator::GeometryStreamGenerator(CustomGeometry* geom_) : _geom(geom_)
    
  6. {
    
  7.         ss = new std::stringstream();
    
  8.         generate();
    
  9. }
    
  10.  
    
  11. GeometryStreamGenerator::~GeometryStreamGenerator()
    
  12. {
    
  13. }
    
  14.  
    
  15. void GeometryStreamGenerator::generate()
    
  16. {
    
  17.         numVertices = _geom->getNumVertices();
    
  18.         numTriangleIndices = _geom->getNumTriangleIndices();
    
  19.         const std::string _magicHeader = "H3DG";
    
  20.         const int _version = 5;
    
  21.         const int _numJoints = 1;
    
  22.         const float _identityMatrix[] = {       1.0f, 0.0f, 0.0f, 0.0f,  
    
  23.                                                 0.0f, 1.0f, 0.0f, 0.0f,  
    
  24.                                                 0.0f, 0.0f, 1.0f, 0.0f,  
    
  25.                                                 0.0f, 0.0f, 0.0f, 1.0f};
    
  26.         const int _numVertexStreams = 3;
    
  27.         const int _magicVertices = 0;
    
  28.         const int _vertexStreamElementSize = 12;
    
  29.         const float* _positions = _geom->getPositions();
    
  30.         const int _magicNormals = 1;
    
  31.         const int _normalsStreamElementSize = 6;
    
  32.         const float* _normals = _geom->getNormals();
    
  33.         const int _magicTextureCoords1 = 6;
    
  34.         const int _texCoordStreamElementSize = 8;
    
  35.         const float* _texCoords = _geom->getTexCoords();
    
  36.         const int* _triangleIndices = _geom->getTriangleIndices();
    
  37.         const int _numMorphTragets = 0;
    
  38.         // header
    
  39.         ss->write(_magicHeader.c_str(), 4*sizeof(char));
    
  40.         ss->write((char*)&_version, sizeof(int));
    
  41.         // joints (mandatory)
    
  42.         ss->write((char*)&_numJoints, sizeof(int));
    
  43.         for (int i=0; i<16; ++i) {
    
  44.                 ss->write((char*)&_identityMatrix[i], sizeof(float));
    
  45.         }
    
  46.         // vertices
    
  47.         ss->write((char*)&_numVertexStreams, sizeof(int));
    
  48.         const int numVerts = _geom->getNumVertices();
    
  49.         ss->write((char*)&numVerts, sizeof(int));
    
  50.         ss->write((char*)&_magicVertices, sizeof(int));
    
  51.         ss->write((char*)&_vertexStreamElementSize, sizeof(int));
    
  52.         for (int i=0; i<_geom->getNumVertices()*3; ++i) {
    
  53.                 ss->write((char*)&_positions[i], sizeof(float));
    
  54.         }
    
  55.         // normals
    
  56.         ss->write((char*)&_magicNormals, sizeof(int));
    
  57.         ss->write((char*)&_normalsStreamElementSize, sizeof(int));
    
  58.         for (int i=0; i<_geom->getNumVertices()*3; ++i) {
    
  59.                 // do not forget to mutliply the value with 32767 and 
    
  60.                 // then convert it to short before writing to the stream
    
  61.                 const short f = (short)(_normals[i]*32767);
    
  62.                 ss->write((char*)&f, sizeof(short));
    
  63.         }
    
  64.         // texture coordinates
    
  65.         ss->write((char*)&_magicTextureCoords1, sizeof(int));
    
  66.         ss->write((char*)&_texCoordStreamElementSize, sizeof(int));
    
  67.         for (int i=0; i<_geom->getNumVertices()*2; ++i) {
    
  68.                 ss->write((char*)&_texCoords[i], sizeof(float));
    
  69.         }
    
  70.         // triangle indices
    
  71.         const int numTriangleIndices = _geom->getNumTriangleIndices();
    
  72.         ss->write((char*)&numTriangleIndices, sizeof(int));
    
  73.         for (int i=0; i<_geom->getNumTriangleIndices(); ++i) {
    
  74.                 ss->write((char*)&_triangleIndices[i], sizeof(int));
    
  75.         }
    
  76.         ss->write((char*)&_numMorphTragets, sizeof(int));
    
  77.         _stream = new char[ss->tellp()];
    
  78.         ss->read(_stream, ss->tellp());
    
  79. }
    
  80.  
    
  81. const char* GeometryStreamGenerator::getStream()
    
  82. {
    
  83.         return _stream;
    
  84. }
    
  85.  
    
  86. const int GeometryStreamGenerator::getStreamSize() 
    
  87. {
    
  88.         int t = (int)ss->tellp();
    
  89.         return t;
    
  90. }
    
  91.  
    
  92. const int GeometryStreamGenerator::getNumVertices()
    
  93. {
    
  94.         return numVertices;
    
  95. }
    
  96.  
    
  97. const int GeometryStreamGenerator::getNumTriangleIndices()
    
  98. {
    
  99.         return numTriangleIndices;
    
  100. }
    
  101.  
    
  102. void GeometryStreamGenerator::release()
    
  103. {
    
  104.         ss->flush();
    
  105.         ss->clear();
    
  106.         delete ss;
    
  107.         ss = 0;
    
  108.         delete[] _stream;
    
  109.         _stream = 0;
    
  110. }
    

CustomGeometry base class

Base class for the custom geometry. This class currently contains lots of deprecated stuff, e.g. the update() function. This function was used to update an in-memory gemoetry resource in the "punk-rock"-way. Until Horde3D Beta3 the geometry resources were read-only, so directmanipulation of vertices was impossible. To modify the vertices I had to unload the geometry resource, re-create it with the new vertex-positions and load it into Horde again. This is not necessary any more because since Beta4 the geometry resources are not read-only anymore.

All custom geometry classes should be derived from this class and implement the abstract functions as needed. (See the examples below)

CustomGeometry.h
  1. #pragma once
    
  2. /**
    
  3.  * Abstract class for custom/dynamic geometry
    
  4.  **/
    
  5. #include "utMath.h"
    
  6. #include "Horde3D.h"
    
  7. #include <string>
    
  8.  
    
  9. class CustomGeometry 
    
  10. {
    
  11. protected:
    
  12.         float _size;
    
  13.         Vec3f _origin;
    
  14.         int _numVertices;
    
  15.         int _numTriangles;
    
  16.         int _numTriangleIndices;
    
  17.         float* _positions;
    
  18.         float* _normals;
    
  19.         float* _texCoords;
    
  20.         int* _tIndices;
    
  21.         std::string _name;
    
  22.         NodeHandle _model;
    
  23.         NodeHandle _parent;
    
  24.         ResHandle _material;
    
  25.         virtual void generatePositions() = 0;
    
  26.         virtual void generateNormals() = 0;
    
  27.         virtual void generateTexCoords() = 0;
    
  28.         virtual void generateTriangleIndices() = 0;
    
  29.  
    
  30. public:
    
  31.         CustomGeometry();
    
  32.         virtual void generate() = 0;
    
  33.         const int getNumVertices() { return _numVertices; }
    
  34.         const float* getPositions() { return _positions; }
    
  35.         const float* getNormals() { return _normals; }
    
  36.         const float* getTexCoords() { return _texCoords; }
    
  37.         const int* getTriangleIndices() { return _tIndices; }
    
  38.         const int getNumTriangles() { return _numTriangles; }
    
  39.         const int getNumTriangleIndices() { return _numTriangleIndices; }
    
  40.         void release();
    
  41.         const Vec3f getInterpolatedNormal(Vec3f n1_, Vec3f n2_);
    
  42.         // pass -1 as the parameter to leave the parent node unchanged
    
  43.         void addCustomModelNode(NodeHandle parent_);
    
  44.         bool removeCustomModelNode();
    
  45.         void setMaterial(ResHandle material_) { _material = material_; }
    
  46.         void setParent(NodeHandle parent_) { _parent = parent_; }
    
  47.         NodeHandle getModel() { return _model; }
    
  48.         ResHandle getMaterial() { return _material; }
    
  49.         void update();
    
  50.         Vec3f getOrigin() { return _origin; }
    
  51.         void setOrigin(Vec3f origin_) { _origin = origin_; }
    
  52.         const float getSize() { return _size; }
    
  53. };
    
CustomGeometry.cpp
  1. #include "CustomGeometry.h"
    
  2. #include <iostream>
    
  3. #include <string>
    
  4. #include <sstream>
    
  5. #include <fstream>
    
  6. #include "GeometryStreamGenerator.h"
    
  7. #include "Horde3DUtils.h"
    
  8.  
    
  9. CustomGeometry::CustomGeometry() : _name("default"), _size(1)
    
  10. {
    
  11.         _origin = Vec3f(0, 0, 0);
    
  12. }
    
  13.  
    
  14. void CustomGeometry::release()
    
  15. {
    
  16.         delete[] _positions;
    
  17.         _positions = 0;
    
  18.         delete[] _normals;
    
  19.         _normals = 0;
    
  20.         delete[] _texCoords;
    
  21.         _texCoords = 0;
    
  22.         delete[] _tIndices;
    
  23.         _tIndices = 0;
    
  24. }
    
  25.  
    
  26. const Vec3f CustomGeometry::getInterpolatedNormal(Vec3f n1_, Vec3f n2_) 
    
  27. {
    
  28.         Vec3f newNormal = n1_ + n2_;
    
  29.         float length = newNormal.length();
    
  30.         return newNormal/length;
    
  31. }
    
  32.  
    
  33. void CustomGeometry::addCustomModelNode(NodeHandle parent_)
    
  34. {
    
  35.         //std::stringstream* sa = new std::stringstream();
    
  36.         std::stringstream ss;
    
  37.         if (parent_ != -1) 
    
  38.                 _parent = parent_;
    
  39.         ss<< "customGeometry-";
    
  40.         ss<<_name;
    
  41.         GeometryStreamGenerator* gsg = new GeometryStreamGenerator(this);
    
  42.         ResHandle customGeoRes = Horde3D::addResource(ResourceTypes::Geometry, ss.str().c_str(), 0);
    
  43.         Horde3D::loadResource(customGeoRes, gsg->getStream(), gsg->getStreamSize());
    
  44.         // model_node_name
    
  45.         ss<<"-Node";
    
  46.         _model = Horde3D::addModelNode(_parent, ss.str().c_str(), customGeoRes);
    
  47.         // mesh_name
    
  48.         ss<<"-Mesh";
    
  49.         Horde3D::addMeshNode(_model, ss.str().c_str(), _material, 0, gsg->getNumTriangleIndices(), 0, gsg->getNumVertices()-1);
    
  50.         Horde3DUtils::dumpMessages();
    
  51.         ss.str("");
    
  52.         ss.clear();
    
  53.         ss.flush();
    
  54.         gsg->release();
    
  55.         delete gsg;
    
  56.         gsg = 0;
    
  57.         //Horde3D::setNodeTransform(_model, _origin.x, _origin.y, _origin.z, 0, 0, 0, 1, 1, 1);
    
  58. }
    
  59.  
    
  60. bool CustomGeometry::removeCustomModelNode()
    
  61. {
    
  62.         std::stringstream* ss = new std::stringstream();
    
  63.         *ss<< "customGeometry-";
    
  64.         *ss<<_name;
    
  65.         ResHandle rh = Horde3D::findResource(ResourceTypes::Geometry, ss->str().c_str());
    
  66.         if (Horde3D::isResourceLoaded(rh)) {
    
  67.                 Horde3D::removeResource(rh);
    
  68.                 Horde3D::unloadResource(rh);
    
  69.                 Horde3D::removeNode(_model);
    
  70.                 Horde3D::releaseUnusedResources();
    
  71.                 Horde3DUtils::dumpMessages();
    
  72.                 delete ss;
    
  73.                 return true;
    
  74.         }
    
  75.         else 
    
  76.                 return false;
    
  77. }
    
  78.  
    
  79. void CustomGeometry::update()
    
  80. {
    
  81.         removeCustomModelNode();
    
  82.         addCustomModelNode(-1);
    
  83. }
    

Simple Square

A simple hard-coded square. This is pretty straight forward and demonstrates how to derive from the CustomGeometry class and how the triangle indices work.

DynamicSquare.h
  1. /**
    
  2.  * Class representing a square 
    
  3.  **/
    
  4. #pragma once
    
  5. #include "CustomGeometry.h"
    
  6.  
    
  7. class DynamicSquare : public CustomGeometry
    
  8. {
    
  9. protected:
    
  10.         virtual void generatePositions();
    
  11.         virtual void generateNormals();
    
  12.         virtual void generateTexCoords();
    
  13.         virtual void generateTriangleIndices();
    
  14.  
    
  15. public:
    
  16.         DynamicSquare();
    
  17.         virtual void generate();
    
  18.         DynamicSquare(const float size_, const std::string name_);
    
  19. };
    
DynamicSquare.cpp
  1. #include "DynamicSquare.h"
    
  2.  
    
  3. DynamicSquare::DynamicSquare() : CustomGeometry()
    
  4. {
    
  5. }
    
  6.  
    
  7. DynamicSquare::DynamicSquare(const float size_, const std::string name_) 
    
  8. {
    
  9.         _size = size_;
    
  10.         _name = name_;
    
  11.         _numVertices = 4;
    
  12.         _numTriangles = 2;
    
  13.         _numTriangleIndices = _numTriangles * 3;
    
  14.         //generate();
    
  15. }
    
  16.  
    
  17. void DynamicSquare::generate() 
    
  18. {
    
  19.         generatePositions();
    
  20.         generateNormals();
    
  21.         generateTexCoords();
    
  22.         generateTriangleIndices();
    
  23. }
    
  24.  
    
  25. void DynamicSquare::generatePositions() 
    
  26. {
    
  27.         _positions = new float[_numVertices * 3 * 2];
    
  28.         // front left point (x/y/z)
    
  29.         _positions[0] = _origin.x * _size - _size/2;
    
  30.         _positions[1] = _origin.y;
    
  31.         _positions[2] = _origin.z * _size -_size/2;
    
  32.         // front right point (x/y/z)
    
  33.         _positions[3] = _origin.x * _size + _size/2;
    
  34.         _positions[4] = _origin.y;
    
  35.         _positions[5] = _origin.z * _size - _size/2;
    
  36.         // back left point (x/y/z)
    
  37.         _positions[6] = _origin.x * _size - _size/2;
    
  38.         _positions[7] = _origin.y;
    
  39.         _positions[8] = _origin.z * _size + _size/2;
    
  40.         // back right point (x/y/z)
    
  41.         _positions[9] = _origin.x * _size + _size/2;
    
  42.         _positions[10] = _origin.y;
    
  43.         _positions[11] = _origin.z * _size + _size/2;
    
  44.  
    
  45. }
    
  46.  
    
  47. void DynamicSquare::generateNormals() 
    
  48. {
    
  49.         _normals = new float[_numVertices * 3];
    
  50.         for (int i=0; i< 12; i+=3) {
    
  51.                 _normals[i] = 0;
    
  52.                 _normals[i+1] = 1;
    
  53.                 _normals[i+2] = 0;
    
  54.         }
    
  55. }
    
  56.  
    
  57. void DynamicSquare::generateTexCoords()
    
  58. {
    
  59.         _texCoords = new float[_numVertices * 2];
    
  60.         _texCoords[0] = 0.0f; 
    
  61.         _texCoords[1] = 0.0f;
    
  62.         _texCoords[2] = 1.0f; 
    
  63.         _texCoords[3] = 0.0f;
    
  64.         _texCoords[4] = 0.0f; 
    
  65.         _texCoords[5] = 1.0f;
    
  66.         _texCoords[6] = 1.0f; 
    
  67.         _texCoords[7] = 1.0f;
    
  68. }
    
  69.  
    
  70. void DynamicSquare::generateTriangleIndices() 
    
  71. {
    
  72.         _tIndices = new int[_numTriangleIndices ];
    
  73.         _tIndices[0] = 0;
    
  74.         _tIndices[1] = 2;
    
  75.         _tIndices[2] = 1;
    
  76.         _tIndices[3] = 1;
    
  77.         _tIndices[4] = 2;
    
  78.         _tIndices[5] = 3;
    
  79. }
    

Simple Grid

All the work above was made to create my own interactive terrain generator(screenshot on top of this page) for a A* pathfinding demonstrator. The Grid-class actually generates a 2-dimensional array of Vec3f(s) and allows to extrude each point and re-generate the mesh in realtime. The internal representation is writeable and in case of a change of any point the overridden update() function will be called to update the Horde3D geometry resource.

DynamicGrid.h
  1. /**
    
  2.  * Class representing a grid
    
  3.  **/
    
  4. #pragma once
    
  5. #include "CustomGeometry.h"
    
  6.  
    
  7. class DynamicGrid : public CustomGeometry
    
  8. {
    
  9. protected:
    
  10.         virtual void generatePositions();
    
  11.         virtual void generateNormals();
    
  12.         virtual void generateTexCoords();
    
  13.         virtual void generateTriangleIndices();
    
  14.        // generate the internal representation of the grid (writeable to allow updates of single points!)
    
  15.         void generateGrid();
    
  16.         int _gridSize;
    
  17.         Vec3f** _grid;
    
  18.         std::string _fileName;
    
  19.  
    
  20. public:
    
  21.         DynamicGrid();
    
  22.         virtual void generate();
    
  23.         DynamicGrid(const float size_, const std::string name_, std::string fileName_);
    
  24.         Vec3f getPointAt(int x_, int y_) { return _grid[y_][x_]; }
    
  25.         // update a point of our grid (args: index x, index y, new position)
    
  26.         void setPointAt(int x_, int y_, Vec3f newPos_) { _grid[y_][x_] = newPos_; }
    
  27.         int getGridSize() { return _gridSize; }
    
  28.         // overwrite update() from parent class
    
  29.         void update();
    
  30.         // read and write grids from/to files
    
  31.         void saveGridToFile(std::string fileName_);
    
  32.         bool readGridFromFile(std::string fileName_);
    
  33.  
    
  34. };
    
DynamicGrid.cpp
  1. #include "DynamicGrid.h"
    
  2. #include "rng.h"
    
  3. #include <iostream>
    
  4. #include <string>
    
  5. #include <sstream>
    
  6. #include <fstream>
    
  7. #include "util.h"
    
  8.  
    
  9. #define GRIDSIZE 50
    
  10.  
    
  11. DynamicGrid::DynamicGrid() : CustomGeometry()
    
  12. {
    
  13. }
    
  14.  
    
  15. DynamicGrid::DynamicGrid(const float size_, const std::string name_, std::string fileName_) : _fileName(fileName_) 
    
  16. {
    
  17.         _name = name_;
    
  18.         _positions = 0;
    
  19.         _normals = 0;
    
  20.         _texCoords = 0;
    
  21.         _tIndices = 0;
    
  22.         readGridFromFile(_fileName);
    
  23.         _numVertices = (_gridSize*_gridSize);
    
  24.         _numTriangles = ((_gridSize - 1) * (_gridSize - 1)) * 2;
    
  25.         _numTriangleIndices = _numTriangles * 3;
    
  26.         _origin = Vec3f(-_size/2*_gridSize, 0, _size/2*_gridSize);
    
  27.         /*
    
  28.         std::cout<<"numVerts: "<<_numVertices<<std::endl;
    
  29.         std::cout<<"numTris: "<<_numTriangles<<std::endl;
    
  30.         std::cout<<"numTInds: "<<_numTriangleIndices<<std::endl;
    
  31.         std::cout<<"size: "<<_size<<std::endl;
    
  32.         */
    
  33.         //std::cout<<_origin.x<<"/"<<_origin.y<<"/"<<_origin.z<<std::endl;
    
  34.         //generate();
    
  35. }
    
  36.  
    
  37. void DynamicGrid::generate() 
    
  38. {
    
  39.         if (!_grid)
    
  40.                 generateGrid();
    
  41.         generatePositions();
    
  42.         generateNormals();
    
  43.         generateTexCoords();
    
  44.         generateTriangleIndices();
    
  45. }
    
  46.  
    
  47. // the following two functions could be combined into one single loop, but I left it this way for clarity...
    
  48. /**
    
  49.  * This function simply generates a 2-dimensional array of Vec3f(s) with slightly random height values
    
  50.  **/
    
  51. void DynamicGrid::generateGrid()
    
  52. {
    
  53.         RNG rng;
    
  54.         _grid = new Vec3f*[_gridSize];
    
  55.         for (int y=0; y<_gridSize; ++y) {
    
  56.                 _grid[y] = new Vec3f[_gridSize];
    
  57.                 for (int x=0; x<_gridSize; ++x) {
    
  58.                         long rand = (abs((int)rng.rand_int31()) %3);
    
  59.                         _grid[y][x] = Vec3f(_origin.x/2+_size/2*x, rand, _origin.z/2-_size/2*y);
    
  60.                         //std::cout<<_grid[y][x].x<<"/"<<_grid[y][x].y<<"/"<<_grid[y][x].z<<std::endl;
    
  61.                 }
    
  62.         }
    
  63. }
    
  64.  
    
  65. /**
    
  66.  * Convert the grid's positions into a Horde3D vertex array.
    
  67.  **/
    
  68. void DynamicGrid::generatePositions() 
    
  69. {
    
  70.         _positions = new float[_numVertices*3];
    
  71.         int counter = 0;
    
  72.         for (int i=0; i<_numVertices*3; i+=3) {
    
  73.                 int y = counter / _gridSize;
    
  74.                 int x = counter % _gridSize;
    
  75.                 _positions[i] = _grid[y][x].x;
    
  76.                 _positions[i+1] = _grid[y][x].y;
    
  77.                 _positions[i+2] = _grid[y][x].z;
    
  78.                 ++counter;
    
  79.         }
    
  80. }
    
  81.  
    
  82. void DynamicGrid::generateNormals() 
    
  83. {
    
  84.         _normals = new float[_numVertices * 3];
    
  85.         for (int i=0; i< _numVertices*3; i+=3) {
    
  86.                 int pos = i/3;
    
  87.                 int xPos = pos % _gridSize;
    
  88.                 int yPos = pos / _gridSize;
    
  89.                 Vec3f xPred;
    
  90.                 Vec3f xSucc;
    
  91.                 Vec3f yPred;
    
  92.                 Vec3f ySucc;
    
  93.                 Vec3f normal;
    
  94.                 if (xPos > 0 && yPos > 0) {
    
  95.                         // if the current vertex is inside the grid we will calculate
    
  96.                         // two normals from the previous&next point and our current vertex
    
  97.                         if (xPos < _gridSize-1 && yPos < _gridSize-1) {
    
  98.                                 xSucc = _grid[yPos][xPos+1];
    
  99.                                 xPred = _grid[yPos][xPos-1];
    
  100.                                 ySucc = _grid[yPos+1][xPos];
    
  101.                                 yPred = _grid[yPos-1][xPos];
    
  102.                                 Vec3f v1 = xSucc - _grid[yPos][xPos];
    
  103.                                 if (v1.y < 0)
    
  104.                                         v1.y *= -1;
    
  105.                                 Vec3f v2 = xPred - _grid[yPos][xPos];
    
  106.                                 if (v2.y < 0)
    
  107.                                         v2.y *= -1;
    
  108.                                 v1 += v2;
    
  109.                                 Vec3f v3 = ySucc - _grid[yPos][xPos];
    
  110.                                 if (v3.y < 0)
    
  111.                                         v3.y *= -1;
    
  112.                                 Vec3f v4 = yPred - _grid[yPos][xPos];
    
  113.                                 if (v4.y < 0)
    
  114.                                         v4.y *= -1;
    
  115.                                 v3 += v4;
    
  116.                                 normal = getInterpolatedNormal(v1, v3);
    
  117.                         }
    
  118.                         // if the vertex is on the grid's border the normal will simply be 0/1/0
    
  119.                         else {
    
  120.                                 normal = Vec3f(0,1,0);
    
  121.                         }
    
  122.                 }
    
  123.                 else {
    
  124.                         normal = Vec3f(0,1,0);
    
  125.                 }
    
  126.                 _normals[i] = normal.x;
    
  127.                 _normals[i+1] = normal.y;
    
  128.                 _normals[i+2] = normal.z;
    
  129.         }
    
  130. }
    
  131.  
    
  132. void DynamicGrid::generateTexCoords()
    
  133. {
    
  134.         _texCoords = new float[_numVertices * 2];
    
  135.         int counter = 0;
    
  136.         int line = 0;
    
  137.         for (int i=0; i<_numVertices*2; i+=2) {
    
  138.                 if ( line % 2 == 0) {
    
  139.                         if (counter %2 == 0) {
    
  140.                                 _texCoords[i] = 0.0f;
    
  141.                                 _texCoords[i+1] = 0.0f;
    
  142.                         }
    
  143.                         else {
    
  144.                                 _texCoords[i] = 0.0f;
    
  145.                                 _texCoords[i+1] = 1.0f;
    
  146.                         }
    
  147.                 }
    
  148.                 else {
    
  149.                         if (counter % 2 == 0) {
    
  150.                                 _texCoords[i] = 1.0f;
    
  151.                                 _texCoords[i+1] = 0.0f;
    
  152.                         }
    
  153.                         else {
    
  154.                                 _texCoords[i] = 1.0f;
    
  155.                                 _texCoords[i+1] = 1.0f;
    
  156.                         }
    
  157.                 }
    
  158.                 ++counter;
    
  159.                 if (counter >= _gridSize) {
    
  160.                         ++line;
    
  161.                         counter = 0;
    
  162.                 }
    
  163.         }
    
  164. }
    
  165.  
    
  166. void DynamicGrid::generateTriangleIndices() 
    
  167. {
    
  168.         _tIndices = new int[ _numTriangleIndices ];
    
  169.         int counter = 0;
    
  170.         int lineBreakCounter = 0;
    
  171.         int counter3 = 0;
    
  172.         for (int i=0; i<_numTriangleIndices; i+=3) {
    
  173.                 if (i%2 ==0) {
    
  174.                         _tIndices[i] = counter;
    
  175.                         _tIndices[i+1] = counter+1;
    
  176.                         _tIndices[i+2] = counter+_gridSize;
    
  177.                 }
    
  178.                 else {
    
  179.                         _tIndices[i] = counter + _gridSize;
    
  180.                         _tIndices[i+1] = counter + 1;
    
  181.                         _tIndices[i+2] = counter+_gridSize+1;
    
  182.                         ++counter;
    
  183.                 }
    
  184.                 ++lineBreakCounter;
    
  185.                 if (lineBreakCounter == _gridSize*2 - 2) {
    
  186.                         --counter;
    
  187.                         ++counter3;
    
  188.                         lineBreakCounter = 0;
    
  189.                         counter = counter3*_gridSize;
    
  190.                 }
    
  191.                 //std::cout<<_tIndices[i]<<"/"<<_tIndices[i+1]<<"/"<<_tIndices[i+2]<<std::endl;
    
  192.         }
    
  193. }
    
  194.  
    
  195. void DynamicGrid::update()
    
  196. {
    
  197.         removeCustomModelNode();
    
  198.         delete[] _positions;
    
  199.         _positions = 0;
    
  200.         delete[] _normals;
    
  201.         _normals = 0;
    
  202.         generatePositions();
    
  203.         generateNormals();
    
  204.         addCustomModelNode(-1);
    
  205. }
    
  206.  
    
  207. void DynamicGrid::saveGridToFile(std::string fileName_)
    
  208. {
    
  209.         //std::stringstream fName;
    
  210.         //fName<<fileName_;
    
  211.         //fName<<".d2g";
    
  212.         std::stringstream ss;
    
  213.         // magic header
    
  214.         ss<<"D2SG\n";
    
  215.         // the gridsize (important to know!)
    
  216.         ss<<_gridSize;
    
  217.         ss<<"\n";
    
  218.         // the quadsize (important to know!)
    
  219.         ss<<_size;
    
  220.         ss<<"\n";
    
  221.         // number of coordinates (most important to know!)
    
  222.         ss<<(_gridSize*_gridSize*3);
    
  223.         ss<<"\n";
    
  224.         // coordinates
    
  225.         for (int y=0; y<_gridSize; ++y) {
    
  226.                 for (int x=0; x<_gridSize; ++x) {
    
  227.                         ss<<_grid[y][x].x;
    
  228.                         ss<<"\n";
    
  229.                         ss<<_grid[y][x].y;
    
  230.                         ss<<"\n";
    
  231.                         ss<<_grid[y][x].z;
    
  232.                         ss<<"\n";
    
  233.                 }
    
  234.         }
    
  235.         ss<<"\n";
    
  236.         std::ofstream dest(fileName_.c_str());
    
  237.         if (dest.is_open()) {
    
  238.                 dest<<ss.str();
    
  239.                 dest.close();
    
  240.         }
    
  241.         std::cout<<"Grid successfully saved to file: "<<fileName_<<std::endl;
    
  242. }
    
  243.  
    
  244. bool DynamicGrid::readGridFromFile(std::string fileName_)
    
  245. {
    
  246.         int numCoordinates;
    
  247.         std::ifstream inFile;
    
  248.         inFile.open(fileName_.c_str());
    
  249.         bool error = false;
    
  250.         if (!inFile) {
    
  251.                 std::cout<<"Gridfile "<<fileName_<<" could not be found! Creating new grid."<<std::endl;
    
  252.                 error = true;
    
  253.         }
    
  254.         else {
    
  255.                 std::string line;
    
  256.                 if (std::getline(inFile, line)) {
    
  257.                         std::cout<<"Line: "<<line<<std::endl;
    
  258.                         if (line != "D2SG") {
    
  259.                                 std::cout<<"wrong grid-file format "<<line.compare("D2SG")<<std::endl;
    
  260.                                 error = true;
    
  261.                         }
    
  262.                         else {
    
  263.                                 std::cout<<"Valid grid-file found!"<<std::endl;
    
  264.                         }
    
  265.                 }
    
  266.                 if (std::getline(inFile, line)) {
    
  267.                         _gridSize = stringToInt(line);
    
  268.                         //std::cout<<"gridsize: "<<_gridSize<<std::endl;
    
  269.                 }
    
  270.                 else {
    
  271.                         error = true;
    
  272.                 }
    
  273.                 if (std::getline(inFile, line)) {
    
  274.                         _size = stringToInt(line);
    
  275.                         //std::cout<<"quadsize: "<<_size<<std::endl;
    
  276.                 }
    
  277.                 else {
    
  278.                         error = true;
    
  279.                 }
    
  280.                 if (std::getline(inFile, line)) {
    
  281.                         numCoordinates = stringToInt(line);
    
  282.                         //std::cout<<"numCoords: "<<numCoordinates<<std::endl;
    
  283.                 }
    
  284.                 else {
    
  285.                         error = true;
    
  286.                 }
    
  287.                 if (!error) {
    
  288.                         _grid = new Vec3f*[_gridSize];
    
  289.                         for(int y=0; y<_gridSize; ++y) {
    
  290.                                 _grid[y] = new Vec3f[_gridSize];
    
  291.                                 for (int x=0; x<_gridSize; ++x) {
    
  292.                                         Vec3f v;
    
  293.                                         if (std::getline(inFile, line)) {
    
  294.                                                 v.x = stringToFloat(line);
    
  295.                                         }
    
  296.                                         if (std::getline(inFile, line)) {
    
  297.                                                 v.y = stringToFloat(line);
    
  298.                                         }
    
  299.                                         if (std::getline(inFile, line)) {
    
  300.                                                 v.z = stringToFloat(line);
    
  301.                                         }
    
  302.                                         _grid[y][x] = v;
    
  303.                                 }
    
  304.                         }
    
  305.                 }
    
  306.         }
    
  307.         inFile.close();
    
  308.         if (error) {
    
  309.                 _gridSize = GRIDSIZE;
    
  310.                 _size = 12;
    
  311.                 _grid = 0;
    
  312.         }
    
  313.         _numVertices = (_gridSize*_gridSize);
    
  314.         _numTriangles = ((_gridSize - 1) * (_gridSize - 1)) * 2;
    
  315.         _numTriangleIndices = _numTriangles * 3;
    
  316.         _origin = Vec3f(-_size/2*_gridSize, 0, _size/2*_gridSize);
    
  317.         return true;
    
  318. }
    

Usage example

Finally this is all you have to do to generate the grid and display it in your scene.

app.cpp
  1.         // initialize a new grid (args: quadsize, model-name, filename (if applicable)
    
  2.         _grid = new DynamicGrid(12.0f, "grid", "grid-filename");
    
  3.         // do not forget to load a material and apply it to the mesh
    
  4.         _grid->setMaterial(gridMatRes);
    
  5.         // generate the grid
    
  6.         _grid->generate();
    
  7.         // add the grid-model to the RootNode
    
  8.         _grid->addCustomModelNode(RootNode);
    

TODO

Personal tools