Debian Codegraph @

Recast/Source/RecastRasterization.cpp

raw ◀ ▶
1 Debian patch touch this file
1 //
2 // Copyright (c) 2009-2010 Mikko Mononen [email protected]
3 //
4 // This software is provided 'as-is', without any express or implied
5 // warranty. In no event will the authors be held liable for any damages
6 // arising from the use of this software.
7 // Permission is granted to anyone to use this software for any purpose,
8 // including commercial applications, and to alter it and redistribute it
9 // freely, subject to the following restrictions:
10 // 1. The origin of this software must not be misrepresented; you must not
11 // claim that you wrote the original software. If you use this software
12 // in a product, an acknowledgment in the product documentation would be
13 // appreciated but is not required.
14 // 2. Altered source versions must be plainly marked as such, and must not be
15 // misrepresented as being the original software.
16 // 3. This notice may not be removed or altered from any source distribution.
17 //
18
19 #include <math.h>
20 #include "Recast.h"
21 #include "RecastAlloc.h"
22 #include "RecastAssert.h"
23
24 /// Check whether two bounding boxes overlap
25 ///
26 /// @param[in] aMin Min axis extents of bounding box A
27 /// @param[in] aMax Max axis extents of bounding box A
28 /// @param[in] bMin Min axis extents of bounding box B
29 /// @param[in] bMax Max axis extents of bounding box B
30 /// @returns true if the two bounding boxes overlap. False otherwise.
31 static bool overlapBounds(const float* aMin, const float* aMax, const float* bMin, const float* bMax)
32 {
33 return
34 aMin[0] <= bMax[0] && aMax[0] >= bMin[0] &&
35 aMin[1] <= bMax[1] && aMax[1] >= bMin[1] &&
36 aMin[2] <= bMax[2] && aMax[2] >= bMin[2];
37 }
38
39 /// Allocates a new span in the heightfield.
40 /// Use a memory pool and free list to minimize actual allocations.
41 ///
•42 /// @param[in] heightfield The heightfield
43 /// @returns A pointer to the allocated or re-used span memory.
•44 static rcSpan* allocSpan(rcHeightfield& heightfield)
45 {
46 // If necessary, allocate new page and update the freelist.
•47 if (heightfield.freelist == NULL || heightfield.freelist->next == NULL)
48 {
49 // Create new page.
50 // Allocate memory for the new pool.
51 rcSpanPool* spanPool = (rcSpanPool*)rcAlloc(sizeof(rcSpanPool), RC_ALLOC_PERM);
52 if (spanPool == NULL)
53 {
54 return NULL;
55 }
56
57 // Add the pool into the list of pools.
•58 spanPool->next = heightfield.pools;
59 heightfield.pools = spanPool;
60
61 // Add new spans to the free list.
•62 rcSpan* freeList = heightfield.freelist;
63 rcSpan* head = &spanPool->items[0];
64 rcSpan* it = &spanPool->items[RC_SPANS_PER_POOL];
65 do
66 {
67 --it;
68 it->next = freeList;
69 freeList = it;
70 }
71 while (it != head);
•72 heightfield.freelist = it;
73 }
74
75 // Pop item from the front of the free list.
•76 rcSpan* newSpan = heightfield.freelist;
77 heightfield.freelist = heightfield.freelist->next;
78 return newSpan;
79 }
80
81 /// Releases the memory used by the span back to the heightfield, so it can be re-used for new spans.
•82 /// @param[in] heightfield The heightfield.
83 /// @param[in] span A pointer to the span to free
•84 static void freeSpan(rcHeightfield& heightfield, rcSpan* span)
85 {
86 if (span == NULL)
87 {
88 return;
89 }
90 // Add the span to the front of the free list.
•91 span->next = heightfield.freelist;
92 heightfield.freelist = span;
93 }
94
95 /// Adds a span to the heightfield. If the new span overlaps existing spans,
96 /// it will merge the new span with the existing ones.
97 ///
•98 /// @param[in] heightfield Heightfield to add spans to
99 /// @param[in] x The new span's column cell x index
100 /// @param[in] z The new span's column cell z index
101 /// @param[in] min The new span's minimum cell index
102 /// @param[in] max The new span's maximum cell index
103 /// @param[in] areaID The new span's area type ID
104 /// @param[in] flagMergeThreshold How close two spans maximum extents need to be to merge area type IDs
•105 static bool addSpan(rcHeightfield& heightfield,
106 const int x, const int z,
107 const unsigned short min, const unsigned short max,
108 const unsigned char areaID, const int flagMergeThreshold)
109 {
110 // Create the new span.
•111 rcSpan* newSpan = allocSpan(heightfield);
112 if (newSpan == NULL)
113 {
114 return false;
115 }
116 newSpan->smin = min;
117 newSpan->smax = max;
118 newSpan->area = areaID;
119 newSpan->next = NULL;
120
•121 const int columnIndex = x + z * heightfield.width;
122 rcSpan* previousSpan = NULL;
•123 rcSpan* currentSpan = heightfield.spans[columnIndex];
124
125 // Insert the new span, possibly merging it with existing spans.
126 while (currentSpan != NULL)
127 {
128 if (currentSpan->smin > newSpan->smax)
129 {
130 // Current span is completely after the new span, break.
131 break;
132 }
133
134 if (currentSpan->smax < newSpan->smin)
135 {
136 // Current span is completely before the new span. Keep going.
137 previousSpan = currentSpan;
138 currentSpan = currentSpan->next;
139 }
140 else
141 {
142 // The new span overlaps with an existing span. Merge them.
143 if (currentSpan->smin < newSpan->smin)
144 {
145 newSpan->smin = currentSpan->smin;
146 }
147 if (currentSpan->smax > newSpan->smax)
148 {
149 newSpan->smax = currentSpan->smax;
150 }
151
152 // Merge flags.
153 if (rcAbs((int)newSpan->smax - (int)currentSpan->smax) <= flagMergeThreshold)
154 {
155 // Higher area ID numbers indicate higher resolution priority.
156 newSpan->area = rcMax(newSpan->area, currentSpan->area);
157 }
158
159 // Remove the current span since it's now merged with newSpan.
160 // Keep going because there might be other overlapping spans that also need to be merged.
161 rcSpan* next = currentSpan->next;
•162 freeSpan(heightfield, currentSpan);
163 if (previousSpan)
164 {
165 previousSpan->next = next;
166 }
167 else
168 {
•169 heightfield.spans[columnIndex] = next;
170 }
171 currentSpan = next;
172 }
173 }
174
175 // Insert new span after prev
176 if (previousSpan != NULL)
177 {
178 newSpan->next = previousSpan->next;
179 previousSpan->next = newSpan;
180 }
181 else
182 {
183 // This span should go before the others in the list
•184 newSpan->next = heightfield.spans[columnIndex];
185 heightfield.spans[columnIndex] = newSpan;
186 }
187
188 return true;
189 }
190
191 bool rcAddSpan(rcContext* context, rcHeightfield& heightfield,
192 const int x, const int z,
193 const unsigned short spanMin, const unsigned short spanMax,
194 const unsigned char areaID, const int flagMergeThreshold)
195 {
196 rcAssert(context);
197
198 if (!addSpan(heightfield, x, z, spanMin, spanMax, areaID, flagMergeThreshold))
199 {
200 context->log(RC_LOG_ERROR, "rcAddSpan: Out of memory.");
201 return false;
202 }
203
204 return true;
205 }
206
207 enum rcAxis
208 {
209 RC_AXIS_X = 0,
210 RC_AXIS_Y = 1,
211 RC_AXIS_Z = 2
212 };
213
214 /// Divides a convex polygon of max 12 vertices into two convex polygons
215 /// across a separating axis.
216 ///
217 /// @param[in] inVerts The input polygon vertices
218 /// @param[in] inVertsCount The number of input polygon vertices
219 /// @param[out] outVerts1 Resulting polygon 1's vertices
220 /// @param[out] outVerts1Count The number of resulting polygon 1 vertices
221 /// @param[out] outVerts2 Resulting polygon 2's vertices
222 /// @param[out] outVerts2Count The number of resulting polygon 2 vertices
223 /// @param[in] axisOffset THe offset along the specified axis
224 /// @param[in] axis The separating axis
225 static void dividePoly(const float* inVerts, int inVertsCount,
226 float* outVerts1, int* outVerts1Count,
227 float* outVerts2, int* outVerts2Count,
228 float axisOffset, rcAxis axis)
229 {
230 rcAssert(inVertsCount <= 12);
231
232 // How far positive or negative away from the separating axis is each vertex.
233 float inVertAxisDelta[12];
234 for (int inVert = 0; inVert < inVertsCount; ++inVert)
235 {
236 inVertAxisDelta[inVert] = axisOffset - inVerts[inVert * 3 + axis];
237 }
238
239 int poly1Vert = 0;
240 int poly2Vert = 0;
241 for (int inVertA = 0, inVertB = inVertsCount - 1; inVertA < inVertsCount; inVertB = inVertA, ++inVertA)
242 {
243 // If the two vertices are on the same side of the separating axis
244 bool sameSide = (inVertAxisDelta[inVertA] >= 0) == (inVertAxisDelta[inVertB] >= 0);
245
246 if (!sameSide)
247 {
248 float s = inVertAxisDelta[inVertB] / (inVertAxisDelta[inVertB] - inVertAxisDelta[inVertA]);
249 outVerts1[poly1Vert * 3 + 0] = inVerts[inVertB * 3 + 0] + (inVerts[inVertA * 3 + 0] - inVerts[inVertB * 3 + 0]) * s;
250 outVerts1[poly1Vert * 3 + 1] = inVerts[inVertB * 3 + 1] + (inVerts[inVertA * 3 + 1] - inVerts[inVertB * 3 + 1]) * s;
251 outVerts1[poly1Vert * 3 + 2] = inVerts[inVertB * 3 + 2] + (inVerts[inVertA * 3 + 2] - inVerts[inVertB * 3 + 2]) * s;
252 rcVcopy(&outVerts2[poly2Vert * 3], &outVerts1[poly1Vert * 3]);
253 poly1Vert++;
254 poly2Vert++;
255
256 // add the inVertA point to the right polygon. Do NOT add points that are on the dividing line
257 // since these were already added above
258 if (inVertAxisDelta[inVertA] > 0)
259 {
260 rcVcopy(&outVerts1[poly1Vert * 3], &inVerts[inVertA * 3]);
261 poly1Vert++;
262 }
263 else if (inVertAxisDelta[inVertA] < 0)
264 {
265 rcVcopy(&outVerts2[poly2Vert * 3], &inVerts[inVertA * 3]);
266 poly2Vert++;
267 }
268 }
269 else
270 {
271 // add the inVertA point to the right polygon. Addition is done even for points on the dividing line
272 if (inVertAxisDelta[inVertA] >= 0)
273 {
274 rcVcopy(&outVerts1[poly1Vert * 3], &inVerts[inVertA * 3]);
275 poly1Vert++;
276 if (inVertAxisDelta[inVertA] != 0)
277 {
278 continue;
279 }
280 }
281 rcVcopy(&outVerts2[poly2Vert * 3], &inVerts[inVertA * 3]);
282 poly2Vert++;
283 }
284 }
285
286 *outVerts1Count = poly1Vert;
287 *outVerts2Count = poly2Vert;
288 }
289
290 /// Rasterize a single triangle to the heightfield.
291 ///
292 /// This code is extremely hot, so much care should be given to maintaining maximum perf here.
293 ///
294 /// @param[in] v0 Triangle vertex 0
295 /// @param[in] v1 Triangle vertex 1
296 /// @param[in] v2 Triangle vertex 2
297 /// @param[in] areaID The area ID to assign to the rasterized spans
•298 /// @param[in] heightfield Heightfield to rasterize into
299 /// @param[in] heightfieldBBMin The min extents of the heightfield bounding box
300 /// @param[in] heightfieldBBMax The max extents of the heightfield bounding box
301 /// @param[in] cellSize The x and z axis size of a voxel in the heightfield
302 /// @param[in] inverseCellSize 1 / cellSize
303 /// @param[in] inverseCellHeight 1 / cellHeight
304 /// @param[in] flagMergeThreshold The threshold in which area flags will be merged
305 /// @returns true if the operation completes successfully. false if there was an error adding spans to the heightfield.
306 static bool rasterizeTri(const float* v0, const float* v1, const float* v2,
•307 const unsigned char areaID, rcHeightfield& heightfield,
308 const float* heightfieldBBMin, const float* heightfieldBBMax,
309 const float cellSize, const float inverseCellSize, const float inverseCellHeight,
310 const int flagMergeThreshold)
311 {
312 // Calculate the bounding box of the triangle.
313 float triBBMin[3];
314 rcVcopy(triBBMin, v0);
315 rcVmin(triBBMin, v1);
316 rcVmin(triBBMin, v2);
317
318 float triBBMax[3];
319 rcVcopy(triBBMax, v0);
320 rcVmax(triBBMax, v1);
321 rcVmax(triBBMax, v2);
322
323 // If the triangle does not touch the bounding box of the heightfield, skip the triangle.
•324 if (!overlapBounds(triBBMin, triBBMax, heightfieldBBMin, heightfieldBBMax))
325 {
326 return true;
327 }
328
•329 const int w = heightfield.width;
330 const int h = heightfield.height;
331 const float by = heightfieldBBMax[1] - heightfieldBBMin[1];
332
333 // Calculate the footprint of the triangle on the grid's z-axis
•334 int z0 = (int)((triBBMin[2] - heightfieldBBMin[2]) * inverseCellSize);
335 int z1 = (int)((triBBMax[2] - heightfieldBBMin[2]) * inverseCellSize);
336
337 // use -1 rather than 0 to cut the polygon properly at the start of the tile
338 z0 = rcClamp(z0, -1, h - 1);
339 z1 = rcClamp(z1, 0, h - 1);
340
341 // Clip the triangle into all grid cells it touches.
342 float buf[7 * 3 * 4];
343 float* in = buf;
344 float* inRow = buf + 7 * 3;
345 float* p1 = inRow + 7 * 3;
346 float* p2 = p1 + 7 * 3;
347
348 rcVcopy(&in[0], v0);
349 rcVcopy(&in[1 * 3], v1);
350 rcVcopy(&in[2 * 3], v2);
351 int nvRow;
352 int nvIn = 3;
353
354 for (int z = z0; z <= z1; ++z)
355 {
356 // Clip polygon to row. Store the remaining polygon as well
•357 const float cellZ = heightfieldBBMin[2] + (float)z * cellSize;
358 dividePoly(in, nvIn, inRow, &nvRow, p1, &nvIn, cellZ + cellSize, RC_AXIS_Z);
359 rcSwap(in, p1);
360
361 if (nvRow < 3)
362 {
363 continue;
364 }
365 if (z < 0)
366 {
367 continue;
368 }
369
370 // find X-axis bounds of the row
371 float minX = inRow[0];
372 float maxX = inRow[0];
373 for (int vert = 1; vert < nvRow; ++vert)
374 {
375 if (minX > inRow[vert * 3])
376 {
377 minX = inRow[vert * 3];
378 }
379 if (maxX < inRow[vert * 3])
380 {
381 maxX = inRow[vert * 3];
382 }
383 }
•384 int x0 = (int)((minX - heightfieldBBMin[0]) * inverseCellSize);
385 int x1 = (int)((maxX - heightfieldBBMin[0]) * inverseCellSize);
386 if (x1 < 0 || x0 >= w)
387 {
388 continue;
389 }
390 x0 = rcClamp(x0, -1, w - 1);
391 x1 = rcClamp(x1, 0, w - 1);
392
393 int nv;
394 int nv2 = nvRow;
395
396 for (int x = x0; x <= x1; ++x)
397 {
398 // Clip polygon to column. store the remaining polygon as well
•399 const float cx = heightfieldBBMin[0] + (float)x * cellSize;
400 dividePoly(inRow, nv2, p1, &nv, p2, &nv2, cx + cellSize, RC_AXIS_X);
401 rcSwap(inRow, p2);
402
403 if (nv < 3)
404 {
405 continue;
406 }
407 if (x < 0)
408 {
409 continue;
410 }
411
412 // Calculate min and max of the span.
413 float spanMin = p1[1];
414 float spanMax = p1[1];
415 for (int vert = 1; vert < nv; ++vert)
416 {
417 spanMin = rcMin(spanMin, p1[vert * 3 + 1]);
418 spanMax = rcMax(spanMax, p1[vert * 3 + 1]);
419 }
•420 spanMin -= heightfieldBBMin[1];
421 spanMax -= heightfieldBBMin[1];
422
423 // Skip the span if it's completely outside the heightfield bounding box
424 if (spanMax < 0.0f)
425 {
426 continue;
427 }
428 if (spanMin > by)
429 {
430 continue;
431 }
432
433 // Clamp the span to the heightfield bounding box.
434 if (spanMin < 0.0f)
435 {
436 spanMin = 0;
437 }
438 if (spanMax > by)
439 {
440 spanMax = by;
441 }
442
443 // Snap the span to the heightfield height grid.
444 unsigned short spanMinCellIndex = (unsigned short)rcClamp((int)floorf(spanMin * inverseCellHeight), 0, RC_SPAN_MAX_HEIGHT);
445 unsigned short spanMaxCellIndex = (unsigned short)rcClamp((int)ceilf(spanMax * inverseCellHeight), (int)spanMinCellIndex + 1, RC_SPAN_MAX_HEIGHT);
446
•447 if (!addSpan(heightfield, x, z, spanMinCellIndex, spanMaxCellIndex, areaID, flagMergeThreshold))
448 {
449 return false;
450 }
451 }
452 }
453
454 return true;
455 }
456
457 bool rcRasterizeTriangle(rcContext* context,
458 const float* v0, const float* v1, const float* v2,
459 const unsigned char areaID, rcHeightfield& heightfield, const int flagMergeThreshold)
460 {
461 rcAssert(context != NULL);
462
463 rcScopedTimer timer(context, RC_TIMER_RASTERIZE_TRIANGLES);
464
465 // Rasterize the single triangle.
466 const float inverseCellSize = 1.0f / heightfield.cs;
467 const float inverseCellHeight = 1.0f / heightfield.ch;
468 if (!rasterizeTri(v0, v1, v2, areaID, heightfield, heightfield.bmin, heightfield.bmax, heightfield.cs, inverseCellSize, inverseCellHeight, flagMergeThreshold))
469 {
470 context->log(RC_LOG_ERROR, "rcRasterizeTriangle: Out of memory.");
471 return false;
472 }
473
474 return true;
475 }
476
477 bool rcRasterizeTriangles(rcContext* context,
478 const float* verts, const int /*nv*/,
479 const int* tris, const unsigned char* triAreaIDs, const int numTris,
480 rcHeightfield& heightfield, const int flagMergeThreshold)
481 {
482 rcAssert(context != NULL);
483
484 rcScopedTimer timer(context, RC_TIMER_RASTERIZE_TRIANGLES);
485
486 // Rasterize the triangles.
487 const float inverseCellSize = 1.0f / heightfield.cs;
488 const float inverseCellHeight = 1.0f / heightfield.ch;
489 for (int triIndex = 0; triIndex < numTris; ++triIndex)
490 {
491 const float* v0 = &verts[tris[triIndex * 3 + 0] * 3];
492 const float* v1 = &verts[tris[triIndex * 3 + 1] * 3];
493 const float* v2 = &verts[tris[triIndex * 3 + 2] * 3];
494 if (!rasterizeTri(v0, v1, v2, triAreaIDs[triIndex], heightfield, heightfield.bmin, heightfield.bmax, heightfield.cs, inverseCellSize, inverseCellHeight, flagMergeThreshold))
495 {
496 context->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory.");
497 return false;
498 }
499 }
500
501 return true;
502 }
503
504 bool rcRasterizeTriangles(rcContext* context,
505 const float* verts, const int /*nv*/,
506 const unsigned short* tris, const unsigned char* triAreaIDs, const int numTris,
507 rcHeightfield& heightfield, const int flagMergeThreshold)
508 {
509 rcAssert(context != NULL);
510
511 rcScopedTimer timer(context, RC_TIMER_RASTERIZE_TRIANGLES);
512
513 // Rasterize the triangles.
514 const float inverseCellSize = 1.0f / heightfield.cs;
515 const float inverseCellHeight = 1.0f / heightfield.ch;
516 for (int triIndex = 0; triIndex < numTris; ++triIndex)
517 {
518 const float* v0 = &verts[tris[triIndex * 3 + 0] * 3];
519 const float* v1 = &verts[tris[triIndex * 3 + 1] * 3];
520 const float* v2 = &verts[tris[triIndex * 3 + 2] * 3];
521 if (!rasterizeTri(v0, v1, v2, triAreaIDs[triIndex], heightfield, heightfield.bmin, heightfield.bmax, heightfield.cs, inverseCellSize, inverseCellHeight, flagMergeThreshold))
522 {
523 context->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory.");
524 return false;
525 }
526 }
527
528 return true;
529 }
530
531 bool rcRasterizeTriangles(rcContext* context,
532 const float* verts, const unsigned char* triAreaIDs, const int numTris,
533 rcHeightfield& heightfield, const int flagMergeThreshold)
534 {
535 rcAssert(context != NULL);
536
537 rcScopedTimer timer(context, RC_TIMER_RASTERIZE_TRIANGLES);
538
539 // Rasterize the triangles.
540 const float inverseCellSize = 1.0f / heightfield.cs;
541 const float inverseCellHeight = 1.0f / heightfield.ch;
542 for (int triIndex = 0; triIndex < numTris; ++triIndex)
543 {
544 const float* v0 = &verts[(triIndex * 3 + 0) * 3];
545 const float* v1 = &verts[(triIndex * 3 + 1) * 3];
546 const float* v2 = &verts[(triIndex * 3 + 2) * 3];
547 if (!rasterizeTri(v0, v1, v2, triAreaIDs[triIndex], heightfield, heightfield.bmin, heightfield.bmax, heightfield.cs, inverseCellSize, inverseCellHeight, flagMergeThreshold))
548 {
549 context->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory.");
550 return false;
551 }
552 }
553
554 return true;
555 }