Mesh.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. #include "Base.h"
  2. #include "Mesh.h"
  3. #include "Model.h"
  4. namespace gameplay
  5. {
  6. Mesh::Mesh(void) : model(NULL)
  7. {
  8. }
  9. Mesh::~Mesh(void)
  10. {
  11. }
  12. unsigned int Mesh::getTypeId(void) const
  13. {
  14. return MESH_ID;
  15. }
  16. const char* Mesh::getElementName(void) const
  17. {
  18. return "Mesh";
  19. }
  20. void Mesh::writeBinary(FILE* file)
  21. {
  22. Object::writeBinary(file);
  23. // vertex formats
  24. write(_vertexFormat.size(), file);
  25. for (std::vector<VertexElement>::iterator i = _vertexFormat.begin(); i != _vertexFormat.end(); i++)
  26. {
  27. i->writeBinary(file);
  28. }
  29. // vertices
  30. writeBinaryVertices(file);
  31. // parts
  32. writeBinaryObjects(parts, file);
  33. }
  34. /////////////////////////////////////////////////////////////
  35. //
  36. // Fast, Minimum Storage Ray-Triangle Intersection
  37. //
  38. // Authors: Tomas Möller, Ben Trumbore
  39. // http://jgt.akpeters.com/papers/MollerTrumbore97
  40. //
  41. // Implementation of algorithm from Real-Time Rendering (vol 1), pg. 305.
  42. //
  43. // Adapted slightly for use here.
  44. //
  45. #define EPSILON 0.000001
  46. #define CROSS(dest,v1,v2) \
  47. dest[0]=v1[1]*v2[2]-v1[2]*v2[1]; \
  48. dest[1]=v1[2]*v2[0]-v1[0]*v2[2]; \
  49. dest[2]=v1[0]*v2[1]-v1[1]*v2[0];
  50. #define DOT(v1,v2) (v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2])
  51. #define SUB(dest,v1,v2) \
  52. dest[0]=v1[0]-v2[0]; \
  53. dest[1]=v1[1]-v2[1]; \
  54. dest[2]=v1[2]-v2[2];
  55. int
  56. intersect_triangle(const float orig[3], const float dir[3],
  57. const float vert0[3], const float vert1[3], const float vert2[3],
  58. float *t, float *u, float *v)
  59. {
  60. float edge1[3], edge2[3], tvec[3], pvec[3], qvec[3];
  61. float det,inv_det;
  62. /* find vectors for two edges sharing vert0 */
  63. SUB(edge1, vert1, vert0);
  64. SUB(edge2, vert2, vert0);
  65. /* begin calculating determinant - also used to calculate U parameter */
  66. CROSS(pvec, dir, edge2);
  67. /* if determinant is near zero, ray lies in plane of triangle */
  68. det = DOT(edge1, pvec);
  69. if (det > -EPSILON && det < EPSILON)
  70. return 0;
  71. inv_det = 1.0f / det;
  72. /* calculate distance from vert0 to ray origin */
  73. SUB(tvec, orig, vert0);
  74. /* calculate U parameter and test bounds */
  75. *u = DOT(tvec, pvec) * inv_det;
  76. if (*u < 0.0 || *u > 1.0)
  77. return 0;
  78. /* prepare to test V parameter */
  79. CROSS(qvec, tvec, edge1);
  80. /* calculate V parameter and test bounds */
  81. *v = DOT(dir, qvec) * inv_det;
  82. if (*v < 0.0 || *u + *v > 1.0)
  83. return 0;
  84. /* calculate t, ray intersects triangle */
  85. *t = DOT(edge2, qvec) * inv_det;
  86. return 1;
  87. }
  88. // Performs an intersection test between a ray and the given mesh part
  89. // and stores the result in "point".
  90. bool intersect(const Vector3& rayOrigin, const Vector3& rayDirection, const std::vector<Vertex>& vertices, const std::vector<MeshPart*>& parts, Vector3* point)
  91. {
  92. const float* orig = &rayOrigin.x;
  93. const float* dir = &rayDirection.x;
  94. for (unsigned int i = 0, partCount = parts.size(); i < partCount; ++i)
  95. {
  96. MeshPart* part = parts[i];
  97. for (unsigned int j = 0, indexCount = part->getIndicesCount(); j < indexCount; j += 3)
  98. {
  99. const float* v0 = &vertices[part->getIndex( j )].position.x;
  100. const float* v1 = &vertices[part->getIndex(j+1)].position.x;
  101. const float* v2 = &vertices[part->getIndex(j+2)].position.x;
  102. float t, u, v;
  103. if (intersect_triangle(orig, dir, v0, v1, v2, &t, &u, &v))
  104. {
  105. // Found an intersection!
  106. if (point)
  107. {
  108. Vector3 rd(rayDirection);
  109. rd.scale(t);
  110. Vector3::add(rayOrigin, rd, point);
  111. }
  112. return true;
  113. }
  114. }
  115. }
  116. return false;
  117. }
  118. void Mesh::generateHeightmap(const char* filename)
  119. {
  120. // Shoot rays down from a point just above the max Y position of the mesh.
  121. // Compute ray-triangle intersection tests against the ray and this mesh to
  122. // generate heightmap data.
  123. Vector3 rayOrigin(0, bounds.max.y + 10, 0);
  124. Vector3 rayDirection(0, -1, 0);
  125. Vector3 intersectionPoint;
  126. int minX = (int)ceil(bounds.min.x);
  127. int maxX = (int)floor(bounds.max.x);
  128. int minZ = (int)ceil(bounds.min.z);
  129. int maxZ = (int)floor(bounds.max.z);
  130. int width = maxX - minX + 1;
  131. int height = maxZ - minZ + 1;
  132. float* heights = new float[width * height];
  133. int index = 0;
  134. float minHeight = FLT_MAX;
  135. float maxHeight = -FLT_MAX;
  136. for (int z = minZ; z <= maxZ; z++)
  137. {
  138. rayOrigin.z = (float)z;
  139. for (int x = minX; x <= maxX; x++)
  140. {
  141. float h;
  142. rayOrigin.x = (float)x;
  143. if (intersect(rayOrigin, rayDirection, vertices, parts, &intersectionPoint))
  144. {
  145. h = intersectionPoint.y;
  146. }
  147. else
  148. {
  149. h = 0;
  150. fprintf(stderr, "Warning: Heightmap triangle intersection failed for (%d, %d).\n", x, z);
  151. }
  152. if (h < minHeight)
  153. minHeight = h;
  154. if (h > maxHeight)
  155. maxHeight = h;
  156. heights[index++] = h;
  157. }
  158. }
  159. // Normalize the max height value
  160. maxHeight = maxHeight - minHeight;
  161. png_structp png_ptr = NULL;
  162. png_infop info_ptr = NULL;
  163. png_bytep row = NULL;
  164. FILE* fp = fopen(filename, "wb");
  165. if (fp == NULL)
  166. {
  167. fprintf(stderr, "Error: Failed to open file for writing: %s\n", filename);
  168. goto error;
  169. }
  170. png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
  171. if (png_ptr == NULL)
  172. {
  173. fprintf(stderr, "Error: Write struct creation failed: %s\n", filename);
  174. goto error;
  175. }
  176. info_ptr = png_create_info_struct(png_ptr);
  177. if (info_ptr == NULL)
  178. {
  179. fprintf(stderr, "Error: Info struct creation failed: %s\n", filename);
  180. goto error;
  181. }
  182. png_init_io(png_ptr, fp);
  183. png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  184. png_write_info(png_ptr, info_ptr);
  185. // Allocate memory for a single row of image data
  186. row = (png_bytep)malloc(3 * width * sizeof(png_byte));
  187. for (int y = 0; y < height; y++)
  188. {
  189. for (int x = 0; x < width; x++)
  190. {
  191. // Write height value normalized between 0-255 (between min and max height)
  192. float h = heights[y*width + x];
  193. float nh = (h - minHeight) / maxHeight;
  194. png_byte b = (png_byte)(nh * 255.0f);
  195. int pos = x*3;
  196. row[pos] = row[pos+1] = row[pos+2] = b;
  197. }
  198. png_write_row(png_ptr, row);
  199. }
  200. png_write_end(png_ptr, NULL);
  201. DEBUGPRINT_VARG("> Saved heightmap: %s\n", filename);
  202. error:
  203. if (heights)
  204. delete[] heights;
  205. if (fp)
  206. fclose(fp);
  207. if (row)
  208. free(row);
  209. if (info_ptr)
  210. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  211. if (png_ptr)
  212. png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
  213. }
  214. void Mesh::writeBinaryVertices(FILE* file)
  215. {
  216. if (vertices.size() > 0)
  217. {
  218. // Assumes that all vertices are the same size.
  219. // Write the number of bytes for the vertex data
  220. const Vertex& vertex = vertices.front();
  221. write(vertices.size() * vertex.byteSize(), file); // (vertex count) * (vertex size)
  222. // for each vertex
  223. for (std::vector<Vertex>::const_iterator i = vertices.begin(); i != vertices.end(); ++i)
  224. {
  225. // Write this vertex
  226. i->writeBinary(file);
  227. }
  228. }
  229. else
  230. {
  231. // No vertex data
  232. write((unsigned int)0, file);
  233. }
  234. // Write bounds
  235. write(&bounds.min.x, 3, file);
  236. write(&bounds.max.x, 3, file);
  237. write(&bounds.center.x, 3, file);
  238. write(bounds.radius, file);
  239. }
  240. void Mesh::writeText(FILE* file)
  241. {
  242. fprintElementStart(file);
  243. // for each VertexFormat
  244. if (vertices.size() > 0 )
  245. {
  246. for (std::vector<VertexElement>::iterator i = _vertexFormat.begin(); i != _vertexFormat.end(); i++)
  247. {
  248. i->writeText(file);
  249. }
  250. }
  251. // for each Vertex
  252. fprintf(file, "<vertices count=\"%lu\">\n", vertices.size());
  253. for (std::vector<Vertex>::iterator i = vertices.begin(); i != vertices.end(); ++i)
  254. {
  255. i->writeText(file);
  256. }
  257. fprintf(file, "</vertices>\n");
  258. // write bounds
  259. fprintf(file, "<bounds>\n");
  260. fprintf(file, "<min>\n");
  261. writeVectorText(bounds.min, file);
  262. fprintf(file, "</min>\n");
  263. fprintf(file, "<max>\n");
  264. writeVectorText(bounds.max, file);
  265. fprintf(file, "</max>\n");
  266. fprintf(file, "<center>\n");
  267. writeVectorText(bounds.center, file);
  268. fprintf(file, "</center>\n");
  269. fprintf(file, "<radius>%f</radius>\n", bounds.radius);
  270. fprintf(file, "</bounds>\n");
  271. // for each MeshPart
  272. for (std::vector<MeshPart*>::iterator i = parts.begin(); i != parts.end(); ++i)
  273. {
  274. (*i)->writeText(file);
  275. }
  276. fprintElementEnd(file);
  277. }
  278. void Mesh::addMeshPart(MeshPart* part)
  279. {
  280. parts.push_back(part);
  281. }
  282. void Mesh::addMeshPart(Vertex* vertex)
  283. {
  284. vertices.push_back(*vertex);
  285. }
  286. void Mesh::addVetexAttribute(unsigned int usage, unsigned int count)
  287. {
  288. _vertexFormat.push_back(VertexElement(usage, count));
  289. }
  290. size_t Mesh::getVertexCount() const
  291. {
  292. return vertices.size();
  293. }
  294. const Vertex& Mesh::getVertex(unsigned int index) const
  295. {
  296. return vertices[index];
  297. }
  298. size_t Mesh::getVertexElementCount() const
  299. {
  300. return _vertexFormat.size();
  301. }
  302. const VertexElement& Mesh::getVertexElement(unsigned int index) const
  303. {
  304. return _vertexFormat[index];
  305. }
  306. bool Mesh::contains(const Vertex& vertex) const
  307. {
  308. return vertexLookupTable.count(vertex) > 0;
  309. }
  310. unsigned int Mesh::addVertex(const Vertex& vertex)
  311. {
  312. unsigned int index = getVertexCount();
  313. vertices.push_back(vertex);
  314. vertexLookupTable[vertex] = index;
  315. return index;
  316. }
  317. unsigned int Mesh::getVertexIndex(const Vertex& vertex)
  318. {
  319. std::map<Vertex,unsigned int>::iterator it;
  320. it = vertexLookupTable.find(vertex);
  321. return it->second;
  322. }
  323. void Mesh::computeBounds()
  324. {
  325. // If we have a Model with a MeshSkin associated with it,
  326. // compute the bounds from the skin - otherwise compute
  327. // it from the local mesh data.
  328. if (model && model->getSkin())
  329. {
  330. model->getSkin()->computeBounds();
  331. return;
  332. }
  333. bounds.min.x = bounds.min.y = bounds.min.z = FLT_MAX;
  334. bounds.max.x = bounds.max.y = bounds.max.z = -FLT_MAX;
  335. bounds.center.x = bounds.center.y = bounds.center.z = 0.0f;
  336. bounds.radius = 0.0f;
  337. for (std::vector<Vertex>::const_iterator i = vertices.begin(); i != vertices.end(); ++i)
  338. {
  339. // Update min/max for this vertex
  340. if (i->position.x < bounds.min.x)
  341. bounds.min.x = i->position.x;
  342. if (i->position.y < bounds.min.y)
  343. bounds.min.y = i->position.y;
  344. if (i->position.z < bounds.min.z)
  345. bounds.min.z = i->position.z;
  346. if (i->position.x > bounds.max.x)
  347. bounds.max.x = i->position.x;
  348. if (i->position.y > bounds.max.y)
  349. bounds.max.y = i->position.y;
  350. if (i->position.z > bounds.max.z)
  351. bounds.max.z = i->position.z;
  352. }
  353. // Compute center point
  354. Vector3::add(bounds.min, bounds.max, &bounds.center);
  355. bounds.center.scale(0.5f);
  356. // Compute radius by looping through all points again and finding the max
  357. // distance between the center point and each vertex position
  358. for (std::vector<Vertex>::const_iterator i = vertices.begin(); i != vertices.end(); ++i)
  359. {
  360. float d = bounds.center.distanceSquared(i->position);
  361. if (d > bounds.radius)
  362. {
  363. bounds.radius = d;
  364. }
  365. }
  366. // Convert squared distance to distance for radius
  367. bounds.radius = sqrt(bounds.radius);
  368. }
  369. }