Heightmap.cpp 17 KB

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