1/* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#define LOG_TAG "OpenGLRenderer" 18 19// The highest z value can't be higher than (CASTER_Z_CAP_RATIO * light.z) 20#define CASTER_Z_CAP_RATIO 0.95f 21 22// When there is no umbra, then just fake the umbra using 23// centroid * (1 - FAKE_UMBRA_SIZE_RATIO) + outline * FAKE_UMBRA_SIZE_RATIO 24#define FAKE_UMBRA_SIZE_RATIO 0.05f 25 26// When the polygon is about 90 vertices, the penumbra + umbra can reach 270 rays. 27// That is consider pretty fine tessllated polygon so far. 28// This is just to prevent using too much some memory when edge slicing is not 29// needed any more. 30#define FINE_TESSELLATED_POLYGON_RAY_NUMBER 270 31/** 32 * Extra vertices for the corner for smoother corner. 33 * Only for outer loop. 34 * Note that we use such extra memory to avoid an extra loop. 35 */ 36// For half circle, we could add EXTRA_VERTEX_PER_PI vertices. 37// Set to 1 if we don't want to have any. 38#define SPOT_EXTRA_CORNER_VERTEX_PER_PI 18 39 40// For the whole polygon, the sum of all the deltas b/t normals is 2 * M_PI, 41// therefore, the maximum number of extra vertices will be twice bigger. 42#define SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER (2 * SPOT_EXTRA_CORNER_VERTEX_PER_PI) 43 44// For each RADIANS_DIVISOR, we would allocate one more vertex b/t the normals. 45#define SPOT_CORNER_RADIANS_DIVISOR (M_PI / SPOT_EXTRA_CORNER_VERTEX_PER_PI) 46 47// For performance, we use (1 - alpha) value for the shader input. 48#define TRANSFORMED_PENUMBRA_ALPHA 1.0f 49#define TRANSFORMED_UMBRA_ALPHA 0.0f 50 51#include <algorithm> 52#include <math.h> 53#include <stdlib.h> 54#include <utils/Log.h> 55 56#include "ShadowTessellator.h" 57#include "SpotShadow.h" 58#include "Vertex.h" 59#include "VertexBuffer.h" 60#include "utils/MathUtils.h" 61 62// TODO: After we settle down the new algorithm, we can remove the old one and 63// its utility functions. 64// Right now, we still need to keep it for comparison purpose and future expansion. 65namespace android { 66namespace uirenderer { 67 68static const float EPSILON = 1e-7; 69 70/** 71 * For each polygon's vertex, the light center will project it to the receiver 72 * as one of the outline vertex. 73 * For each outline vertex, we need to store the position and normal. 74 * Normal here is defined against the edge by the current vertex and the next vertex. 75 */ 76struct OutlineData { 77 Vector2 position; 78 Vector2 normal; 79 float radius; 80}; 81 82/** 83 * For each vertex, we need to keep track of its angle, whether it is penumbra or 84 * umbra, and its corresponding vertex index. 85 */ 86struct SpotShadow::VertexAngleData { 87 // The angle to the vertex from the centroid. 88 float mAngle; 89 // True is the vertex comes from penumbra, otherwise it comes from umbra. 90 bool mIsPenumbra; 91 // The index of the vertex described by this data. 92 int mVertexIndex; 93 void set(float angle, bool isPenumbra, int index) { 94 mAngle = angle; 95 mIsPenumbra = isPenumbra; 96 mVertexIndex = index; 97 } 98}; 99 100/** 101 * Calculate the angle between and x and a y coordinate. 102 * The atan2 range from -PI to PI. 103 */ 104static float angle(const Vector2& point, const Vector2& center) { 105 return atan2(point.y - center.y, point.x - center.x); 106} 107 108/** 109 * Calculate the intersection of a ray with the line segment defined by two points. 110 * 111 * Returns a negative value in error conditions. 112 113 * @param rayOrigin The start of the ray 114 * @param dx The x vector of the ray 115 * @param dy The y vector of the ray 116 * @param p1 The first point defining the line segment 117 * @param p2 The second point defining the line segment 118 * @return The distance along the ray if it intersects with the line segment, negative if otherwise 119 */ 120static float rayIntersectPoints(const Vector2& rayOrigin, float dx, float dy, 121 const Vector2& p1, const Vector2& p2) { 122 // The math below is derived from solving this formula, basically the 123 // intersection point should stay on both the ray and the edge of (p1, p2). 124 // solve([p1x+t*(p2x-p1x)=dx*t2+px,p1y+t*(p2y-p1y)=dy*t2+py],[t,t2]); 125 126 float divisor = (dx * (p1.y - p2.y) + dy * p2.x - dy * p1.x); 127 if (divisor == 0) return -1.0f; // error, invalid divisor 128 129#if DEBUG_SHADOW 130 float interpVal = (dx * (p1.y - rayOrigin.y) + dy * rayOrigin.x - dy * p1.x) / divisor; 131 if (interpVal < 0 || interpVal > 1) { 132 ALOGW("rayIntersectPoints is hitting outside the segment %f", interpVal); 133 } 134#endif 135 136 float distance = (p1.x * (rayOrigin.y - p2.y) + p2.x * (p1.y - rayOrigin.y) + 137 rayOrigin.x * (p2.y - p1.y)) / divisor; 138 139 return distance; // may be negative in error cases 140} 141 142/** 143 * Sort points by their X coordinates 144 * 145 * @param points the points as a Vector2 array. 146 * @param pointsLength the number of vertices of the polygon. 147 */ 148void SpotShadow::xsort(Vector2* points, int pointsLength) { 149 auto cmp = [](const Vector2& a, const Vector2& b) -> bool { 150 return a.x < b.x; 151 }; 152 std::sort(points, points + pointsLength, cmp); 153} 154 155/** 156 * compute the convex hull of a collection of Points 157 * 158 * @param points the points as a Vector2 array. 159 * @param pointsLength the number of vertices of the polygon. 160 * @param retPoly pre allocated array of floats to put the vertices 161 * @return the number of points in the polygon 0 if no intersection 162 */ 163int SpotShadow::hull(Vector2* points, int pointsLength, Vector2* retPoly) { 164 xsort(points, pointsLength); 165 int n = pointsLength; 166 Vector2 lUpper[n]; 167 lUpper[0] = points[0]; 168 lUpper[1] = points[1]; 169 170 int lUpperSize = 2; 171 172 for (int i = 2; i < n; i++) { 173 lUpper[lUpperSize] = points[i]; 174 lUpperSize++; 175 176 while (lUpperSize > 2 && !ccw( 177 lUpper[lUpperSize - 3].x, lUpper[lUpperSize - 3].y, 178 lUpper[lUpperSize - 2].x, lUpper[lUpperSize - 2].y, 179 lUpper[lUpperSize - 1].x, lUpper[lUpperSize - 1].y)) { 180 // Remove the middle point of the three last 181 lUpper[lUpperSize - 2].x = lUpper[lUpperSize - 1].x; 182 lUpper[lUpperSize - 2].y = lUpper[lUpperSize - 1].y; 183 lUpperSize--; 184 } 185 } 186 187 Vector2 lLower[n]; 188 lLower[0] = points[n - 1]; 189 lLower[1] = points[n - 2]; 190 191 int lLowerSize = 2; 192 193 for (int i = n - 3; i >= 0; i--) { 194 lLower[lLowerSize] = points[i]; 195 lLowerSize++; 196 197 while (lLowerSize > 2 && !ccw( 198 lLower[lLowerSize - 3].x, lLower[lLowerSize - 3].y, 199 lLower[lLowerSize - 2].x, lLower[lLowerSize - 2].y, 200 lLower[lLowerSize - 1].x, lLower[lLowerSize - 1].y)) { 201 // Remove the middle point of the three last 202 lLower[lLowerSize - 2] = lLower[lLowerSize - 1]; 203 lLowerSize--; 204 } 205 } 206 207 // output points in CW ordering 208 const int total = lUpperSize + lLowerSize - 2; 209 int outIndex = total - 1; 210 for (int i = 0; i < lUpperSize; i++) { 211 retPoly[outIndex] = lUpper[i]; 212 outIndex--; 213 } 214 215 for (int i = 1; i < lLowerSize - 1; i++) { 216 retPoly[outIndex] = lLower[i]; 217 outIndex--; 218 } 219 // TODO: Add test harness which verify that all the points are inside the hull. 220 return total; 221} 222 223/** 224 * Test whether the 3 points form a counter clockwise turn. 225 * 226 * @return true if a right hand turn 227 */ 228bool SpotShadow::ccw(float ax, float ay, float bx, float by, 229 float cx, float cy) { 230 return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > EPSILON; 231} 232 233/** 234 * Sort points about a center point 235 * 236 * @param poly The in and out polyogon as a Vector2 array. 237 * @param polyLength The number of vertices of the polygon. 238 * @param center the center ctr[0] = x , ctr[1] = y to sort around. 239 */ 240void SpotShadow::sort(Vector2* poly, int polyLength, const Vector2& center) { 241 quicksortCirc(poly, 0, polyLength - 1, center); 242} 243 244/** 245 * Swap points pointed to by i and j 246 */ 247void SpotShadow::swap(Vector2* points, int i, int j) { 248 Vector2 temp = points[i]; 249 points[i] = points[j]; 250 points[j] = temp; 251} 252 253/** 254 * quick sort implementation about the center. 255 */ 256void SpotShadow::quicksortCirc(Vector2* points, int low, int high, 257 const Vector2& center) { 258 int i = low, j = high; 259 int p = low + (high - low) / 2; 260 float pivot = angle(points[p], center); 261 while (i <= j) { 262 while (angle(points[i], center) > pivot) { 263 i++; 264 } 265 while (angle(points[j], center) < pivot) { 266 j--; 267 } 268 269 if (i <= j) { 270 swap(points, i, j); 271 i++; 272 j--; 273 } 274 } 275 if (low < j) quicksortCirc(points, low, j, center); 276 if (i < high) quicksortCirc(points, i, high, center); 277} 278 279/** 280 * Test whether a point is inside the polygon. 281 * 282 * @param testPoint the point to test 283 * @param poly the polygon 284 * @return true if the testPoint is inside the poly. 285 */ 286bool SpotShadow::testPointInsidePolygon(const Vector2 testPoint, 287 const Vector2* poly, int len) { 288 bool c = false; 289 float testx = testPoint.x; 290 float testy = testPoint.y; 291 for (int i = 0, j = len - 1; i < len; j = i++) { 292 float startX = poly[j].x; 293 float startY = poly[j].y; 294 float endX = poly[i].x; 295 float endY = poly[i].y; 296 297 if (((endY > testy) != (startY > testy)) 298 && (testx < (startX - endX) * (testy - endY) 299 / (startY - endY) + endX)) { 300 c = !c; 301 } 302 } 303 return c; 304} 305 306/** 307 * Make the polygon turn clockwise. 308 * 309 * @param polygon the polygon as a Vector2 array. 310 * @param len the number of points of the polygon 311 */ 312void SpotShadow::makeClockwise(Vector2* polygon, int len) { 313 if (polygon == nullptr || len == 0) { 314 return; 315 } 316 if (!ShadowTessellator::isClockwise(polygon, len)) { 317 reverse(polygon, len); 318 } 319} 320 321/** 322 * Reverse the polygon 323 * 324 * @param polygon the polygon as a Vector2 array 325 * @param len the number of points of the polygon 326 */ 327void SpotShadow::reverse(Vector2* polygon, int len) { 328 int n = len / 2; 329 for (int i = 0; i < n; i++) { 330 Vector2 tmp = polygon[i]; 331 int k = len - 1 - i; 332 polygon[i] = polygon[k]; 333 polygon[k] = tmp; 334 } 335} 336 337/** 338 * Compute a horizontal circular polygon about point (x , y , height) of radius 339 * (size) 340 * 341 * @param points number of the points of the output polygon. 342 * @param lightCenter the center of the light. 343 * @param size the light size. 344 * @param ret result polygon. 345 */ 346void SpotShadow::computeLightPolygon(int points, const Vector3& lightCenter, 347 float size, Vector3* ret) { 348 // TODO: Caching all the sin / cos values and store them in a look up table. 349 for (int i = 0; i < points; i++) { 350 float angle = 2 * i * M_PI / points; 351 ret[i].x = cosf(angle) * size + lightCenter.x; 352 ret[i].y = sinf(angle) * size + lightCenter.y; 353 ret[i].z = lightCenter.z; 354 } 355} 356 357/** 358 * From light center, project one vertex to the z=0 surface and get the outline. 359 * 360 * @param outline The result which is the outline position. 361 * @param lightCenter The center of light. 362 * @param polyVertex The input polygon's vertex. 363 * 364 * @return float The ratio of (polygon.z / light.z - polygon.z) 365 */ 366float SpotShadow::projectCasterToOutline(Vector2& outline, 367 const Vector3& lightCenter, const Vector3& polyVertex) { 368 float lightToPolyZ = lightCenter.z - polyVertex.z; 369 float ratioZ = CASTER_Z_CAP_RATIO; 370 if (lightToPolyZ != 0) { 371 // If any caster's vertex is almost above the light, we just keep it as 95% 372 // of the height of the light. 373 ratioZ = MathUtils::clamp(polyVertex.z / lightToPolyZ, 0.0f, CASTER_Z_CAP_RATIO); 374 } 375 376 outline.x = polyVertex.x - ratioZ * (lightCenter.x - polyVertex.x); 377 outline.y = polyVertex.y - ratioZ * (lightCenter.y - polyVertex.y); 378 return ratioZ; 379} 380 381/** 382 * Generate the shadow spot light of shape lightPoly and a object poly 383 * 384 * @param isCasterOpaque whether the caster is opaque 385 * @param lightCenter the center of the light 386 * @param lightSize the radius of the light 387 * @param poly x,y,z vertexes of a convex polygon that occludes the light source 388 * @param polyLength number of vertexes of the occluding polygon 389 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return 390 * empty strip if error. 391 */ 392void SpotShadow::createSpotShadow(bool isCasterOpaque, const Vector3& lightCenter, 393 float lightSize, const Vector3* poly, int polyLength, const Vector3& polyCentroid, 394 VertexBuffer& shadowTriangleStrip) { 395 if (CC_UNLIKELY(lightCenter.z <= 0)) { 396 ALOGW("Relative Light Z is not positive. No spot shadow!"); 397 return; 398 } 399 if (CC_UNLIKELY(polyLength < 3)) { 400#if DEBUG_SHADOW 401 ALOGW("Invalid polygon length. No spot shadow!"); 402#endif 403 return; 404 } 405 OutlineData outlineData[polyLength]; 406 Vector2 outlineCentroid; 407 // Calculate the projected outline for each polygon's vertices from the light center. 408 // 409 // O Light 410 // / 411 // / 412 // . Polygon vertex 413 // / 414 // / 415 // O Outline vertices 416 // 417 // Ratio = (Poly - Outline) / (Light - Poly) 418 // Outline.x = Poly.x - Ratio * (Light.x - Poly.x) 419 // Outline's radius / Light's radius = Ratio 420 421 // Compute the last outline vertex to make sure we can get the normal and outline 422 // in one single loop. 423 projectCasterToOutline(outlineData[polyLength - 1].position, lightCenter, 424 poly[polyLength - 1]); 425 426 // Take the outline's polygon, calculate the normal for each outline edge. 427 int currentNormalIndex = polyLength - 1; 428 int nextNormalIndex = 0; 429 430 for (int i = 0; i < polyLength; i++) { 431 float ratioZ = projectCasterToOutline(outlineData[i].position, 432 lightCenter, poly[i]); 433 outlineData[i].radius = ratioZ * lightSize; 434 435 outlineData[currentNormalIndex].normal = ShadowTessellator::calculateNormal( 436 outlineData[currentNormalIndex].position, 437 outlineData[nextNormalIndex].position); 438 currentNormalIndex = (currentNormalIndex + 1) % polyLength; 439 nextNormalIndex++; 440 } 441 442 projectCasterToOutline(outlineCentroid, lightCenter, polyCentroid); 443 444 int penumbraIndex = 0; 445 // Then each polygon's vertex produce at minmal 2 penumbra vertices. 446 // Since the size can be dynamic here, we keep track of the size and update 447 // the real size at the end. 448 int allocatedPenumbraLength = 2 * polyLength + SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER; 449 Vector2 penumbra[allocatedPenumbraLength]; 450 int totalExtraCornerSliceNumber = 0; 451 452 Vector2 umbra[polyLength]; 453 454 // When centroid is covered by all circles from outline, then we consider 455 // the umbra is invalid, and we will tune down the shadow strength. 456 bool hasValidUmbra = true; 457 // We need the minimal of RaitoVI to decrease the spot shadow strength accordingly. 458 float minRaitoVI = FLT_MAX; 459 460 for (int i = 0; i < polyLength; i++) { 461 // Generate all the penumbra's vertices only using the (outline vertex + normal * radius) 462 // There is no guarantee that the penumbra is still convex, but for 463 // each outline vertex, it will connect to all its corresponding penumbra vertices as 464 // triangle fans. And for neighber penumbra vertex, it will be a trapezoid. 465 // 466 // Penumbra Vertices marked as Pi 467 // Outline Vertices marked as Vi 468 // (P3) 469 // (P2) | ' (P4) 470 // (P1)' | | ' 471 // ' | | ' 472 // (P0) ------------------------------------------------(P5) 473 // | (V0) |(V1) 474 // | | 475 // | | 476 // | | 477 // | | 478 // | | 479 // | | 480 // | | 481 // | | 482 // (V3)-----------------------------------(V2) 483 int preNormalIndex = (i + polyLength - 1) % polyLength; 484 485 const Vector2& previousNormal = outlineData[preNormalIndex].normal; 486 const Vector2& currentNormal = outlineData[i].normal; 487 488 // Depending on how roundness we want for each corner, we can subdivide 489 // further here and/or introduce some heuristic to decide how much the 490 // subdivision should be. 491 int currentExtraSliceNumber = ShadowTessellator::getExtraVertexNumber( 492 previousNormal, currentNormal, SPOT_CORNER_RADIANS_DIVISOR); 493 494 int currentCornerSliceNumber = 1 + currentExtraSliceNumber; 495 totalExtraCornerSliceNumber += currentExtraSliceNumber; 496#if DEBUG_SHADOW 497 ALOGD("currentExtraSliceNumber should be %d", currentExtraSliceNumber); 498 ALOGD("currentCornerSliceNumber should be %d", currentCornerSliceNumber); 499 ALOGD("totalCornerSliceNumber is %d", totalExtraCornerSliceNumber); 500#endif 501 if (CC_UNLIKELY(totalExtraCornerSliceNumber > SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER)) { 502 currentCornerSliceNumber = 1; 503 } 504 for (int k = 0; k <= currentCornerSliceNumber; k++) { 505 Vector2 avgNormal = 506 (previousNormal * (currentCornerSliceNumber - k) + currentNormal * k) / 507 currentCornerSliceNumber; 508 avgNormal.normalize(); 509 penumbra[penumbraIndex++] = outlineData[i].position + 510 avgNormal * outlineData[i].radius; 511 } 512 513 514 // Compute the umbra by the intersection from the outline's centroid! 515 // 516 // (V) ------------------------------------ 517 // | ' | 518 // | ' | 519 // | ' (I) | 520 // | ' | 521 // | ' (C) | 522 // | | 523 // | | 524 // | | 525 // | | 526 // ------------------------------------ 527 // 528 // Connect a line b/t the outline vertex (V) and the centroid (C), it will 529 // intersect with the outline vertex's circle at point (I). 530 // Now, ratioVI = VI / VC, ratioIC = IC / VC 531 // Then the intersetion point can be computed as Ixy = Vxy * ratioIC + Cxy * ratioVI; 532 // 533 // When all of the outline circles cover the the outline centroid, (like I is 534 // on the other side of C), there is no real umbra any more, so we just fake 535 // a small area around the centroid as the umbra, and tune down the spot 536 // shadow's umbra strength to simulate the effect the whole shadow will 537 // become lighter in this case. 538 // The ratio can be simulated by using the inverse of maximum of ratioVI for 539 // all (V). 540 float distOutline = (outlineData[i].position - outlineCentroid).length(); 541 if (CC_UNLIKELY(distOutline == 0)) { 542 // If the outline has 0 area, then there is no spot shadow anyway. 543 ALOGW("Outline has 0 area, no spot shadow!"); 544 return; 545 } 546 547 float ratioVI = outlineData[i].radius / distOutline; 548 minRaitoVI = MathUtils::min(minRaitoVI, ratioVI); 549 if (ratioVI >= (1 - FAKE_UMBRA_SIZE_RATIO)) { 550 ratioVI = (1 - FAKE_UMBRA_SIZE_RATIO); 551 } 552 // When we know we don't have valid umbra, don't bother to compute the 553 // values below. But we can't skip the loop yet since we want to know the 554 // maximum ratio. 555 float ratioIC = 1 - ratioVI; 556 umbra[i] = outlineData[i].position * ratioIC + outlineCentroid * ratioVI; 557 } 558 559 hasValidUmbra = (minRaitoVI <= 1.0); 560 float shadowStrengthScale = 1.0; 561 if (!hasValidUmbra) { 562#if DEBUG_SHADOW 563 ALOGW("The object is too close to the light or too small, no real umbra!"); 564#endif 565 for (int i = 0; i < polyLength; i++) { 566 umbra[i] = outlineData[i].position * FAKE_UMBRA_SIZE_RATIO + 567 outlineCentroid * (1 - FAKE_UMBRA_SIZE_RATIO); 568 } 569 shadowStrengthScale = 1.0 / minRaitoVI; 570 } 571 572 int penumbraLength = penumbraIndex; 573 int umbraLength = polyLength; 574 575#if DEBUG_SHADOW 576 ALOGD("penumbraLength is %d , allocatedPenumbraLength %d", penumbraLength, allocatedPenumbraLength); 577 dumpPolygon(poly, polyLength, "input poly"); 578 dumpPolygon(penumbra, penumbraLength, "penumbra"); 579 dumpPolygon(umbra, umbraLength, "umbra"); 580 ALOGD("hasValidUmbra is %d and shadowStrengthScale is %f", hasValidUmbra, shadowStrengthScale); 581#endif 582 583 // The penumbra and umbra needs to be in convex shape to keep consistency 584 // and quality. 585 // Since we are still shooting rays to penumbra, it needs to be convex. 586 // Umbra can be represented as a fan from the centroid, but visually umbra 587 // looks nicer when it is convex. 588 Vector2 finalUmbra[umbraLength]; 589 Vector2 finalPenumbra[penumbraLength]; 590 int finalUmbraLength = hull(umbra, umbraLength, finalUmbra); 591 int finalPenumbraLength = hull(penumbra, penumbraLength, finalPenumbra); 592 593 generateTriangleStrip(isCasterOpaque, shadowStrengthScale, finalPenumbra, 594 finalPenumbraLength, finalUmbra, finalUmbraLength, poly, polyLength, 595 shadowTriangleStrip, outlineCentroid); 596 597} 598 599/** 600 * This is only for experimental purpose. 601 * After intersections are calculated, we could smooth the polygon if needed. 602 * So far, we don't think it is more appealing yet. 603 * 604 * @param level The level of smoothness. 605 * @param rays The total number of rays. 606 * @param rayDist (In and Out) The distance for each ray. 607 * 608 */ 609void SpotShadow::smoothPolygon(int level, int rays, float* rayDist) { 610 for (int k = 0; k < level; k++) { 611 for (int i = 0; i < rays; i++) { 612 float p1 = rayDist[(rays - 1 + i) % rays]; 613 float p2 = rayDist[i]; 614 float p3 = rayDist[(i + 1) % rays]; 615 rayDist[i] = (p1 + p2 * 2 + p3) / 4; 616 } 617 } 618} 619 620// Index pair is meant for storing the tessellation information for the penumbra 621// area. One index must come from exterior tangent of the circles, the other one 622// must come from the interior tangent of the circles. 623struct IndexPair { 624 int outerIndex; 625 int innerIndex; 626}; 627 628// For one penumbra vertex, find the cloest umbra vertex and return its index. 629inline int getClosestUmbraIndex(const Vector2& pivot, const Vector2* polygon, int polygonLength) { 630 float minLengthSquared = FLT_MAX; 631 int resultIndex = -1; 632 bool hasDecreased = false; 633 // Starting with some negative offset, assuming both umbra and penumbra are starting 634 // at the same angle, this can help to find the result faster. 635 // Normally, loop 3 times, we can find the closest point. 636 int offset = polygonLength - 2; 637 for (int i = 0; i < polygonLength; i++) { 638 int currentIndex = (i + offset) % polygonLength; 639 float currentLengthSquared = (pivot - polygon[currentIndex]).lengthSquared(); 640 if (currentLengthSquared < minLengthSquared) { 641 if (minLengthSquared != FLT_MAX) { 642 hasDecreased = true; 643 } 644 minLengthSquared = currentLengthSquared; 645 resultIndex = currentIndex; 646 } else if (currentLengthSquared > minLengthSquared && hasDecreased) { 647 // Early break b/c we have found the closet one and now the length 648 // is increasing again. 649 break; 650 } 651 } 652 if(resultIndex == -1) { 653 ALOGE("resultIndex is -1, the polygon must be invalid!"); 654 resultIndex = 0; 655 } 656 return resultIndex; 657} 658 659// Allow some epsilon here since the later ray intersection did allow for some small 660// floating point error, when the intersection point is slightly outside the segment. 661inline bool sameDirections(bool isPositiveCross, float a, float b) { 662 if (isPositiveCross) { 663 return a >= -EPSILON && b >= -EPSILON; 664 } else { 665 return a <= EPSILON && b <= EPSILON; 666 } 667} 668 669// Find the right polygon edge to shoot the ray at. 670inline int findPolyIndex(bool isPositiveCross, int startPolyIndex, const Vector2& umbraDir, 671 const Vector2* polyToCentroid, int polyLength) { 672 // Make sure we loop with a bound. 673 for (int i = 0; i < polyLength; i++) { 674 int currentIndex = (i + startPolyIndex) % polyLength; 675 const Vector2& currentToCentroid = polyToCentroid[currentIndex]; 676 const Vector2& nextToCentroid = polyToCentroid[(currentIndex + 1) % polyLength]; 677 678 float currentCrossUmbra = currentToCentroid.cross(umbraDir); 679 float umbraCrossNext = umbraDir.cross(nextToCentroid); 680 if (sameDirections(isPositiveCross, currentCrossUmbra, umbraCrossNext)) { 681#if DEBUG_SHADOW 682 ALOGD("findPolyIndex loop %d times , index %d", i, currentIndex ); 683#endif 684 return currentIndex; 685 } 686 } 687 LOG_ALWAYS_FATAL("Can't find the right polygon's edge from startPolyIndex %d", startPolyIndex); 688 return -1; 689} 690 691// Generate the index pair for penumbra / umbra vertices, and more penumbra vertices 692// if needed. 693inline void genNewPenumbraAndPairWithUmbra(const Vector2* penumbra, int penumbraLength, 694 const Vector2* umbra, int umbraLength, Vector2* newPenumbra, int& newPenumbraIndex, 695 IndexPair* verticesPair, int& verticesPairIndex) { 696 // In order to keep everything in just one loop, we need to pre-compute the 697 // closest umbra vertex for the last penumbra vertex. 698 int previousClosestUmbraIndex = getClosestUmbraIndex(penumbra[penumbraLength - 1], 699 umbra, umbraLength); 700 for (int i = 0; i < penumbraLength; i++) { 701 const Vector2& currentPenumbraVertex = penumbra[i]; 702 // For current penumbra vertex, starting from previousClosestUmbraIndex, 703 // then check the next one until the distance increase. 704 // The last one before the increase is the umbra vertex we need to pair with. 705 float currentLengthSquared = 706 (currentPenumbraVertex - umbra[previousClosestUmbraIndex]).lengthSquared(); 707 int currentClosestUmbraIndex = previousClosestUmbraIndex; 708 int indexDelta = 0; 709 for (int j = 1; j < umbraLength; j++) { 710 int newUmbraIndex = (previousClosestUmbraIndex + j) % umbraLength; 711 float newLengthSquared = (currentPenumbraVertex - umbra[newUmbraIndex]).lengthSquared(); 712 if (newLengthSquared > currentLengthSquared) { 713 // currentClosestUmbraIndex is the umbra vertex's index which has 714 // currently found smallest distance, so we can simply break here. 715 break; 716 } else { 717 currentLengthSquared = newLengthSquared; 718 indexDelta++; 719 currentClosestUmbraIndex = newUmbraIndex; 720 } 721 } 722 723 if (indexDelta > 1) { 724 // For those umbra don't have penumbra, generate new penumbra vertices by interpolation. 725 // 726 // Assuming Pi for penumbra vertices, and Ui for umbra vertices. 727 // In the case like below P1 paired with U1 and P2 paired with U5. 728 // U2 to U4 are unpaired umbra vertices. 729 // 730 // P1 P2 731 // | | 732 // U1 U2 U3 U4 U5 733 // 734 // We will need to generate 3 more penumbra vertices P1.1, P1.2, P1.3 735 // to pair with U2 to U4. 736 // 737 // P1 P1.1 P1.2 P1.3 P2 738 // | | | | | 739 // U1 U2 U3 U4 U5 740 // 741 // That distance ratio b/t Ui to U1 and Ui to U5 decides its paired penumbra 742 // vertex's location. 743 int newPenumbraNumber = indexDelta - 1; 744 745 float accumulatedDeltaLength[newPenumbraNumber]; 746 float totalDeltaLength = 0; 747 748 // To save time, cache the previous umbra vertex info outside the loop 749 // and update each loop. 750 Vector2 previousClosestUmbra = umbra[previousClosestUmbraIndex]; 751 Vector2 skippedUmbra; 752 // Use umbra data to precompute the length b/t unpaired umbra vertices, 753 // and its ratio against the total length. 754 for (int k = 0; k < indexDelta; k++) { 755 int skippedUmbraIndex = (previousClosestUmbraIndex + k + 1) % umbraLength; 756 skippedUmbra = umbra[skippedUmbraIndex]; 757 float currentDeltaLength = (skippedUmbra - previousClosestUmbra).length(); 758 759 totalDeltaLength += currentDeltaLength; 760 accumulatedDeltaLength[k] = totalDeltaLength; 761 762 previousClosestUmbra = skippedUmbra; 763 } 764 765 const Vector2& previousPenumbra = penumbra[(i + penumbraLength - 1) % penumbraLength]; 766 // Then for each unpaired umbra vertex, create a new penumbra by the ratio, 767 // and pair them togehter. 768 for (int k = 0; k < newPenumbraNumber; k++) { 769 float weightForCurrentPenumbra = 1.0f; 770 if (totalDeltaLength != 0.0f) { 771 weightForCurrentPenumbra = accumulatedDeltaLength[k] / totalDeltaLength; 772 } 773 float weightForPreviousPenumbra = 1.0f - weightForCurrentPenumbra; 774 775 Vector2 interpolatedPenumbra = currentPenumbraVertex * weightForCurrentPenumbra + 776 previousPenumbra * weightForPreviousPenumbra; 777 778 int skippedUmbraIndex = (previousClosestUmbraIndex + k + 1) % umbraLength; 779 verticesPair[verticesPairIndex].outerIndex = newPenumbraIndex; 780 verticesPair[verticesPairIndex].innerIndex = skippedUmbraIndex; 781 verticesPairIndex++; 782 newPenumbra[newPenumbraIndex++] = interpolatedPenumbra; 783 } 784 } 785 verticesPair[verticesPairIndex].outerIndex = newPenumbraIndex; 786 verticesPair[verticesPairIndex].innerIndex = currentClosestUmbraIndex; 787 verticesPairIndex++; 788 newPenumbra[newPenumbraIndex++] = currentPenumbraVertex; 789 790 previousClosestUmbraIndex = currentClosestUmbraIndex; 791 } 792} 793 794// Precompute all the polygon's vector, return true if the reference cross product is positive. 795inline bool genPolyToCentroid(const Vector2* poly2d, int polyLength, 796 const Vector2& centroid, Vector2* polyToCentroid) { 797 for (int j = 0; j < polyLength; j++) { 798 polyToCentroid[j] = poly2d[j] - centroid; 799 // Normalize these vectors such that we can use epsilon comparison after 800 // computing their cross products with another normalized vector. 801 polyToCentroid[j].normalize(); 802 } 803 float refCrossProduct = 0; 804 for (int j = 0; j < polyLength; j++) { 805 refCrossProduct = polyToCentroid[j].cross(polyToCentroid[(j + 1) % polyLength]); 806 if (refCrossProduct != 0) { 807 break; 808 } 809 } 810 811 return refCrossProduct > 0; 812} 813 814// For one umbra vertex, shoot an ray from centroid to it. 815// If the ray hit the polygon first, then return the intersection point as the 816// closer vertex. 817inline Vector2 getCloserVertex(const Vector2& umbraVertex, const Vector2& centroid, 818 const Vector2* poly2d, int polyLength, const Vector2* polyToCentroid, 819 bool isPositiveCross, int& previousPolyIndex) { 820 Vector2 umbraToCentroid = umbraVertex - centroid; 821 float distanceToUmbra = umbraToCentroid.length(); 822 umbraToCentroid = umbraToCentroid / distanceToUmbra; 823 824 // previousPolyIndex is updated for each item such that we can minimize the 825 // looping inside findPolyIndex(); 826 previousPolyIndex = findPolyIndex(isPositiveCross, previousPolyIndex, 827 umbraToCentroid, polyToCentroid, polyLength); 828 829 float dx = umbraToCentroid.x; 830 float dy = umbraToCentroid.y; 831 float distanceToIntersectPoly = rayIntersectPoints(centroid, dx, dy, 832 poly2d[previousPolyIndex], poly2d[(previousPolyIndex + 1) % polyLength]); 833 if (distanceToIntersectPoly < 0) { 834 distanceToIntersectPoly = 0; 835 } 836 837 // Pick the closer one as the occluded area vertex. 838 Vector2 closerVertex; 839 if (distanceToIntersectPoly < distanceToUmbra) { 840 closerVertex.x = centroid.x + dx * distanceToIntersectPoly; 841 closerVertex.y = centroid.y + dy * distanceToIntersectPoly; 842 } else { 843 closerVertex = umbraVertex; 844 } 845 846 return closerVertex; 847} 848 849/** 850 * Generate a triangle strip given two convex polygon 851**/ 852void SpotShadow::generateTriangleStrip(bool isCasterOpaque, float shadowStrengthScale, 853 Vector2* penumbra, int penumbraLength, Vector2* umbra, int umbraLength, 854 const Vector3* poly, int polyLength, VertexBuffer& shadowTriangleStrip, 855 const Vector2& centroid) { 856 bool hasOccludedUmbraArea = false; 857 Vector2 poly2d[polyLength]; 858 859 if (isCasterOpaque) { 860 for (int i = 0; i < polyLength; i++) { 861 poly2d[i].x = poly[i].x; 862 poly2d[i].y = poly[i].y; 863 } 864 // Make sure the centroid is inside the umbra, otherwise, fall back to the 865 // approach as if there is no occluded umbra area. 866 if (testPointInsidePolygon(centroid, poly2d, polyLength)) { 867 hasOccludedUmbraArea = true; 868 } 869 } 870 871 // For each penumbra vertex, find its corresponding closest umbra vertex index. 872 // 873 // Penumbra Vertices marked as Pi 874 // Umbra Vertices marked as Ui 875 // (P3) 876 // (P2) | ' (P4) 877 // (P1)' | | ' 878 // ' | | ' 879 // (P0) ------------------------------------------------(P5) 880 // | (U0) |(U1) 881 // | | 882 // | |(U2) (P5.1) 883 // | | 884 // | | 885 // | | 886 // | | 887 // | | 888 // | | 889 // (U4)-----------------------------------(U3) (P6) 890 // 891 // At least, like P0, P1, P2, they will find the matching umbra as U0. 892 // If we jump over some umbra vertex without matching penumbra vertex, then 893 // we will generate some new penumbra vertex by interpolation. Like P6 is 894 // matching U3, but U2 is not matched with any penumbra vertex. 895 // So interpolate P5.1 out and match U2. 896 // In this way, every umbra vertex will have a matching penumbra vertex. 897 // 898 // The total pair number can be as high as umbraLength + penumbraLength. 899 const int maxNewPenumbraLength = umbraLength + penumbraLength; 900 IndexPair verticesPair[maxNewPenumbraLength]; 901 int verticesPairIndex = 0; 902 903 // Cache all the existing penumbra vertices and newly interpolated vertices into a 904 // a new array. 905 Vector2 newPenumbra[maxNewPenumbraLength]; 906 int newPenumbraIndex = 0; 907 908 // For each penumbra vertex, find its closet umbra vertex by comparing the 909 // neighbor umbra vertices. 910 genNewPenumbraAndPairWithUmbra(penumbra, penumbraLength, umbra, umbraLength, newPenumbra, 911 newPenumbraIndex, verticesPair, verticesPairIndex); 912 ShadowTessellator::checkOverflow(verticesPairIndex, maxNewPenumbraLength, "Spot pair"); 913 ShadowTessellator::checkOverflow(newPenumbraIndex, maxNewPenumbraLength, "Spot new penumbra"); 914#if DEBUG_SHADOW 915 for (int i = 0; i < umbraLength; i++) { 916 ALOGD("umbra i %d, [%f, %f]", i, umbra[i].x, umbra[i].y); 917 } 918 for (int i = 0; i < newPenumbraIndex; i++) { 919 ALOGD("new penumbra i %d, [%f, %f]", i, newPenumbra[i].x, newPenumbra[i].y); 920 } 921 for (int i = 0; i < verticesPairIndex; i++) { 922 ALOGD("index i %d, [%d, %d]", i, verticesPair[i].outerIndex, verticesPair[i].innerIndex); 923 } 924#endif 925 926 // For the size of vertex buffer, we need 3 rings, one has newPenumbraSize, 927 // one has umbraLength, the last one has at most umbraLength. 928 // 929 // For the size of index buffer, the umbra area needs (2 * umbraLength + 2). 930 // The penumbra one can vary a bit, but it is bounded by (2 * verticesPairIndex + 2). 931 // And 2 more for jumping between penumbra to umbra. 932 const int newPenumbraLength = newPenumbraIndex; 933 const int totalVertexCount = newPenumbraLength + umbraLength * 2; 934 const int totalIndexCount = 2 * umbraLength + 2 * verticesPairIndex + 6; 935 AlphaVertex* shadowVertices = 936 shadowTriangleStrip.alloc<AlphaVertex>(totalVertexCount); 937 uint16_t* indexBuffer = 938 shadowTriangleStrip.allocIndices<uint16_t>(totalIndexCount); 939 int vertexBufferIndex = 0; 940 int indexBufferIndex = 0; 941 942 // Fill the IB and VB for the penumbra area. 943 for (int i = 0; i < newPenumbraLength; i++) { 944 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], newPenumbra[i].x, 945 newPenumbra[i].y, TRANSFORMED_PENUMBRA_ALPHA); 946 } 947 for (int i = 0; i < umbraLength; i++) { 948 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], umbra[i].x, umbra[i].y, 949 TRANSFORMED_UMBRA_ALPHA); 950 } 951 952 for (int i = 0; i < verticesPairIndex; i++) { 953 indexBuffer[indexBufferIndex++] = verticesPair[i].outerIndex; 954 // All umbra index need to be offseted by newPenumbraSize. 955 indexBuffer[indexBufferIndex++] = verticesPair[i].innerIndex + newPenumbraLength; 956 } 957 indexBuffer[indexBufferIndex++] = verticesPair[0].outerIndex; 958 indexBuffer[indexBufferIndex++] = verticesPair[0].innerIndex + newPenumbraLength; 959 960 // Now fill the IB and VB for the umbra area. 961 // First duplicated the index from previous strip and the first one for the 962 // degenerated triangles. 963 indexBuffer[indexBufferIndex] = indexBuffer[indexBufferIndex - 1]; 964 indexBufferIndex++; 965 indexBuffer[indexBufferIndex++] = newPenumbraLength + 0; 966 // Save the first VB index for umbra area in order to close the loop. 967 int savedStartIndex = vertexBufferIndex; 968 969 if (hasOccludedUmbraArea) { 970 // Precompute all the polygon's vector, and the reference cross product, 971 // in order to find the right polygon edge for the ray to intersect. 972 Vector2 polyToCentroid[polyLength]; 973 bool isPositiveCross = genPolyToCentroid(poly2d, polyLength, centroid, polyToCentroid); 974 975 // Because both the umbra and polygon are going in the same direction, 976 // we can save the previous polygon index to make sure we have less polygon 977 // vertex to compute for each ray. 978 int previousPolyIndex = 0; 979 for (int i = 0; i < umbraLength; i++) { 980 // Shoot a ray from centroid to each umbra vertices and pick the one with 981 // shorter distance to the centroid, b/t the umbra vertex or the intersection point. 982 Vector2 closerVertex = getCloserVertex(umbra[i], centroid, poly2d, polyLength, 983 polyToCentroid, isPositiveCross, previousPolyIndex); 984 985 // We already stored the umbra vertices, just need to add the occlued umbra's ones. 986 indexBuffer[indexBufferIndex++] = newPenumbraLength + i; 987 indexBuffer[indexBufferIndex++] = vertexBufferIndex; 988 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], 989 closerVertex.x, closerVertex.y, TRANSFORMED_UMBRA_ALPHA); 990 } 991 } else { 992 // If there is no occluded umbra at all, then draw the triangle fan 993 // starting from the centroid to all umbra vertices. 994 int lastCentroidIndex = vertexBufferIndex; 995 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], centroid.x, 996 centroid.y, TRANSFORMED_UMBRA_ALPHA); 997 for (int i = 0; i < umbraLength; i++) { 998 indexBuffer[indexBufferIndex++] = newPenumbraLength + i; 999 indexBuffer[indexBufferIndex++] = lastCentroidIndex; 1000 } 1001 } 1002 // Closing the umbra area triangle's loop here. 1003 indexBuffer[indexBufferIndex++] = newPenumbraLength; 1004 indexBuffer[indexBufferIndex++] = savedStartIndex; 1005 1006 // At the end, update the real index and vertex buffer size. 1007 shadowTriangleStrip.updateVertexCount(vertexBufferIndex); 1008 shadowTriangleStrip.updateIndexCount(indexBufferIndex); 1009 ShadowTessellator::checkOverflow(vertexBufferIndex, totalVertexCount, "Spot Vertex Buffer"); 1010 ShadowTessellator::checkOverflow(indexBufferIndex, totalIndexCount, "Spot Index Buffer"); 1011 1012 shadowTriangleStrip.setMeshFeatureFlags(VertexBuffer::kAlpha | VertexBuffer::kIndices); 1013 shadowTriangleStrip.computeBounds<AlphaVertex>(); 1014} 1015 1016#if DEBUG_SHADOW 1017 1018#define TEST_POINT_NUMBER 128 1019/** 1020 * Calculate the bounds for generating random test points. 1021 */ 1022void SpotShadow::updateBound(const Vector2 inVector, Vector2& lowerBound, 1023 Vector2& upperBound) { 1024 if (inVector.x < lowerBound.x) { 1025 lowerBound.x = inVector.x; 1026 } 1027 1028 if (inVector.y < lowerBound.y) { 1029 lowerBound.y = inVector.y; 1030 } 1031 1032 if (inVector.x > upperBound.x) { 1033 upperBound.x = inVector.x; 1034 } 1035 1036 if (inVector.y > upperBound.y) { 1037 upperBound.y = inVector.y; 1038 } 1039} 1040 1041/** 1042 * For debug purpose, when things go wrong, dump the whole polygon data. 1043 */ 1044void SpotShadow::dumpPolygon(const Vector2* poly, int polyLength, const char* polyName) { 1045 for (int i = 0; i < polyLength; i++) { 1046 ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y); 1047 } 1048} 1049 1050/** 1051 * For debug purpose, when things go wrong, dump the whole polygon data. 1052 */ 1053void SpotShadow::dumpPolygon(const Vector3* poly, int polyLength, const char* polyName) { 1054 for (int i = 0; i < polyLength; i++) { 1055 ALOGD("polygon %s i %d x %f y %f z %f", polyName, i, poly[i].x, poly[i].y, poly[i].z); 1056 } 1057} 1058 1059/** 1060 * Test whether the polygon is convex. 1061 */ 1062bool SpotShadow::testConvex(const Vector2* polygon, int polygonLength, 1063 const char* name) { 1064 bool isConvex = true; 1065 for (int i = 0; i < polygonLength; i++) { 1066 Vector2 start = polygon[i]; 1067 Vector2 middle = polygon[(i + 1) % polygonLength]; 1068 Vector2 end = polygon[(i + 2) % polygonLength]; 1069 1070 float delta = (float(middle.x) - start.x) * (float(end.y) - start.y) - 1071 (float(middle.y) - start.y) * (float(end.x) - start.x); 1072 bool isCCWOrCoLinear = (delta >= EPSILON); 1073 1074 if (isCCWOrCoLinear) { 1075 ALOGW("(Error Type 2): polygon (%s) is not a convex b/c start (x %f, y %f)," 1076 "middle (x %f, y %f) and end (x %f, y %f) , delta is %f !!!", 1077 name, start.x, start.y, middle.x, middle.y, end.x, end.y, delta); 1078 isConvex = false; 1079 break; 1080 } 1081 } 1082 return isConvex; 1083} 1084 1085/** 1086 * Test whether or not the polygon (intersection) is within the 2 input polygons. 1087 * Using Marte Carlo method, we generate a random point, and if it is inside the 1088 * intersection, then it must be inside both source polygons. 1089 */ 1090void SpotShadow::testIntersection(const Vector2* poly1, int poly1Length, 1091 const Vector2* poly2, int poly2Length, 1092 const Vector2* intersection, int intersectionLength) { 1093 // Find the min and max of x and y. 1094 Vector2 lowerBound = {FLT_MAX, FLT_MAX}; 1095 Vector2 upperBound = {-FLT_MAX, -FLT_MAX}; 1096 for (int i = 0; i < poly1Length; i++) { 1097 updateBound(poly1[i], lowerBound, upperBound); 1098 } 1099 for (int i = 0; i < poly2Length; i++) { 1100 updateBound(poly2[i], lowerBound, upperBound); 1101 } 1102 1103 bool dumpPoly = false; 1104 for (int k = 0; k < TEST_POINT_NUMBER; k++) { 1105 // Generate a random point between minX, minY and maxX, maxY. 1106 float randomX = rand() / float(RAND_MAX); 1107 float randomY = rand() / float(RAND_MAX); 1108 1109 Vector2 testPoint; 1110 testPoint.x = lowerBound.x + randomX * (upperBound.x - lowerBound.x); 1111 testPoint.y = lowerBound.y + randomY * (upperBound.y - lowerBound.y); 1112 1113 // If the random point is in both poly 1 and 2, then it must be intersection. 1114 if (testPointInsidePolygon(testPoint, intersection, intersectionLength)) { 1115 if (!testPointInsidePolygon(testPoint, poly1, poly1Length)) { 1116 dumpPoly = true; 1117 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is" 1118 " not in the poly1", 1119 testPoint.x, testPoint.y); 1120 } 1121 1122 if (!testPointInsidePolygon(testPoint, poly2, poly2Length)) { 1123 dumpPoly = true; 1124 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is" 1125 " not in the poly2", 1126 testPoint.x, testPoint.y); 1127 } 1128 } 1129 } 1130 1131 if (dumpPoly) { 1132 dumpPolygon(intersection, intersectionLength, "intersection"); 1133 for (int i = 1; i < intersectionLength; i++) { 1134 Vector2 delta = intersection[i] - intersection[i - 1]; 1135 ALOGD("Intersetion i, %d Vs i-1 is delta %f", i, delta.lengthSquared()); 1136 } 1137 1138 dumpPolygon(poly1, poly1Length, "poly 1"); 1139 dumpPolygon(poly2, poly2Length, "poly 2"); 1140 } 1141} 1142#endif 1143 1144}; // namespace uirenderer 1145}; // namespace android 1146