Heightmap.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. #include "Heightmap.h"
  2. #include "GPBFile.h"
  3. #include "Thread.h"
  4. namespace gameplay
  5. {
  6. // Number of threads to spawn for the heightmap generator
  7. #define THREAD_COUNT 8
  8. // Thread data structure
  9. struct HeightmapThreadData
  10. {
  11. float rayHeight; // [in]
  12. const Vector3* rayDirection; // [in]
  13. const std::vector<Mesh*>* meshes; // [in]
  14. const BoundingVolume* bounds; // [in]
  15. float minX; // [in]
  16. float maxX; // [in]
  17. float minZ; // [in]
  18. float maxZ; // [in]
  19. float stepX; // [in]
  20. float stepZ; // [in]
  21. float minHeight; // [out]
  22. float maxHeight; // [out]
  23. float* heights; // [in][out]
  24. int width; // [in]
  25. int height; // [in]
  26. int heightIndex; // [in]
  27. };
  28. // Globals used by thread
  29. int __processedHeightmapScanLines = 0;
  30. int __totalHeightmapScanlines = 0;
  31. int __failedRayCasts = 0;
  32. // Forward declarations
  33. int generateHeightmapChunk(void* threadData);
  34. bool intersect(const Vector3& rayOrigin, const Vector3& rayDirection, const Vector3& boxMin, const Vector3& boxMax, float* distance = NULL);
  35. int intersect_triangle(const float orig[3], const float dir[3], const float vert0[3], const float vert1[3], const float vert2[3], float *t, float *u, float *v);
  36. bool intersect(const Vector3& rayOrigin, const Vector3& rayDirection, const std::vector<Vertex>& vertices, const std::vector<MeshPart*>& parts, Vector3* point);
  37. void Heightmap::generate(const std::vector<std::string>& nodeIds, int width, int height, const char* filename, bool highP)
  38. {
  39. LOG(1, "Generating heightmap: %s...\n", filename);
  40. // Initialize state variables
  41. __processedHeightmapScanLines = 0;
  42. __totalHeightmapScanlines = 0;
  43. __failedRayCasts = 0;
  44. GPBFile* gpbFile = GPBFile::getInstance();
  45. // Lookup nodes in GPB file and compute a single bounding volume that encapsulates all meshes
  46. // to be included in the heightmap generation.
  47. BoundingVolume bounds;
  48. bounds.min.set(FLT_MAX, FLT_MAX, FLT_MAX);
  49. bounds.max.set(-FLT_MAX, -FLT_MAX, -FLT_MAX);
  50. std::vector<Mesh*> meshes;
  51. for (unsigned int j = 0, ncount = nodeIds.size(); j < ncount; ++j)
  52. {
  53. Node* node = gpbFile->getNode(nodeIds[j].c_str());
  54. if (node)
  55. {
  56. Mesh* mesh = node->getModel() ? node->getModel()->getMesh() : NULL;
  57. if (mesh)
  58. {
  59. // Add this mesh and update our bounding volume
  60. if (meshes.size() == 0)
  61. bounds = mesh->bounds;
  62. else
  63. bounds.merge(mesh->bounds);
  64. meshes.push_back(mesh);
  65. }
  66. else
  67. {
  68. LOG(1, "WARNING: Node passed to heightmap argument does not have a mesh: %s\n", nodeIds[j].c_str());
  69. }
  70. }
  71. else
  72. {
  73. LOG(1, "WARNING: Failed to locate node for heightmap argument: %s\n", nodeIds[j].c_str());
  74. }
  75. }
  76. if (meshes.size() == 0)
  77. {
  78. LOG(1, "WARNING: Skipping generation of heightmap '%s'. No nodes found.\n", filename);
  79. return;
  80. }
  81. // Shoot rays down from a point just above the max Y position of the mesh.
  82. // Compute ray-triangle intersection tests against the ray and this mesh to
  83. // generate heightmap data.
  84. Vector3 rayOrigin(0, bounds.max.y + 10, 0);
  85. Vector3 rayDirection(0, -1, 0);
  86. float minX = bounds.min.x;
  87. float maxX = bounds.max.x;
  88. float minZ = bounds.min.z;
  89. float maxZ = bounds.max.z;
  90. int size = width * height;
  91. float* heights = new float[size];
  92. float minHeight = FLT_MAX;
  93. float maxHeight = -FLT_MAX;
  94. __totalHeightmapScanlines = height;
  95. // Determine # of threads to spawn
  96. int threadCount = std::min(THREAD_COUNT, height);
  97. // Split the work into separate threads to make max use of available cpu cores and speed up computation.
  98. HeightmapThreadData* threadData = new HeightmapThreadData[threadCount];
  99. THREAD_HANDLE* threads = new THREAD_HANDLE[threadCount];
  100. int stepSize = height / threadCount;
  101. for (int i = 0, remaining = height; i < threadCount; ++i, remaining -= stepSize)
  102. {
  103. HeightmapThreadData& data = threadData[i];
  104. data.rayHeight = rayOrigin.y;
  105. data.rayDirection = &rayDirection;
  106. data.bounds = &bounds;
  107. data.meshes = &meshes;
  108. data.minX = minX;
  109. data.maxX = maxX;
  110. data.minZ = minZ + (stepSize * i);
  111. data.maxZ = data.minZ + stepSize - 1;
  112. if (i == threadCount - 1)
  113. data.maxZ = maxZ;
  114. data.stepX = (maxX - minX) / width;
  115. data.stepZ = (maxZ - minZ) / height;
  116. data.heights = heights;
  117. data.width = width;
  118. data.height = remaining > stepSize ? stepSize : remaining;
  119. data.heightIndex = width * (stepSize * i);
  120. // Start the processing thread
  121. if (!createThread(&threads[i], &generateHeightmapChunk, &data))
  122. {
  123. LOG(1, "ERROR: Failed to spawn worker thread for generation of heightmap: %s\n", filename);
  124. return;
  125. }
  126. }
  127. // Wait for all threads to terminate
  128. waitForThreads(threadCount, threads);
  129. // Close all thread handles and free memory allocations.
  130. for (int i = 0; i < threadCount; ++i)
  131. closeThread(threads[i]);
  132. // Update min/max height from all completed threads
  133. for (int i = 0; i < threadCount; ++i)
  134. {
  135. if (threadData[i].minHeight < minHeight)
  136. minHeight = threadData[i].minHeight;
  137. if (threadData[i].maxHeight > maxHeight)
  138. maxHeight = threadData[i].maxHeight;
  139. }
  140. LOG(1, "\r\tDone.\n");
  141. if (__failedRayCasts)
  142. {
  143. LOG(2, "Warning: %d triangle intersections failed for heightmap: %s\n", __failedRayCasts, filename);
  144. // Go through and clamp any height values that are set to -FLT_MAX to the min recorded height value
  145. // (otherwise the range of height values will be far too large).
  146. for (int i = 0; i < size; ++i)
  147. {
  148. if (heights[i] == -FLT_MAX)
  149. heights[i] = minHeight;
  150. }
  151. }
  152. // Normalize the max height value
  153. maxHeight = maxHeight - minHeight;
  154. png_structp png_ptr = NULL;
  155. png_infop info_ptr = NULL;
  156. png_bytep row = NULL;
  157. FILE* fp = fopen(filename, "wb");
  158. if (fp == NULL)
  159. {
  160. LOG(1, "Error: Failed to open file for writing: %s\n", filename);
  161. goto error;
  162. }
  163. png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
  164. if (png_ptr == NULL)
  165. {
  166. LOG(1, "Error: Write struct creation failed: %s\n", filename);
  167. goto error;
  168. }
  169. info_ptr = png_create_info_struct(png_ptr);
  170. if (info_ptr == NULL)
  171. {
  172. LOG(1, "Error: Info struct creation failed: %s\n", filename);
  173. goto error;
  174. }
  175. png_init_io(png_ptr, fp);
  176. 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);
  177. png_write_info(png_ptr, info_ptr);
  178. // Allocate memory for a single row of image data
  179. row = (png_bytep)malloc(3 * width * sizeof(png_byte));
  180. for (int y = 0; y < height; y++)
  181. {
  182. for (int x = 0; x < width; x++)
  183. {
  184. // Write height value normalized between 0-255 (between min and max height)
  185. float h = heights[y*width + x];
  186. float nh = (h - minHeight) / maxHeight;
  187. int pos = x*3;
  188. if (highP)
  189. {
  190. // high precision packed 24-bit (RGB)
  191. int bits = (int)(nh * 16777215.0f); // 2^24-1
  192. row[pos+2] = (png_byte)(bits & 0xff);
  193. bits >>= 8;
  194. row[pos+1] = (png_byte)(bits & 0xff);
  195. bits >>= 8;
  196. row[pos] = (png_byte)(bits & 0xff);
  197. }
  198. else
  199. {
  200. // standard precision 8-bit (grayscale)
  201. png_byte b = (png_byte)(nh * 255.0f);
  202. row[pos] = row[pos+1] = row[pos+2] = b;
  203. }
  204. }
  205. png_write_row(png_ptr, row);
  206. }
  207. png_write_end(png_ptr, NULL);
  208. LOG(1, "Saved heightmap: %s\n", filename);
  209. error:
  210. if (threadData)
  211. delete[] threadData;
  212. if (threads)
  213. delete[] threads;
  214. if (heights)
  215. delete[] heights;
  216. if (fp)
  217. fclose(fp);
  218. if (row)
  219. free(row);
  220. if (info_ptr)
  221. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  222. if (png_ptr)
  223. png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
  224. }
  225. int generateHeightmapChunk(void* threadData)
  226. {
  227. HeightmapThreadData* data = (HeightmapThreadData*)threadData;
  228. Vector3 rayOrigin(0, data->rayHeight, 0);
  229. const Vector3& rayDirection = *data->rayDirection;
  230. const std::vector<Mesh*>& meshes = *data->meshes;
  231. float* heights = data->heights;
  232. Vector3 intersectionPoint;
  233. float minHeight = FLT_MAX;
  234. float maxHeight = -FLT_MAX;
  235. int index = data->heightIndex;
  236. int zi = 0;
  237. for (float z = data->minZ; zi < data->height; z += data->stepZ, ++zi)
  238. {
  239. LOG(1, "\r\t%d%%", (int)(((float)__processedHeightmapScanLines / __totalHeightmapScanlines) * 100.0f));
  240. rayOrigin.z = z;
  241. int xi = 0;
  242. for (float x = data->minX; xi < data->width; x += data->stepX, ++xi)
  243. {
  244. float h = -FLT_MAX;
  245. rayOrigin.x = x;
  246. for (unsigned int i = 0, count = meshes.size(); i < count; ++i)
  247. {
  248. // Pick the highest intersecting Y value of all meshes
  249. Mesh* mesh = meshes[i];
  250. // Perform a quick ray/bounding box test to quick-out
  251. if (!intersect(rayOrigin, rayDirection, mesh->bounds.min, mesh->bounds.max))
  252. continue;
  253. // Compute the intersection point of ray with mesh
  254. if (intersect(rayOrigin, rayDirection, mesh->vertices, mesh->parts, &intersectionPoint))
  255. {
  256. if (intersectionPoint.y > h)
  257. {
  258. h = intersectionPoint.y;
  259. // Update min/max height values
  260. if (h < minHeight)
  261. minHeight = h;
  262. if (h > maxHeight)
  263. maxHeight = h;
  264. }
  265. }
  266. }
  267. // Update the glboal height array
  268. heights[index++] = h;
  269. if (h == -FLT_MAX)
  270. ++__failedRayCasts;
  271. }
  272. ++__processedHeightmapScanLines;
  273. }
  274. // Update min/max height for this thread data
  275. data->minHeight = minHeight;
  276. data->maxHeight = maxHeight;
  277. return 0;
  278. }
  279. /////////////////////////////////////////////////////////////
  280. //
  281. // Fast, Minimum Storage Ray-Triangle Intersection
  282. //
  283. // Authors: Tomas Möller, Ben Trumbore
  284. // http://jgt.akpeters.com/papers/MollerTrumbore97
  285. //
  286. // Implementation of algorithm from Real-Time Rendering (vol 1), pg. 305.
  287. //
  288. // Adapted slightly for use here.
  289. //
  290. #ifndef EPSILON
  291. #define EPSILON 0.000001
  292. #endif
  293. #define CROSS(dest,v1,v2) \
  294. dest[0]=v1[1]*v2[2]-v1[2]*v2[1]; \
  295. dest[1]=v1[2]*v2[0]-v1[0]*v2[2]; \
  296. dest[2]=v1[0]*v2[1]-v1[1]*v2[0];
  297. #define DOT(v1,v2) (v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2])
  298. #define SUB(dest,v1,v2) \
  299. dest[0]=v1[0]-v2[0]; \
  300. dest[1]=v1[1]-v2[1]; \
  301. dest[2]=v1[2]-v2[2];
  302. int intersect_triangle(const float orig[3], const float dir[3], const float vert0[3], const float vert1[3], const float vert2[3], float *t, float *u, float *v)
  303. {
  304. float edge1[3], edge2[3], tvec[3], pvec[3], qvec[3];
  305. float det,inv_det;
  306. /* find vectors for two edges sharing vert0 */
  307. SUB(edge1, vert1, vert0);
  308. SUB(edge2, vert2, vert0);
  309. /* begin calculating determinant - also used to calculate U parameter */
  310. CROSS(pvec, dir, edge2);
  311. /* if determinant is near zero, ray lies in plane of triangle */
  312. det = DOT(edge1, pvec);
  313. if (det > -EPSILON && det < EPSILON)
  314. return 0;
  315. inv_det = 1.0f / det;
  316. /* calculate distance from vert0 to ray origin */
  317. SUB(tvec, orig, vert0);
  318. /* calculate U parameter and test bounds */
  319. *u = DOT(tvec, pvec) * inv_det;
  320. if (*u < 0.0 || *u > 1.0)
  321. return 0;
  322. /* prepare to test V parameter */
  323. CROSS(qvec, tvec, edge1);
  324. /* calculate V parameter and test bounds */
  325. *v = DOT(dir, qvec) * inv_det;
  326. if (*v < 0.0 || *u + *v > 1.0)
  327. return 0;
  328. /* calculate t, ray intersects triangle */
  329. *t = DOT(edge2, qvec) * inv_det;
  330. return 1;
  331. }
  332. // Performs an intersection test between a ray and the given mesh part and stores the result in "point".
  333. bool intersect(const Vector3& rayOrigin, const Vector3& rayDirection, const std::vector<Vertex>& vertices, const std::vector<MeshPart*>& parts, Vector3* point)
  334. {
  335. const float* orig = &rayOrigin.x;
  336. const float* dir = &rayDirection.x;
  337. float minT = FLT_MAX;
  338. for (unsigned int i = 0, partCount = parts.size(); i < partCount; ++i)
  339. {
  340. MeshPart* part = parts[i];
  341. for (unsigned int j = 0, indexCount = part->getIndicesCount(); j < indexCount; j += 3)
  342. {
  343. const float* v0 = &vertices[part->getIndex( j )].position.x;
  344. const float* v1 = &vertices[part->getIndex(j+1)].position.x;
  345. const float* v2 = &vertices[part->getIndex(j+2)].position.x;
  346. // Perform a quick check (in 2D) to determine if the point is definitely NOT in the triangle
  347. float xmin, xmax, zmin, zmax;
  348. xmin = v0[0] < v1[0] ? v0[0] : v1[0]; xmin = xmin < v2[0] ? xmin : v2[0];
  349. xmax = v0[0] > v1[0] ? v0[0] : v1[0]; xmax = xmax > v2[0] ? xmax : v2[0];
  350. zmin = v0[2] < v1[2] ? v0[2] : v1[2]; zmin = zmin < v2[2] ? zmin : v2[2];
  351. zmax = v0[2] > v1[2] ? v0[2] : v1[2]; zmax = zmax > v2[2] ? zmax : v2[2];
  352. if (orig[0] < xmin || orig[0] > xmax || orig[2] < zmin || orig[2] > zmax)
  353. continue;
  354. // Perform a full ray/traingle intersection test in 3D to get the intersection point
  355. float t, u, v;
  356. if (intersect_triangle(orig, dir, v0, v1, v2, &t, &u, &v))
  357. {
  358. // Found an intersection!
  359. if (t < minT)
  360. {
  361. minT = t;
  362. if (point)
  363. {
  364. Vector3 rd(rayDirection);
  365. rd.scale(t);
  366. Vector3::add(rayOrigin, rd, point);
  367. }
  368. }
  369. //return true;
  370. }
  371. }
  372. }
  373. return (minT != FLT_MAX);//false;
  374. }
  375. // Ray/Box intersection test.
  376. bool intersect(const Vector3& rayOrigin, const Vector3& rayDirection, const Vector3& boxMin, const Vector3& boxMax, float* distance)
  377. {
  378. const Vector3& origin = rayOrigin;
  379. const Vector3& direction = rayDirection;
  380. const Vector3& min = boxMin;
  381. const Vector3& max = boxMax;
  382. // Intermediate calculation variables.
  383. float dnear = 0.0f;
  384. float dfar = 0.0f;
  385. float tmin = 0.0f;
  386. float tmax = 0.0f;
  387. // X direction.
  388. float div = 1.0f / direction.x;
  389. if (div >= 0.0f)
  390. {
  391. tmin = (min.x - origin.x) * div;
  392. tmax = (max.x - origin.x) * div;
  393. }
  394. else
  395. {
  396. tmin = (max.x - origin.x) * div;
  397. tmax = (min.x - origin.x) * div;
  398. }
  399. dnear = tmin;
  400. dfar = tmax;
  401. // Check if the ray misses the box.
  402. if (dnear > dfar || dfar < 0.0f)
  403. {
  404. return false;
  405. }
  406. // Y direction.
  407. div = 1.0f / direction.y;
  408. if (div >= 0.0f)
  409. {
  410. tmin = (min.y - origin.y) * div;
  411. tmax = (max.y - origin.y) * div;
  412. }
  413. else
  414. {
  415. tmin = (max.y - origin.y) * div;
  416. tmax = (min.y - origin.y) * div;
  417. }
  418. // Update the near and far intersection distances.
  419. if (tmin > dnear)
  420. {
  421. dnear = tmin;
  422. }
  423. if (tmax < dfar)
  424. {
  425. dfar = tmax;
  426. }
  427. // Check if the ray misses the box.
  428. if (dnear > dfar || dfar < 0.0f)
  429. {
  430. return false;
  431. }
  432. // Z direction.
  433. div = 1.0f / direction.z;
  434. if (div >= 0.0f)
  435. {
  436. tmin = (min.z - origin.z) * div;
  437. tmax = (max.z - origin.z) * div;
  438. }
  439. else
  440. {
  441. tmin = (max.z - origin.z) * div;
  442. tmax = (min.z - origin.z) * div;
  443. }
  444. // Update the near and far intersection distances.
  445. if (tmin > dnear)
  446. {
  447. dnear = tmin;
  448. }
  449. if (tmax < dfar)
  450. {
  451. dfar = tmax;
  452. }
  453. // Check if the ray misses the box.
  454. if (dnear > dfar || dfar < 0.0f)
  455. {
  456. return false;
  457. }
  458. // The ray intersects the box
  459. if (distance)
  460. *distance = dnear;
  461. return true;
  462. }
  463. }