blob: 576ba0efd17d9947418eeccce57abd4daa508ce9 [file] [log] [blame]
ztenghui7b4516e2014-01-07 10:42:55 -08001/*
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
ztenghui512e6432014-09-10 13:08:20 -070019// The highest z value can't be higher than (CASTER_Z_CAP_RATIO * light.z)
ztenghuic50a03d2014-08-21 13:47:54 -070020#define CASTER_Z_CAP_RATIO 0.95f
ztenghui512e6432014-09-10 13:08:20 -070021
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
ztenghui7b4516e2014-01-07 10:42:55 -080047
48#include <math.h>
ztenghuif5ca8b42014-01-27 15:53:28 -080049#include <stdlib.h>
ztenghui7b4516e2014-01-07 10:42:55 -080050#include <utils/Log.h>
51
ztenghui63d41ab2014-02-14 13:13:41 -080052#include "ShadowTessellator.h"
ztenghui7b4516e2014-01-07 10:42:55 -080053#include "SpotShadow.h"
54#include "Vertex.h"
ztenghuic50a03d2014-08-21 13:47:54 -070055#include "utils/MathUtils.h"
ztenghui7b4516e2014-01-07 10:42:55 -080056
ztenghuic50a03d2014-08-21 13:47:54 -070057// TODO: After we settle down the new algorithm, we can remove the old one and
58// its utility functions.
59// Right now, we still need to keep it for comparison purpose and future expansion.
ztenghui7b4516e2014-01-07 10:42:55 -080060namespace android {
61namespace uirenderer {
62
Chris Craik726118b2014-03-07 18:27:49 -080063static const double EPSILON = 1e-7;
64
ztenghui7b4516e2014-01-07 10:42:55 -080065/**
ztenghuic50a03d2014-08-21 13:47:54 -070066 * For each polygon's vertex, the light center will project it to the receiver
67 * as one of the outline vertex.
68 * For each outline vertex, we need to store the position and normal.
69 * Normal here is defined against the edge by the current vertex and the next vertex.
70 */
71struct OutlineData {
72 Vector2 position;
73 Vector2 normal;
74 float radius;
75};
76
77/**
ztenghui512e6432014-09-10 13:08:20 -070078 * For each vertex, we need to keep track of its angle, whether it is penumbra or
79 * umbra, and its corresponding vertex index.
80 */
81struct SpotShadow::VertexAngleData {
82 // The angle to the vertex from the centroid.
83 float mAngle;
84 // True is the vertex comes from penumbra, otherwise it comes from umbra.
85 bool mIsPenumbra;
86 // The index of the vertex described by this data.
87 int mVertexIndex;
88 void set(float angle, bool isPenumbra, int index) {
89 mAngle = angle;
90 mIsPenumbra = isPenumbra;
91 mVertexIndex = index;
92 }
93};
94
95/**
Chris Craik726118b2014-03-07 18:27:49 -080096 * Calculate the angle between and x and a y coordinate.
97 * The atan2 range from -PI to PI.
ztenghui7b4516e2014-01-07 10:42:55 -080098 */
Chris Craikb79a3e32014-03-11 12:20:17 -070099static float angle(const Vector2& point, const Vector2& center) {
Chris Craik726118b2014-03-07 18:27:49 -0800100 return atan2(point.y - center.y, point.x - center.x);
101}
102
103/**
104 * Calculate the intersection of a ray with the line segment defined by two points.
105 *
106 * Returns a negative value in error conditions.
107
108 * @param rayOrigin The start of the ray
109 * @param dx The x vector of the ray
110 * @param dy The y vector of the ray
111 * @param p1 The first point defining the line segment
112 * @param p2 The second point defining the line segment
113 * @return The distance along the ray if it intersects with the line segment, negative if otherwise
114 */
Chris Craikb79a3e32014-03-11 12:20:17 -0700115static float rayIntersectPoints(const Vector2& rayOrigin, float dx, float dy,
Chris Craik726118b2014-03-07 18:27:49 -0800116 const Vector2& p1, const Vector2& p2) {
117 // The math below is derived from solving this formula, basically the
118 // intersection point should stay on both the ray and the edge of (p1, p2).
119 // solve([p1x+t*(p2x-p1x)=dx*t2+px,p1y+t*(p2y-p1y)=dy*t2+py],[t,t2]);
120
121 double divisor = (dx * (p1.y - p2.y) + dy * p2.x - dy * p1.x);
122 if (divisor == 0) return -1.0f; // error, invalid divisor
123
124#if DEBUG_SHADOW
125 double interpVal = (dx * (p1.y - rayOrigin.y) + dy * rayOrigin.x - dy * p1.x) / divisor;
ztenghui99af9422014-03-14 14:35:54 -0700126 if (interpVal < 0 || interpVal > 1) {
127 ALOGW("rayIntersectPoints is hitting outside the segment %f", interpVal);
128 }
Chris Craik726118b2014-03-07 18:27:49 -0800129#endif
130
131 double distance = (p1.x * (rayOrigin.y - p2.y) + p2.x * (p1.y - rayOrigin.y) +
132 rayOrigin.x * (p2.y - p1.y)) / divisor;
133
134 return distance; // may be negative in error cases
ztenghui7b4516e2014-01-07 10:42:55 -0800135}
136
137/**
ztenghui7b4516e2014-01-07 10:42:55 -0800138 * Sort points by their X coordinates
139 *
140 * @param points the points as a Vector2 array.
141 * @param pointsLength the number of vertices of the polygon.
142 */
143void SpotShadow::xsort(Vector2* points, int pointsLength) {
144 quicksortX(points, 0, pointsLength - 1);
145}
146
147/**
148 * compute the convex hull of a collection of Points
149 *
150 * @param points the points as a Vector2 array.
151 * @param pointsLength the number of vertices of the polygon.
152 * @param retPoly pre allocated array of floats to put the vertices
153 * @return the number of points in the polygon 0 if no intersection
154 */
155int SpotShadow::hull(Vector2* points, int pointsLength, Vector2* retPoly) {
156 xsort(points, pointsLength);
157 int n = pointsLength;
158 Vector2 lUpper[n];
159 lUpper[0] = points[0];
160 lUpper[1] = points[1];
161
162 int lUpperSize = 2;
163
164 for (int i = 2; i < n; i++) {
165 lUpper[lUpperSize] = points[i];
166 lUpperSize++;
167
ztenghuif5ca8b42014-01-27 15:53:28 -0800168 while (lUpperSize > 2 && !ccw(
169 lUpper[lUpperSize - 3].x, lUpper[lUpperSize - 3].y,
170 lUpper[lUpperSize - 2].x, lUpper[lUpperSize - 2].y,
171 lUpper[lUpperSize - 1].x, lUpper[lUpperSize - 1].y)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800172 // Remove the middle point of the three last
173 lUpper[lUpperSize - 2].x = lUpper[lUpperSize - 1].x;
174 lUpper[lUpperSize - 2].y = lUpper[lUpperSize - 1].y;
175 lUpperSize--;
176 }
177 }
178
179 Vector2 lLower[n];
180 lLower[0] = points[n - 1];
181 lLower[1] = points[n - 2];
182
183 int lLowerSize = 2;
184
185 for (int i = n - 3; i >= 0; i--) {
186 lLower[lLowerSize] = points[i];
187 lLowerSize++;
188
ztenghuif5ca8b42014-01-27 15:53:28 -0800189 while (lLowerSize > 2 && !ccw(
190 lLower[lLowerSize - 3].x, lLower[lLowerSize - 3].y,
191 lLower[lLowerSize - 2].x, lLower[lLowerSize - 2].y,
192 lLower[lLowerSize - 1].x, lLower[lLowerSize - 1].y)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800193 // Remove the middle point of the three last
194 lLower[lLowerSize - 2] = lLower[lLowerSize - 1];
195 lLowerSize--;
196 }
197 }
ztenghui7b4516e2014-01-07 10:42:55 -0800198
Chris Craik726118b2014-03-07 18:27:49 -0800199 // output points in CW ordering
200 const int total = lUpperSize + lLowerSize - 2;
201 int outIndex = total - 1;
ztenghui7b4516e2014-01-07 10:42:55 -0800202 for (int i = 0; i < lUpperSize; i++) {
Chris Craik726118b2014-03-07 18:27:49 -0800203 retPoly[outIndex] = lUpper[i];
204 outIndex--;
ztenghui7b4516e2014-01-07 10:42:55 -0800205 }
206
207 for (int i = 1; i < lLowerSize - 1; i++) {
Chris Craik726118b2014-03-07 18:27:49 -0800208 retPoly[outIndex] = lLower[i];
209 outIndex--;
ztenghui7b4516e2014-01-07 10:42:55 -0800210 }
211 // TODO: Add test harness which verify that all the points are inside the hull.
Chris Craik726118b2014-03-07 18:27:49 -0800212 return total;
ztenghui7b4516e2014-01-07 10:42:55 -0800213}
214
215/**
ztenghuif5ca8b42014-01-27 15:53:28 -0800216 * Test whether the 3 points form a counter clockwise turn.
ztenghui7b4516e2014-01-07 10:42:55 -0800217 *
ztenghui7b4516e2014-01-07 10:42:55 -0800218 * @return true if a right hand turn
219 */
ztenghuif5ca8b42014-01-27 15:53:28 -0800220bool SpotShadow::ccw(double ax, double ay, double bx, double by,
ztenghui7b4516e2014-01-07 10:42:55 -0800221 double cx, double cy) {
222 return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > EPSILON;
223}
224
225/**
226 * Calculates the intersection of poly1 with poly2 and put in poly2.
ztenghui50ecf842014-03-11 16:52:30 -0700227 * Note that both poly1 and poly2 must be in CW order already!
ztenghui7b4516e2014-01-07 10:42:55 -0800228 *
229 * @param poly1 The 1st polygon, as a Vector2 array.
230 * @param poly1Length The number of vertices of 1st polygon.
231 * @param poly2 The 2nd and output polygon, as a Vector2 array.
232 * @param poly2Length The number of vertices of 2nd polygon.
233 * @return number of vertices in output polygon as poly2.
234 */
ztenghui50ecf842014-03-11 16:52:30 -0700235int SpotShadow::intersection(const Vector2* poly1, int poly1Length,
ztenghui7b4516e2014-01-07 10:42:55 -0800236 Vector2* poly2, int poly2Length) {
ztenghui50ecf842014-03-11 16:52:30 -0700237#if DEBUG_SHADOW
ztenghui2e023f32014-04-28 16:43:13 -0700238 if (!ShadowTessellator::isClockwise(poly1, poly1Length)) {
ztenghui50ecf842014-03-11 16:52:30 -0700239 ALOGW("Poly1 is not clockwise! Intersection is wrong!");
240 }
ztenghui2e023f32014-04-28 16:43:13 -0700241 if (!ShadowTessellator::isClockwise(poly2, poly2Length)) {
ztenghui50ecf842014-03-11 16:52:30 -0700242 ALOGW("Poly2 is not clockwise! Intersection is wrong!");
243 }
244#endif
ztenghui7b4516e2014-01-07 10:42:55 -0800245 Vector2 poly[poly1Length * poly2Length + 2];
246 int count = 0;
247 int pcount = 0;
248
249 // If one vertex from one polygon sits inside another polygon, add it and
250 // count them.
251 for (int i = 0; i < poly1Length; i++) {
252 if (testPointInsidePolygon(poly1[i], poly2, poly2Length)) {
253 poly[count] = poly1[i];
254 count++;
255 pcount++;
256
257 }
258 }
259
260 int insidePoly2 = pcount;
261 for (int i = 0; i < poly2Length; i++) {
262 if (testPointInsidePolygon(poly2[i], poly1, poly1Length)) {
263 poly[count] = poly2[i];
264 count++;
265 }
266 }
267
268 int insidePoly1 = count - insidePoly2;
269 // If all vertices from poly1 are inside poly2, then just return poly1.
270 if (insidePoly2 == poly1Length) {
271 memcpy(poly2, poly1, poly1Length * sizeof(Vector2));
272 return poly1Length;
273 }
274
275 // If all vertices from poly2 are inside poly1, then just return poly2.
276 if (insidePoly1 == poly2Length) {
277 return poly2Length;
278 }
279
280 // Since neither polygon fully contain the other one, we need to add all the
281 // intersection points.
John Reck1aa5d2d2014-07-24 13:38:28 -0700282 Vector2 intersection = {0, 0};
ztenghui7b4516e2014-01-07 10:42:55 -0800283 for (int i = 0; i < poly2Length; i++) {
284 for (int j = 0; j < poly1Length; j++) {
285 int poly2LineStart = i;
286 int poly2LineEnd = ((i + 1) % poly2Length);
287 int poly1LineStart = j;
288 int poly1LineEnd = ((j + 1) % poly1Length);
289 bool found = lineIntersection(
290 poly2[poly2LineStart].x, poly2[poly2LineStart].y,
291 poly2[poly2LineEnd].x, poly2[poly2LineEnd].y,
292 poly1[poly1LineStart].x, poly1[poly1LineStart].y,
293 poly1[poly1LineEnd].x, poly1[poly1LineEnd].y,
294 intersection);
295 if (found) {
296 poly[count].x = intersection.x;
297 poly[count].y = intersection.y;
298 count++;
299 } else {
300 Vector2 delta = poly2[i] - poly1[j];
ztenghuif5ca8b42014-01-27 15:53:28 -0800301 if (delta.lengthSquared() < EPSILON) {
ztenghui7b4516e2014-01-07 10:42:55 -0800302 poly[count] = poly2[i];
303 count++;
304 }
305 }
306 }
307 }
308
309 if (count == 0) {
310 return 0;
311 }
312
313 // Sort the result polygon around the center.
John Reck1aa5d2d2014-07-24 13:38:28 -0700314 Vector2 center = {0.0f, 0.0f};
ztenghui7b4516e2014-01-07 10:42:55 -0800315 for (int i = 0; i < count; i++) {
316 center += poly[i];
317 }
318 center /= count;
319 sort(poly, count, center);
320
ztenghuif5ca8b42014-01-27 15:53:28 -0800321#if DEBUG_SHADOW
322 // Since poly2 is overwritten as the result, we need to save a copy to do
323 // our verification.
324 Vector2 oldPoly2[poly2Length];
325 int oldPoly2Length = poly2Length;
326 memcpy(oldPoly2, poly2, sizeof(Vector2) * poly2Length);
327#endif
ztenghui7b4516e2014-01-07 10:42:55 -0800328
ztenghuif5ca8b42014-01-27 15:53:28 -0800329 // Filter the result out from poly and put it into poly2.
ztenghui7b4516e2014-01-07 10:42:55 -0800330 poly2[0] = poly[0];
ztenghuif5ca8b42014-01-27 15:53:28 -0800331 int lastOutputIndex = 0;
ztenghui7b4516e2014-01-07 10:42:55 -0800332 for (int i = 1; i < count; i++) {
ztenghuif5ca8b42014-01-27 15:53:28 -0800333 Vector2 delta = poly[i] - poly2[lastOutputIndex];
334 if (delta.lengthSquared() >= EPSILON) {
335 poly2[++lastOutputIndex] = poly[i];
336 } else {
337 // If the vertices are too close, pick the inner one, because the
338 // inner one is more likely to be an intersection point.
339 Vector2 delta1 = poly[i] - center;
340 Vector2 delta2 = poly2[lastOutputIndex] - center;
341 if (delta1.lengthSquared() < delta2.lengthSquared()) {
342 poly2[lastOutputIndex] = poly[i];
343 }
ztenghui7b4516e2014-01-07 10:42:55 -0800344 }
345 }
ztenghuif5ca8b42014-01-27 15:53:28 -0800346 int resultLength = lastOutputIndex + 1;
347
348#if DEBUG_SHADOW
349 testConvex(poly2, resultLength, "intersection");
350 testConvex(poly1, poly1Length, "input poly1");
351 testConvex(oldPoly2, oldPoly2Length, "input poly2");
352
353 testIntersection(poly1, poly1Length, oldPoly2, oldPoly2Length, poly2, resultLength);
354#endif
ztenghui7b4516e2014-01-07 10:42:55 -0800355
356 return resultLength;
357}
358
359/**
360 * Sort points about a center point
361 *
362 * @param poly The in and out polyogon as a Vector2 array.
363 * @param polyLength The number of vertices of the polygon.
364 * @param center the center ctr[0] = x , ctr[1] = y to sort around.
365 */
366void SpotShadow::sort(Vector2* poly, int polyLength, const Vector2& center) {
367 quicksortCirc(poly, 0, polyLength - 1, center);
368}
369
370/**
ztenghui7b4516e2014-01-07 10:42:55 -0800371 * Swap points pointed to by i and j
372 */
373void SpotShadow::swap(Vector2* points, int i, int j) {
374 Vector2 temp = points[i];
375 points[i] = points[j];
376 points[j] = temp;
377}
378
379/**
380 * quick sort implementation about the center.
381 */
382void SpotShadow::quicksortCirc(Vector2* points, int low, int high,
383 const Vector2& center) {
384 int i = low, j = high;
385 int p = low + (high - low) / 2;
386 float pivot = angle(points[p], center);
387 while (i <= j) {
Chris Craik726118b2014-03-07 18:27:49 -0800388 while (angle(points[i], center) > pivot) {
ztenghui7b4516e2014-01-07 10:42:55 -0800389 i++;
390 }
Chris Craik726118b2014-03-07 18:27:49 -0800391 while (angle(points[j], center) < pivot) {
ztenghui7b4516e2014-01-07 10:42:55 -0800392 j--;
393 }
394
395 if (i <= j) {
396 swap(points, i, j);
397 i++;
398 j--;
399 }
400 }
401 if (low < j) quicksortCirc(points, low, j, center);
402 if (i < high) quicksortCirc(points, i, high, center);
403}
404
405/**
406 * Sort points by x axis
407 *
408 * @param points points to sort
409 * @param low start index
410 * @param high end index
411 */
412void SpotShadow::quicksortX(Vector2* points, int low, int high) {
413 int i = low, j = high;
414 int p = low + (high - low) / 2;
415 float pivot = points[p].x;
416 while (i <= j) {
417 while (points[i].x < pivot) {
418 i++;
419 }
420 while (points[j].x > pivot) {
421 j--;
422 }
423
424 if (i <= j) {
425 swap(points, i, j);
426 i++;
427 j--;
428 }
429 }
430 if (low < j) quicksortX(points, low, j);
431 if (i < high) quicksortX(points, i, high);
432}
433
434/**
435 * Test whether a point is inside the polygon.
436 *
437 * @param testPoint the point to test
438 * @param poly the polygon
439 * @return true if the testPoint is inside the poly.
440 */
441bool SpotShadow::testPointInsidePolygon(const Vector2 testPoint,
442 const Vector2* poly, int len) {
443 bool c = false;
444 double testx = testPoint.x;
445 double testy = testPoint.y;
446 for (int i = 0, j = len - 1; i < len; j = i++) {
447 double startX = poly[j].x;
448 double startY = poly[j].y;
449 double endX = poly[i].x;
450 double endY = poly[i].y;
451
ztenghui512e6432014-09-10 13:08:20 -0700452 if (((endY > testy) != (startY > testy))
453 && (testx < (startX - endX) * (testy - endY)
ztenghui7b4516e2014-01-07 10:42:55 -0800454 / (startY - endY) + endX)) {
455 c = !c;
456 }
457 }
458 return c;
459}
460
461/**
462 * Make the polygon turn clockwise.
463 *
464 * @param polygon the polygon as a Vector2 array.
465 * @param len the number of points of the polygon
466 */
467void SpotShadow::makeClockwise(Vector2* polygon, int len) {
468 if (polygon == 0 || len == 0) {
469 return;
470 }
ztenghui2e023f32014-04-28 16:43:13 -0700471 if (!ShadowTessellator::isClockwise(polygon, len)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800472 reverse(polygon, len);
473 }
474}
475
476/**
ztenghui7b4516e2014-01-07 10:42:55 -0800477 * Reverse the polygon
478 *
479 * @param polygon the polygon as a Vector2 array
480 * @param len the number of points of the polygon
481 */
482void SpotShadow::reverse(Vector2* polygon, int len) {
483 int n = len / 2;
484 for (int i = 0; i < n; i++) {
485 Vector2 tmp = polygon[i];
486 int k = len - 1 - i;
487 polygon[i] = polygon[k];
488 polygon[k] = tmp;
489 }
490}
491
492/**
493 * Intersects two lines in parametric form. This function is called in a tight
494 * loop, and we need double precision to get things right.
495 *
496 * @param x1 the x coordinate point 1 of line 1
497 * @param y1 the y coordinate point 1 of line 1
498 * @param x2 the x coordinate point 2 of line 1
499 * @param y2 the y coordinate point 2 of line 1
500 * @param x3 the x coordinate point 1 of line 2
501 * @param y3 the y coordinate point 1 of line 2
502 * @param x4 the x coordinate point 2 of line 2
503 * @param y4 the y coordinate point 2 of line 2
504 * @param ret the x,y location of the intersection
505 * @return true if it found an intersection
506 */
507inline bool SpotShadow::lineIntersection(double x1, double y1, double x2, double y2,
508 double x3, double y3, double x4, double y4, Vector2& ret) {
509 double d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
510 if (d == 0.0) return false;
511
512 double dx = (x1 * y2 - y1 * x2);
513 double dy = (x3 * y4 - y3 * x4);
514 double x = (dx * (x3 - x4) - (x1 - x2) * dy) / d;
515 double y = (dx * (y3 - y4) - (y1 - y2) * dy) / d;
516
517 // The intersection should be in the middle of the point 1 and point 2,
518 // likewise point 3 and point 4.
519 if (((x - x1) * (x - x2) > EPSILON)
520 || ((x - x3) * (x - x4) > EPSILON)
521 || ((y - y1) * (y - y2) > EPSILON)
522 || ((y - y3) * (y - y4) > EPSILON)) {
523 // Not interesected
524 return false;
525 }
526 ret.x = x;
527 ret.y = y;
528 return true;
529
530}
531
532/**
533 * Compute a horizontal circular polygon about point (x , y , height) of radius
534 * (size)
535 *
536 * @param points number of the points of the output polygon.
537 * @param lightCenter the center of the light.
538 * @param size the light size.
539 * @param ret result polygon.
540 */
541void SpotShadow::computeLightPolygon(int points, const Vector3& lightCenter,
542 float size, Vector3* ret) {
543 // TODO: Caching all the sin / cos values and store them in a look up table.
544 for (int i = 0; i < points; i++) {
545 double angle = 2 * i * M_PI / points;
Chris Craik726118b2014-03-07 18:27:49 -0800546 ret[i].x = cosf(angle) * size + lightCenter.x;
547 ret[i].y = sinf(angle) * size + lightCenter.y;
ztenghui7b4516e2014-01-07 10:42:55 -0800548 ret[i].z = lightCenter.z;
549 }
550}
551
552/**
ztenghui512e6432014-09-10 13:08:20 -0700553 * From light center, project one vertex to the z=0 surface and get the outline.
ztenghui7b4516e2014-01-07 10:42:55 -0800554 *
ztenghui512e6432014-09-10 13:08:20 -0700555 * @param outline The result which is the outline position.
556 * @param lightCenter The center of light.
557 * @param polyVertex The input polygon's vertex.
558 *
559 * @return float The ratio of (polygon.z / light.z - polygon.z)
ztenghui7b4516e2014-01-07 10:42:55 -0800560 */
ztenghuic50a03d2014-08-21 13:47:54 -0700561float SpotShadow::projectCasterToOutline(Vector2& outline,
562 const Vector3& lightCenter, const Vector3& polyVertex) {
563 float lightToPolyZ = lightCenter.z - polyVertex.z;
564 float ratioZ = CASTER_Z_CAP_RATIO;
565 if (lightToPolyZ != 0) {
566 // If any caster's vertex is almost above the light, we just keep it as 95%
567 // of the height of the light.
ztenghui3bd3fa12014-08-25 14:42:27 -0700568 ratioZ = MathUtils::clamp(polyVertex.z / lightToPolyZ, 0.0f, CASTER_Z_CAP_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700569 }
570
571 outline.x = polyVertex.x - ratioZ * (lightCenter.x - polyVertex.x);
572 outline.y = polyVertex.y - ratioZ * (lightCenter.y - polyVertex.y);
573 return ratioZ;
574}
575
576/**
577 * Generate the shadow spot light of shape lightPoly and a object poly
578 *
579 * @param isCasterOpaque whether the caster is opaque
580 * @param lightCenter the center of the light
581 * @param lightSize the radius of the light
582 * @param poly x,y,z vertexes of a convex polygon that occludes the light source
583 * @param polyLength number of vertexes of the occluding polygon
584 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
585 * empty strip if error.
586 */
587void SpotShadow::createSpotShadow(bool isCasterOpaque, const Vector3& lightCenter,
588 float lightSize, const Vector3* poly, int polyLength, const Vector3& polyCentroid,
589 VertexBuffer& shadowTriangleStrip) {
ztenghui3bd3fa12014-08-25 14:42:27 -0700590 if (CC_UNLIKELY(lightCenter.z <= 0)) {
591 ALOGW("Relative Light Z is not positive. No spot shadow!");
592 return;
593 }
ztenghui512e6432014-09-10 13:08:20 -0700594 if (CC_UNLIKELY(polyLength < 3)) {
595#if DEBUG_SHADOW
596 ALOGW("Invalid polygon length. No spot shadow!");
597#endif
598 return;
599 }
ztenghuic50a03d2014-08-21 13:47:54 -0700600 OutlineData outlineData[polyLength];
601 Vector2 outlineCentroid;
602 // Calculate the projected outline for each polygon's vertices from the light center.
603 //
604 // O Light
605 // /
606 // /
607 // . Polygon vertex
608 // /
609 // /
610 // O Outline vertices
611 //
612 // Ratio = (Poly - Outline) / (Light - Poly)
613 // Outline.x = Poly.x - Ratio * (Light.x - Poly.x)
614 // Outline's radius / Light's radius = Ratio
615
616 // Compute the last outline vertex to make sure we can get the normal and outline
617 // in one single loop.
618 projectCasterToOutline(outlineData[polyLength - 1].position, lightCenter,
619 poly[polyLength - 1]);
620
621 // Take the outline's polygon, calculate the normal for each outline edge.
622 int currentNormalIndex = polyLength - 1;
623 int nextNormalIndex = 0;
624
625 for (int i = 0; i < polyLength; i++) {
626 float ratioZ = projectCasterToOutline(outlineData[i].position,
627 lightCenter, poly[i]);
628 outlineData[i].radius = ratioZ * lightSize;
629
630 outlineData[currentNormalIndex].normal = ShadowTessellator::calculateNormal(
631 outlineData[currentNormalIndex].position,
632 outlineData[nextNormalIndex].position);
633 currentNormalIndex = (currentNormalIndex + 1) % polyLength;
634 nextNormalIndex++;
635 }
636
637 projectCasterToOutline(outlineCentroid, lightCenter, polyCentroid);
638
639 int penumbraIndex = 0;
ztenghui512e6432014-09-10 13:08:20 -0700640 // Then each polygon's vertex produce at minmal 2 penumbra vertices.
641 // Since the size can be dynamic here, we keep track of the size and update
642 // the real size at the end.
643 int allocatedPenumbraLength = 2 * polyLength + SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER;
644 Vector2 penumbra[allocatedPenumbraLength];
645 int totalExtraCornerSliceNumber = 0;
ztenghuic50a03d2014-08-21 13:47:54 -0700646
647 Vector2 umbra[polyLength];
ztenghuic50a03d2014-08-21 13:47:54 -0700648
ztenghui512e6432014-09-10 13:08:20 -0700649 // When centroid is covered by all circles from outline, then we consider
650 // the umbra is invalid, and we will tune down the shadow strength.
ztenghuic50a03d2014-08-21 13:47:54 -0700651 bool hasValidUmbra = true;
ztenghui512e6432014-09-10 13:08:20 -0700652 // We need the minimal of RaitoVI to decrease the spot shadow strength accordingly.
653 float minRaitoVI = FLT_MAX;
ztenghuic50a03d2014-08-21 13:47:54 -0700654
655 for (int i = 0; i < polyLength; i++) {
656 // Generate all the penumbra's vertices only using the (outline vertex + normal * radius)
657 // There is no guarantee that the penumbra is still convex, but for
658 // each outline vertex, it will connect to all its corresponding penumbra vertices as
659 // triangle fans. And for neighber penumbra vertex, it will be a trapezoid.
660 //
661 // Penumbra Vertices marked as Pi
662 // Outline Vertices marked as Vi
663 // (P3)
664 // (P2) | ' (P4)
665 // (P1)' | | '
666 // ' | | '
667 // (P0) ------------------------------------------------(P5)
668 // | (V0) |(V1)
669 // | |
670 // | |
671 // | |
672 // | |
673 // | |
674 // | |
675 // | |
676 // | |
677 // (V3)-----------------------------------(V2)
678 int preNormalIndex = (i + polyLength - 1) % polyLength;
ztenghuic50a03d2014-08-21 13:47:54 -0700679
ztenghui512e6432014-09-10 13:08:20 -0700680 const Vector2& previousNormal = outlineData[preNormalIndex].normal;
681 const Vector2& currentNormal = outlineData[i].normal;
682
683 // Depending on how roundness we want for each corner, we can subdivide
ztenghuic50a03d2014-08-21 13:47:54 -0700684 // further here and/or introduce some heuristic to decide how much the
685 // subdivision should be.
ztenghui512e6432014-09-10 13:08:20 -0700686 int currentExtraSliceNumber = ShadowTessellator::getExtraVertexNumber(
687 previousNormal, currentNormal, SPOT_CORNER_RADIANS_DIVISOR);
ztenghuic50a03d2014-08-21 13:47:54 -0700688
ztenghui512e6432014-09-10 13:08:20 -0700689 int currentCornerSliceNumber = 1 + currentExtraSliceNumber;
690 totalExtraCornerSliceNumber += currentExtraSliceNumber;
691#if DEBUG_SHADOW
692 ALOGD("currentExtraSliceNumber should be %d", currentExtraSliceNumber);
693 ALOGD("currentCornerSliceNumber should be %d", currentCornerSliceNumber);
694 ALOGD("totalCornerSliceNumber is %d", totalExtraCornerSliceNumber);
695#endif
696 if (CC_UNLIKELY(totalExtraCornerSliceNumber > SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER)) {
697 currentCornerSliceNumber = 1;
698 }
699 for (int k = 0; k <= currentCornerSliceNumber; k++) {
700 Vector2 avgNormal =
701 (previousNormal * (currentCornerSliceNumber - k) + currentNormal * k) /
702 currentCornerSliceNumber;
703 avgNormal.normalize();
704 penumbra[penumbraIndex++] = outlineData[i].position +
705 avgNormal * outlineData[i].radius;
706 }
ztenghuic50a03d2014-08-21 13:47:54 -0700707
ztenghuic50a03d2014-08-21 13:47:54 -0700708
709 // Compute the umbra by the intersection from the outline's centroid!
710 //
711 // (V) ------------------------------------
712 // | ' |
713 // | ' |
714 // | ' (I) |
715 // | ' |
716 // | ' (C) |
717 // | |
718 // | |
719 // | |
720 // | |
721 // ------------------------------------
722 //
723 // Connect a line b/t the outline vertex (V) and the centroid (C), it will
724 // intersect with the outline vertex's circle at point (I).
725 // Now, ratioVI = VI / VC, ratioIC = IC / VC
726 // Then the intersetion point can be computed as Ixy = Vxy * ratioIC + Cxy * ratioVI;
727 //
ztenghui512e6432014-09-10 13:08:20 -0700728 // When all of the outline circles cover the the outline centroid, (like I is
ztenghuic50a03d2014-08-21 13:47:54 -0700729 // on the other side of C), there is no real umbra any more, so we just fake
730 // a small area around the centroid as the umbra, and tune down the spot
731 // shadow's umbra strength to simulate the effect the whole shadow will
732 // become lighter in this case.
733 // The ratio can be simulated by using the inverse of maximum of ratioVI for
734 // all (V).
ztenghui512e6432014-09-10 13:08:20 -0700735 float distOutline = (outlineData[i].position - outlineCentroid).length();
ztenghui3bd3fa12014-08-25 14:42:27 -0700736 if (CC_UNLIKELY(distOutline == 0)) {
ztenghuic50a03d2014-08-21 13:47:54 -0700737 // If the outline has 0 area, then there is no spot shadow anyway.
738 ALOGW("Outline has 0 area, no spot shadow!");
739 return;
740 }
ztenghui512e6432014-09-10 13:08:20 -0700741
742 float ratioVI = outlineData[i].radius / distOutline;
743 minRaitoVI = MathUtils::min(minRaitoVI, ratioVI);
744 if (ratioVI >= (1 - FAKE_UMBRA_SIZE_RATIO)) {
745 ratioVI = (1 - FAKE_UMBRA_SIZE_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700746 }
747 // When we know we don't have valid umbra, don't bother to compute the
748 // values below. But we can't skip the loop yet since we want to know the
749 // maximum ratio.
ztenghui512e6432014-09-10 13:08:20 -0700750 float ratioIC = 1 - ratioVI;
751 umbra[i] = outlineData[i].position * ratioIC + outlineCentroid * ratioVI;
ztenghuic50a03d2014-08-21 13:47:54 -0700752 }
753
ztenghui512e6432014-09-10 13:08:20 -0700754 hasValidUmbra = (minRaitoVI <= 1.0);
ztenghuic50a03d2014-08-21 13:47:54 -0700755 float shadowStrengthScale = 1.0;
756 if (!hasValidUmbra) {
ztenghui512e6432014-09-10 13:08:20 -0700757#if DEBUG_SHADOW
ztenghuic50a03d2014-08-21 13:47:54 -0700758 ALOGW("The object is too close to the light or too small, no real umbra!");
ztenghui512e6432014-09-10 13:08:20 -0700759#endif
ztenghuic50a03d2014-08-21 13:47:54 -0700760 for (int i = 0; i < polyLength; i++) {
761 umbra[i] = outlineData[i].position * FAKE_UMBRA_SIZE_RATIO +
ztenghui512e6432014-09-10 13:08:20 -0700762 outlineCentroid * (1 - FAKE_UMBRA_SIZE_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700763 }
ztenghui512e6432014-09-10 13:08:20 -0700764 shadowStrengthScale = 1.0 / minRaitoVI;
ztenghuic50a03d2014-08-21 13:47:54 -0700765 }
766
ztenghui512e6432014-09-10 13:08:20 -0700767 int penumbraLength = penumbraIndex;
768 int umbraLength = polyLength;
769
ztenghuic50a03d2014-08-21 13:47:54 -0700770#if DEBUG_SHADOW
ztenghui512e6432014-09-10 13:08:20 -0700771 ALOGD("penumbraLength is %d , allocatedPenumbraLength %d", penumbraLength, allocatedPenumbraLength);
ztenghuic50a03d2014-08-21 13:47:54 -0700772 dumpPolygon(poly, polyLength, "input poly");
ztenghuic50a03d2014-08-21 13:47:54 -0700773 dumpPolygon(penumbra, penumbraLength, "penumbra");
ztenghui512e6432014-09-10 13:08:20 -0700774 dumpPolygon(umbra, umbraLength, "umbra");
ztenghuic50a03d2014-08-21 13:47:54 -0700775 ALOGD("hasValidUmbra is %d and shadowStrengthScale is %f", hasValidUmbra, shadowStrengthScale);
776#endif
777
ztenghui512e6432014-09-10 13:08:20 -0700778 // The penumbra and umbra needs to be in convex shape to keep consistency
779 // and quality.
780 // Since we are still shooting rays to penumbra, it needs to be convex.
781 // Umbra can be represented as a fan from the centroid, but visually umbra
782 // looks nicer when it is convex.
783 Vector2 finalUmbra[umbraLength];
784 Vector2 finalPenumbra[penumbraLength];
785 int finalUmbraLength = hull(umbra, umbraLength, finalUmbra);
786 int finalPenumbraLength = hull(penumbra, penumbraLength, finalPenumbra);
787
788 generateTriangleStrip(isCasterOpaque, shadowStrengthScale, finalPenumbra,
789 finalPenumbraLength, finalUmbra, finalUmbraLength, poly, polyLength,
790 shadowTriangleStrip, outlineCentroid);
791
ztenghuic50a03d2014-08-21 13:47:54 -0700792}
793
ztenghui7b4516e2014-01-07 10:42:55 -0800794/**
Chris Craik726118b2014-03-07 18:27:49 -0800795 * Converts a polygon specified with CW vertices into an array of distance-from-centroid values.
796 *
797 * Returns false in error conditions
798 *
799 * @param poly Array of vertices. Note that these *must* be CW.
800 * @param polyLength The number of vertices in the polygon.
801 * @param polyCentroid The centroid of the polygon, from which rays will be cast
802 * @param rayDist The output array for the calculated distances, must be SHADOW_RAY_COUNT in size
803 */
804bool convertPolyToRayDist(const Vector2* poly, int polyLength, const Vector2& polyCentroid,
805 float* rayDist) {
806 const int rays = SHADOW_RAY_COUNT;
807 const float step = M_PI * 2 / rays;
808
809 const Vector2* lastVertex = &(poly[polyLength - 1]);
810 float startAngle = angle(*lastVertex, polyCentroid);
811
812 // Start with the ray that's closest to and less than startAngle
813 int rayIndex = floor((startAngle - EPSILON) / step);
814 rayIndex = (rayIndex + rays) % rays; // ensure positive
815
816 for (int polyIndex = 0; polyIndex < polyLength; polyIndex++) {
817 /*
818 * For a given pair of vertices on the polygon, poly[i-1] and poly[i], the rays that
819 * intersect these will be those that are between the two angles from the centroid that the
820 * vertices define.
821 *
822 * Because the polygon vertices are stored clockwise, the closest ray with an angle
823 * *smaller* than that defined by angle(poly[i], centroid) will be the first ray that does
824 * not intersect with poly[i-1], poly[i].
825 */
826 float currentAngle = angle(poly[polyIndex], polyCentroid);
827
828 // find first ray that will not intersect the line segment poly[i-1] & poly[i]
829 int firstRayIndexOnNextSegment = floor((currentAngle - EPSILON) / step);
830 firstRayIndexOnNextSegment = (firstRayIndexOnNextSegment + rays) % rays; // ensure positive
831
832 // Iterate through all rays that intersect with poly[i-1], poly[i] line segment.
833 // This may be 0 rays.
834 while (rayIndex != firstRayIndexOnNextSegment) {
835 float distanceToIntersect = rayIntersectPoints(polyCentroid,
836 cos(rayIndex * step),
837 sin(rayIndex * step),
838 *lastVertex, poly[polyIndex]);
ztenghui50ecf842014-03-11 16:52:30 -0700839 if (distanceToIntersect < 0) {
840#if DEBUG_SHADOW
841 ALOGW("ERROR: convertPolyToRayDist failed");
842#endif
843 return false; // error case, abort
844 }
Chris Craik726118b2014-03-07 18:27:49 -0800845
846 rayDist[rayIndex] = distanceToIntersect;
847
848 rayIndex = (rayIndex - 1 + rays) % rays;
849 }
850 lastVertex = &poly[polyIndex];
851 }
852
ztenghui512e6432014-09-10 13:08:20 -0700853 return true;
Chris Craik726118b2014-03-07 18:27:49 -0800854}
855
ztenghui50ecf842014-03-11 16:52:30 -0700856int SpotShadow::calculateOccludedUmbra(const Vector2* umbra, int umbraLength,
857 const Vector3* poly, int polyLength, Vector2* occludedUmbra) {
858 // Occluded umbra area is computed as the intersection of the projected 2D
859 // poly and umbra.
860 for (int i = 0; i < polyLength; i++) {
861 occludedUmbra[i].x = poly[i].x;
862 occludedUmbra[i].y = poly[i].y;
863 }
864
865 // Both umbra and incoming polygon are guaranteed to be CW, so we can call
866 // intersection() directly.
867 return intersection(umbra, umbraLength,
868 occludedUmbra, polyLength);
869}
870
Chris Craik726118b2014-03-07 18:27:49 -0800871/**
ztenghui7b4516e2014-01-07 10:42:55 -0800872 * This is only for experimental purpose.
873 * After intersections are calculated, we could smooth the polygon if needed.
874 * So far, we don't think it is more appealing yet.
875 *
876 * @param level The level of smoothness.
877 * @param rays The total number of rays.
878 * @param rayDist (In and Out) The distance for each ray.
879 *
880 */
881void SpotShadow::smoothPolygon(int level, int rays, float* rayDist) {
882 for (int k = 0; k < level; k++) {
883 for (int i = 0; i < rays; i++) {
884 float p1 = rayDist[(rays - 1 + i) % rays];
885 float p2 = rayDist[i];
886 float p3 = rayDist[(i + 1) % rays];
887 rayDist[i] = (p1 + p2 * 2 + p3) / 4;
888 }
889 }
890}
891
ztenghui512e6432014-09-10 13:08:20 -0700892/**
893 * Generate a array of the angleData for either umbra or penumbra vertices.
894 *
895 * This array will be merged and used to guide where to shoot the rays, in clockwise order.
896 *
897 * @param angleDataList The result array of angle data.
898 *
899 * @return int The maximum angle's index in the array.
900 */
901int SpotShadow::setupAngleList(VertexAngleData* angleDataList,
902 int polyLength, const Vector2* polygon, const Vector2& centroid,
903 bool isPenumbra, const char* name) {
904 float maxAngle = FLT_MIN;
905 int maxAngleIndex = 0;
906 for (int i = 0; i < polyLength; i++) {
907 float currentAngle = angle(polygon[i], centroid);
908 if (currentAngle > maxAngle) {
909 maxAngle = currentAngle;
910 maxAngleIndex = i;
911 }
912 angleDataList[i].set(currentAngle, isPenumbra, i);
913#if DEBUG_SHADOW
914 ALOGD("%s AngleList i %d %f", name, i, currentAngle);
Andreas Gampe42ddc182014-11-21 09:49:08 -0800915#else
916 (void)name;
ztenghui512e6432014-09-10 13:08:20 -0700917#endif
918 }
919 return maxAngleIndex;
920}
921
922/**
923 * Make sure the polygons are indeed in clockwise order.
924 *
925 * Possible reasons to return false: 1. The input polygon is not setup properly. 2. The hull
926 * algorithm is not able to generate it properly.
927 *
928 * Anyway, since the algorithm depends on the clockwise, when these kind of unexpected error
929 * situation is found, we need to detect it and early return without corrupting the memory.
930 *
931 * @return bool True if the angle list is actually from big to small.
932 */
933bool SpotShadow::checkClockwise(int indexOfMaxAngle, int listLength, VertexAngleData* angleList,
934 const char* name) {
935 int currentIndex = indexOfMaxAngle;
936#if DEBUG_SHADOW
937 ALOGD("max index %d", currentIndex);
938#endif
939 for (int i = 0; i < listLength - 1; i++) {
940 // TODO: Cache the last angle.
941 float currentAngle = angleList[currentIndex].mAngle;
942 float nextAngle = angleList[(currentIndex + 1) % listLength].mAngle;
943 if (currentAngle < nextAngle) {
944#if DEBUG_SHADOW
945 ALOGE("%s, is not CW, at index %d", name, currentIndex);
Andreas Gampe42ddc182014-11-21 09:49:08 -0800946#else
947 (void)name;
ztenghui512e6432014-09-10 13:08:20 -0700948#endif
949 return false;
950 }
951 currentIndex = (currentIndex + 1) % listLength;
952 }
953 return true;
954}
955
956/**
957 * Check the polygon is clockwise.
958 *
959 * @return bool True is the polygon is clockwise.
960 */
961bool SpotShadow::checkPolyClockwise(int polyAngleLength, int maxPolyAngleIndex,
962 const float* polyAngleList) {
963 bool isPolyCW = true;
964 // Starting from maxPolyAngleIndex , check around to make sure angle decrease.
965 for (int i = 0; i < polyAngleLength - 1; i++) {
966 float currentAngle = polyAngleList[(i + maxPolyAngleIndex) % polyAngleLength];
967 float nextAngle = polyAngleList[(i + maxPolyAngleIndex + 1) % polyAngleLength];
968 if (currentAngle < nextAngle) {
969 isPolyCW = false;
970 }
971 }
972 return isPolyCW;
973}
974
975/**
976 * Given the sorted array of all the vertices angle data, calculate for each
977 * vertices, the offset value to array element which represent the start edge
978 * of the polygon we need to shoot the ray at.
979 *
980 * TODO: Calculate this for umbra and penumbra in one loop using one single array.
981 *
982 * @param distances The result of the array distance counter.
983 */
984void SpotShadow::calculateDistanceCounter(bool needsOffsetToUmbra, int angleLength,
985 const VertexAngleData* allVerticesAngleData, int* distances) {
986
987 bool firstVertexIsPenumbra = allVerticesAngleData[0].mIsPenumbra;
988 // If we want distance to inner, then we just set to 0 when we see inner.
989 bool needsSearch = needsOffsetToUmbra ? firstVertexIsPenumbra : !firstVertexIsPenumbra;
990 int distanceCounter = 0;
991 if (needsSearch) {
992 int foundIndex = -1;
993 for (int i = (angleLength - 1); i >= 0; i--) {
994 bool currentIsOuter = allVerticesAngleData[i].mIsPenumbra;
995 // If we need distance to inner, then we need to find a inner vertex.
996 if (currentIsOuter != firstVertexIsPenumbra) {
997 foundIndex = i;
998 break;
999 }
1000 }
1001 LOG_ALWAYS_FATAL_IF(foundIndex == -1, "Wrong index found, means either"
1002 " umbra or penumbra's length is 0");
1003 distanceCounter = angleLength - foundIndex;
1004 }
1005#if DEBUG_SHADOW
1006 ALOGD("distances[0] is %d", distanceCounter);
1007#endif
1008
1009 distances[0] = distanceCounter; // means never see a target poly
1010
1011 for (int i = 1; i < angleLength; i++) {
1012 bool firstVertexIsPenumbra = allVerticesAngleData[i].mIsPenumbra;
1013 // When we needs for distance for each outer vertex to inner, then we
1014 // increase the distance when seeing outer vertices. Otherwise, we clear
1015 // to 0.
1016 bool needsIncrement = needsOffsetToUmbra ? firstVertexIsPenumbra : !firstVertexIsPenumbra;
1017 // If counter is not -1, that means we have seen an other polygon's vertex.
1018 if (needsIncrement && distanceCounter != -1) {
1019 distanceCounter++;
1020 } else {
1021 distanceCounter = 0;
1022 }
1023 distances[i] = distanceCounter;
1024 }
1025}
1026
1027/**
1028 * Given umbra and penumbra angle data list, merge them by sorting the angle
1029 * from the biggest to smallest.
1030 *
1031 * @param allVerticesAngleData The result array of merged angle data.
1032 */
1033void SpotShadow::mergeAngleList(int maxUmbraAngleIndex, int maxPenumbraAngleIndex,
1034 const VertexAngleData* umbraAngleList, int umbraLength,
1035 const VertexAngleData* penumbraAngleList, int penumbraLength,
1036 VertexAngleData* allVerticesAngleData) {
1037
1038 int totalRayNumber = umbraLength + penumbraLength;
1039 int umbraIndex = maxUmbraAngleIndex;
1040 int penumbraIndex = maxPenumbraAngleIndex;
1041
1042 float currentUmbraAngle = umbraAngleList[umbraIndex].mAngle;
1043 float currentPenumbraAngle = penumbraAngleList[penumbraIndex].mAngle;
1044
1045 // TODO: Clean this up using a while loop with 2 iterators.
1046 for (int i = 0; i < totalRayNumber; i++) {
1047 if (currentUmbraAngle > currentPenumbraAngle) {
1048 allVerticesAngleData[i] = umbraAngleList[umbraIndex];
1049 umbraIndex = (umbraIndex + 1) % umbraLength;
1050
1051 // If umbraIndex round back, that means we are running out of
1052 // umbra vertices to merge, so just copy all the penumbra leftover.
1053 // Otherwise, we update the currentUmbraAngle.
1054 if (umbraIndex != maxUmbraAngleIndex) {
1055 currentUmbraAngle = umbraAngleList[umbraIndex].mAngle;
1056 } else {
1057 for (int j = i + 1; j < totalRayNumber; j++) {
1058 allVerticesAngleData[j] = penumbraAngleList[penumbraIndex];
1059 penumbraIndex = (penumbraIndex + 1) % penumbraLength;
1060 }
1061 break;
1062 }
1063 } else {
1064 allVerticesAngleData[i] = penumbraAngleList[penumbraIndex];
1065 penumbraIndex = (penumbraIndex + 1) % penumbraLength;
1066 // If penumbraIndex round back, that means we are running out of
1067 // penumbra vertices to merge, so just copy all the umbra leftover.
1068 // Otherwise, we update the currentPenumbraAngle.
1069 if (penumbraIndex != maxPenumbraAngleIndex) {
1070 currentPenumbraAngle = penumbraAngleList[penumbraIndex].mAngle;
1071 } else {
1072 for (int j = i + 1; j < totalRayNumber; j++) {
1073 allVerticesAngleData[j] = umbraAngleList[umbraIndex];
1074 umbraIndex = (umbraIndex + 1) % umbraLength;
1075 }
1076 break;
1077 }
1078 }
1079 }
1080}
1081
1082#if DEBUG_SHADOW
1083/**
1084 * DEBUG ONLY: Verify all the offset compuation is correctly done by examining
1085 * each vertex and its neighbor.
1086 */
1087static void verifyDistanceCounter(const VertexAngleData* allVerticesAngleData,
1088 const int* distances, int angleLength, const char* name) {
1089 int currentDistance = distances[0];
1090 for (int i = 1; i < angleLength; i++) {
1091 if (distances[i] != INT_MIN) {
1092 if (!((currentDistance + 1) == distances[i]
1093 || distances[i] == 0)) {
1094 ALOGE("Wrong distance found at i %d name %s", i, name);
1095 }
1096 currentDistance = distances[i];
1097 if (currentDistance != 0) {
1098 bool currentOuter = allVerticesAngleData[i].mIsPenumbra;
1099 for (int j = 1; j <= (currentDistance - 1); j++) {
1100 bool neigborOuter =
1101 allVerticesAngleData[(i + angleLength - j) % angleLength].mIsPenumbra;
1102 if (neigborOuter != currentOuter) {
1103 ALOGE("Wrong distance found at i %d name %s", i, name);
1104 }
1105 }
1106 bool oppositeOuter =
1107 allVerticesAngleData[(i + angleLength - currentDistance) % angleLength].mIsPenumbra;
1108 if (oppositeOuter == currentOuter) {
1109 ALOGE("Wrong distance found at i %d name %s", i, name);
1110 }
1111 }
1112 }
1113 }
1114}
1115
1116/**
1117 * DEBUG ONLY: Verify all the angle data compuated are is correctly done
1118 */
1119static void verifyAngleData(int totalRayNumber, const VertexAngleData* allVerticesAngleData,
1120 const int* distancesToInner, const int* distancesToOuter,
1121 const VertexAngleData* umbraAngleList, int maxUmbraAngleIndex, int umbraLength,
1122 const VertexAngleData* penumbraAngleList, int maxPenumbraAngleIndex,
1123 int penumbraLength) {
1124 for (int i = 0; i < totalRayNumber; i++) {
1125 ALOGD("currentAngleList i %d, angle %f, isInner %d, index %d distancesToInner"
1126 " %d distancesToOuter %d", i, allVerticesAngleData[i].mAngle,
1127 !allVerticesAngleData[i].mIsPenumbra,
1128 allVerticesAngleData[i].mVertexIndex, distancesToInner[i], distancesToOuter[i]);
1129 }
1130
1131 verifyDistanceCounter(allVerticesAngleData, distancesToInner, totalRayNumber, "distancesToInner");
1132 verifyDistanceCounter(allVerticesAngleData, distancesToOuter, totalRayNumber, "distancesToOuter");
1133
1134 for (int i = 0; i < totalRayNumber; i++) {
1135 if ((distancesToInner[i] * distancesToOuter[i]) != 0) {
1136 ALOGE("distancesToInner wrong at index %d distancesToInner[i] %d,"
1137 " distancesToOuter[i] %d", i, distancesToInner[i], distancesToOuter[i]);
1138 }
1139 }
1140 int currentUmbraVertexIndex =
1141 umbraAngleList[maxUmbraAngleIndex].mVertexIndex;
1142 int currentPenumbraVertexIndex =
1143 penumbraAngleList[maxPenumbraAngleIndex].mVertexIndex;
1144 for (int i = 0; i < totalRayNumber; i++) {
1145 if (allVerticesAngleData[i].mIsPenumbra == true) {
1146 if (allVerticesAngleData[i].mVertexIndex != currentPenumbraVertexIndex) {
1147 ALOGW("wrong penumbra indexing i %d allVerticesAngleData[i].mVertexIndex %d "
1148 "currentpenumbraVertexIndex %d", i,
1149 allVerticesAngleData[i].mVertexIndex, currentPenumbraVertexIndex);
1150 }
1151 currentPenumbraVertexIndex = (currentPenumbraVertexIndex + 1) % penumbraLength;
1152 } else {
1153 if (allVerticesAngleData[i].mVertexIndex != currentUmbraVertexIndex) {
1154 ALOGW("wrong umbra indexing i %d allVerticesAngleData[i].mVertexIndex %d "
1155 "currentUmbraVertexIndex %d", i,
1156 allVerticesAngleData[i].mVertexIndex, currentUmbraVertexIndex);
1157 }
1158 currentUmbraVertexIndex = (currentUmbraVertexIndex + 1) % umbraLength;
1159 }
1160 }
1161 for (int i = 0; i < totalRayNumber - 1; i++) {
1162 float currentAngle = allVerticesAngleData[i].mAngle;
1163 float nextAngle = allVerticesAngleData[(i + 1) % totalRayNumber].mAngle;
1164 if (currentAngle < nextAngle) {
1165 ALOGE("Unexpected angle values!, currentAngle nextAngle %f %f", currentAngle, nextAngle);
1166 }
1167 }
1168}
1169#endif
1170
1171/**
1172 * In order to compute the occluded umbra, we need to setup the angle data list
1173 * for the polygon data. Since we only store one poly vertex per polygon vertex,
1174 * this array only needs to be a float array which are the angles for each vertex.
1175 *
1176 * @param polyAngleList The result list
1177 *
1178 * @return int The index for the maximum angle in this array.
1179 */
1180int SpotShadow::setupPolyAngleList(float* polyAngleList, int polyAngleLength,
1181 const Vector2* poly2d, const Vector2& centroid) {
1182 int maxPolyAngleIndex = -1;
1183 float maxPolyAngle = -FLT_MAX;
1184 for (int i = 0; i < polyAngleLength; i++) {
1185 polyAngleList[i] = angle(poly2d[i], centroid);
1186 if (polyAngleList[i] > maxPolyAngle) {
1187 maxPolyAngle = polyAngleList[i];
1188 maxPolyAngleIndex = i;
1189 }
1190 }
1191 return maxPolyAngleIndex;
1192}
1193
1194/**
1195 * For umbra and penumbra, given the offset info and the current ray number,
1196 * find the right edge index (the (starting vertex) for the ray to shoot at.
1197 *
1198 * @return int The index of the starting vertex of the edge.
1199 */
1200inline int SpotShadow::getEdgeStartIndex(const int* offsets, int rayIndex, int totalRayNumber,
1201 const VertexAngleData* allVerticesAngleData) {
1202 int tempOffset = offsets[rayIndex];
1203 int targetRayIndex = (rayIndex - tempOffset + totalRayNumber) % totalRayNumber;
1204 return allVerticesAngleData[targetRayIndex].mVertexIndex;
1205}
1206
1207/**
1208 * For the occluded umbra, given the array of angles, find the index of the
1209 * starting vertex of the edge, for the ray to shoo at.
1210 *
1211 * TODO: Save the last result to shorten the search distance.
1212 *
1213 * @return int The index of the starting vertex of the edge.
1214 */
1215inline int SpotShadow::getPolyEdgeStartIndex(int maxPolyAngleIndex, int polyLength,
1216 const float* polyAngleList, float rayAngle) {
1217 int minPolyAngleIndex = (maxPolyAngleIndex + polyLength - 1) % polyLength;
1218 int resultIndex = -1;
1219 if (rayAngle > polyAngleList[maxPolyAngleIndex]
1220 || rayAngle <= polyAngleList[minPolyAngleIndex]) {
1221 resultIndex = minPolyAngleIndex;
1222 } else {
1223 for (int i = 0; i < polyLength - 1; i++) {
1224 int currentIndex = (maxPolyAngleIndex + i) % polyLength;
1225 int nextIndex = (maxPolyAngleIndex + i + 1) % polyLength;
1226 if (rayAngle <= polyAngleList[currentIndex]
1227 && rayAngle > polyAngleList[nextIndex]) {
1228 resultIndex = currentIndex;
1229 }
1230 }
1231 }
1232 if (CC_UNLIKELY(resultIndex == -1)) {
1233 // TODO: Add more error handling here.
1234 ALOGE("Wrong index found, means no edge can't be found for rayAngle %f", rayAngle);
1235 }
1236 return resultIndex;
1237}
1238
1239/**
1240 * Convert the incoming polygons into arrays of vertices, for each ray.
1241 * Ray only shoots when there is one vertex either on penumbra on umbra.
1242 *
1243 * Finally, it will generate vertices per ray for umbra, penumbra and optionally
1244 * occludedUmbra.
1245 *
1246 * Return true (success) when all vertices are generated
1247 */
1248int SpotShadow::convertPolysToVerticesPerRay(
1249 bool hasOccludedUmbraArea, const Vector2* poly2d, int polyLength,
1250 const Vector2* umbra, int umbraLength, const Vector2* penumbra,
1251 int penumbraLength, const Vector2& centroid,
1252 Vector2* umbraVerticesPerRay, Vector2* penumbraVerticesPerRay,
1253 Vector2* occludedUmbraVerticesPerRay) {
1254 int totalRayNumber = umbraLength + penumbraLength;
1255
1256 // For incoming umbra / penumbra polygons, we will build an intermediate data
1257 // structure to help us sort all the vertices according to the vertices.
1258 // Using this data structure, we can tell where (the angle) to shoot the ray,
1259 // whether we shoot at penumbra edge or umbra edge, and which edge to shoot at.
1260 //
1261 // We first parse each vertices and generate a table of VertexAngleData.
1262 // Based on that, we create 2 arrays telling us which edge to shoot at.
1263 VertexAngleData allVerticesAngleData[totalRayNumber];
1264 VertexAngleData umbraAngleList[umbraLength];
1265 VertexAngleData penumbraAngleList[penumbraLength];
1266
1267 int polyAngleLength = hasOccludedUmbraArea ? polyLength : 0;
1268 float polyAngleList[polyAngleLength];
1269
1270 const int maxUmbraAngleIndex =
1271 setupAngleList(umbraAngleList, umbraLength, umbra, centroid, false, "umbra");
1272 const int maxPenumbraAngleIndex =
1273 setupAngleList(penumbraAngleList, penumbraLength, penumbra, centroid, true, "penumbra");
1274 const int maxPolyAngleIndex = setupPolyAngleList(polyAngleList, polyAngleLength, poly2d, centroid);
1275
1276 // Check all the polygons here are CW.
1277 bool isPolyCW = checkPolyClockwise(polyAngleLength, maxPolyAngleIndex, polyAngleList);
1278 bool isUmbraCW = checkClockwise(maxUmbraAngleIndex, umbraLength,
1279 umbraAngleList, "umbra");
1280 bool isPenumbraCW = checkClockwise(maxPenumbraAngleIndex, penumbraLength,
1281 penumbraAngleList, "penumbra");
1282
1283 if (!isUmbraCW || !isPenumbraCW || !isPolyCW) {
1284#if DEBUG_SHADOW
1285 ALOGE("One polygon is not CW isUmbraCW %d isPenumbraCW %d isPolyCW %d",
1286 isUmbraCW, isPenumbraCW, isPolyCW);
1287#endif
1288 return false;
1289 }
1290
1291 mergeAngleList(maxUmbraAngleIndex, maxPenumbraAngleIndex,
1292 umbraAngleList, umbraLength, penumbraAngleList, penumbraLength,
1293 allVerticesAngleData);
1294
1295 // Calculate the offset to the left most Inner vertex for each outerVertex.
1296 // Then the offset to the left most Outer vertex for each innerVertex.
1297 int offsetToInner[totalRayNumber];
1298 int offsetToOuter[totalRayNumber];
1299 calculateDistanceCounter(true, totalRayNumber, allVerticesAngleData, offsetToInner);
1300 calculateDistanceCounter(false, totalRayNumber, allVerticesAngleData, offsetToOuter);
1301
1302 // Generate both umbraVerticesPerRay and penumbraVerticesPerRay
1303 for (int i = 0; i < totalRayNumber; i++) {
1304 float rayAngle = allVerticesAngleData[i].mAngle;
1305 bool isUmbraVertex = !allVerticesAngleData[i].mIsPenumbra;
1306
1307 float dx = cosf(rayAngle);
1308 float dy = sinf(rayAngle);
1309 float distanceToIntersectUmbra = -1;
1310
1311 if (isUmbraVertex) {
1312 // We can just copy umbra easily, and calculate the distance for the
1313 // occluded umbra computation.
1314 int startUmbraIndex = allVerticesAngleData[i].mVertexIndex;
1315 umbraVerticesPerRay[i] = umbra[startUmbraIndex];
1316 if (hasOccludedUmbraArea) {
1317 distanceToIntersectUmbra = (umbraVerticesPerRay[i] - centroid).length();
1318 }
1319
1320 //shoot ray to penumbra only
1321 int startPenumbraIndex = getEdgeStartIndex(offsetToOuter, i, totalRayNumber,
1322 allVerticesAngleData);
1323 float distanceToIntersectPenumbra = rayIntersectPoints(centroid, dx, dy,
1324 penumbra[startPenumbraIndex],
1325 penumbra[(startPenumbraIndex + 1) % penumbraLength]);
1326 if (distanceToIntersectPenumbra < 0) {
1327#if DEBUG_SHADOW
1328 ALOGW("convertPolyToRayDist for penumbra failed rayAngle %f dx %f dy %f",
1329 rayAngle, dx, dy);
1330#endif
1331 distanceToIntersectPenumbra = 0;
1332 }
1333 penumbraVerticesPerRay[i].x = centroid.x + dx * distanceToIntersectPenumbra;
1334 penumbraVerticesPerRay[i].y = centroid.y + dy * distanceToIntersectPenumbra;
1335 } else {
1336 // We can just copy the penumbra
1337 int startPenumbraIndex = allVerticesAngleData[i].mVertexIndex;
1338 penumbraVerticesPerRay[i] = penumbra[startPenumbraIndex];
1339
1340 // And shoot ray to umbra only
1341 int startUmbraIndex = getEdgeStartIndex(offsetToInner, i, totalRayNumber,
1342 allVerticesAngleData);
1343
1344 distanceToIntersectUmbra = rayIntersectPoints(centroid, dx, dy,
1345 umbra[startUmbraIndex], umbra[(startUmbraIndex + 1) % umbraLength]);
1346 if (distanceToIntersectUmbra < 0) {
1347#if DEBUG_SHADOW
1348 ALOGW("convertPolyToRayDist for umbra failed rayAngle %f dx %f dy %f",
1349 rayAngle, dx, dy);
1350#endif
1351 distanceToIntersectUmbra = 0;
1352 }
1353 umbraVerticesPerRay[i].x = centroid.x + dx * distanceToIntersectUmbra;
1354 umbraVerticesPerRay[i].y = centroid.y + dy * distanceToIntersectUmbra;
1355 }
1356
1357 if (hasOccludedUmbraArea) {
1358 // Shoot the same ray to the poly2d, and get the distance.
1359 int startPolyIndex = getPolyEdgeStartIndex(maxPolyAngleIndex, polyLength,
1360 polyAngleList, rayAngle);
1361
1362 float distanceToIntersectPoly = rayIntersectPoints(centroid, dx, dy,
1363 poly2d[startPolyIndex], poly2d[(startPolyIndex + 1) % polyLength]);
1364 if (distanceToIntersectPoly < 0) {
1365 distanceToIntersectPoly = 0;
1366 }
1367 distanceToIntersectPoly = MathUtils::min(distanceToIntersectUmbra, distanceToIntersectPoly);
1368 occludedUmbraVerticesPerRay[i].x = centroid.x + dx * distanceToIntersectPoly;
1369 occludedUmbraVerticesPerRay[i].y = centroid.y + dy * distanceToIntersectPoly;
1370 }
1371 }
1372
1373#if DEBUG_SHADOW
1374 verifyAngleData(totalRayNumber, allVerticesAngleData, offsetToInner,
1375 offsetToOuter, umbraAngleList, maxUmbraAngleIndex, umbraLength,
1376 penumbraAngleList, maxPenumbraAngleIndex, penumbraLength);
1377#endif
1378 return true; // success
1379
1380}
1381
1382/**
1383 * Generate a triangle strip given two convex polygon
1384**/
Andreas Gampe42ddc182014-11-21 09:49:08 -08001385void SpotShadow::generateTriangleStrip(bool isCasterOpaque, float /* shadowStrengthScale */,
ztenghui512e6432014-09-10 13:08:20 -07001386 Vector2* penumbra, int penumbraLength, Vector2* umbra, int umbraLength,
1387 const Vector3* poly, int polyLength, VertexBuffer& shadowTriangleStrip,
1388 const Vector2& centroid) {
1389
1390 bool hasOccludedUmbraArea = false;
1391 Vector2 poly2d[polyLength];
1392
1393 if (isCasterOpaque) {
1394 for (int i = 0; i < polyLength; i++) {
1395 poly2d[i].x = poly[i].x;
1396 poly2d[i].y = poly[i].y;
1397 }
1398 // Make sure the centroid is inside the umbra, otherwise, fall back to the
1399 // approach as if there is no occluded umbra area.
1400 if (testPointInsidePolygon(centroid, poly2d, polyLength)) {
1401 hasOccludedUmbraArea = true;
1402 }
1403 }
1404
1405 int totalRayNum = umbraLength + penumbraLength;
1406 Vector2 umbraVertices[totalRayNum];
1407 Vector2 penumbraVertices[totalRayNum];
1408 Vector2 occludedUmbraVertices[totalRayNum];
1409 bool convertSuccess = convertPolysToVerticesPerRay(hasOccludedUmbraArea, poly2d,
1410 polyLength, umbra, umbraLength, penumbra, penumbraLength,
1411 centroid, umbraVertices, penumbraVertices, occludedUmbraVertices);
1412 if (!convertSuccess) {
1413 return;
1414 }
1415
1416 // Minimal value is 1, for each vertex show up once.
1417 // The bigger this value is , the smoother the look is, but more memory
1418 // is consumed.
1419 // When the ray number is high, that means the polygon has been fine
1420 // tessellated, we don't need this extra slice, just keep it as 1.
1421 int sliceNumberPerEdge = (totalRayNum > FINE_TESSELLATED_POLYGON_RAY_NUMBER) ? 1 : 2;
1422
1423 // For each polygon, we at most add (totalRayNum * sliceNumberPerEdge) vertices.
1424 int slicedVertexCountPerPolygon = totalRayNum * sliceNumberPerEdge;
1425 int totalVertexCount = slicedVertexCountPerPolygon * 2 + totalRayNum;
1426 int totalIndexCount = 2 * (slicedVertexCountPerPolygon * 2 + 2);
1427 AlphaVertex* shadowVertices =
1428 shadowTriangleStrip.alloc<AlphaVertex>(totalVertexCount);
1429 uint16_t* indexBuffer =
1430 shadowTriangleStrip.allocIndices<uint16_t>(totalIndexCount);
1431
1432 int indexBufferIndex = 0;
1433 int vertexBufferIndex = 0;
1434
1435 uint16_t slicedUmbraVertexIndex[totalRayNum * sliceNumberPerEdge];
1436 // Should be something like 0 0 0 1 1 1 2 3 3 3...
1437 int rayNumberPerSlicedUmbra[totalRayNum * sliceNumberPerEdge];
1438 int realUmbraVertexCount = 0;
1439 for (int i = 0; i < totalRayNum; i++) {
1440 Vector2 currentPenumbra = penumbraVertices[i];
1441 Vector2 currentUmbra = umbraVertices[i];
1442
1443 Vector2 nextPenumbra = penumbraVertices[(i + 1) % totalRayNum];
1444 Vector2 nextUmbra = umbraVertices[(i + 1) % totalRayNum];
1445 // NextUmbra/Penumbra will be done in the next loop!!
1446 for (int weight = 0; weight < sliceNumberPerEdge; weight++) {
1447 const Vector2& slicedPenumbra = (currentPenumbra * (sliceNumberPerEdge - weight)
1448 + nextPenumbra * weight) / sliceNumberPerEdge;
1449
1450 const Vector2& slicedUmbra = (currentUmbra * (sliceNumberPerEdge - weight)
1451 + nextUmbra * weight) / sliceNumberPerEdge;
1452
1453 // In the vertex buffer, we fill the Penumbra first, then umbra.
1454 indexBuffer[indexBufferIndex++] = vertexBufferIndex;
1455 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], slicedPenumbra.x,
1456 slicedPenumbra.y, 0.0f);
1457
1458 // When we add umbra vertex, we need to remember its current ray number.
1459 // And its own vertexBufferIndex. This is for occluded umbra usage.
1460 indexBuffer[indexBufferIndex++] = vertexBufferIndex;
1461 rayNumberPerSlicedUmbra[realUmbraVertexCount] = i;
1462 slicedUmbraVertexIndex[realUmbraVertexCount] = vertexBufferIndex;
1463 realUmbraVertexCount++;
1464 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], slicedUmbra.x,
1465 slicedUmbra.y, M_PI);
1466 }
1467 }
1468
1469 indexBuffer[indexBufferIndex++] = 0;
1470 //RealUmbraVertexIndex[0] must be 1, so we connect back well at the
1471 //beginning of occluded area.
1472 indexBuffer[indexBufferIndex++] = 1;
1473
1474 float occludedUmbraAlpha = M_PI;
1475 if (hasOccludedUmbraArea) {
1476 // Now the occludedUmbra area;
1477 int currentRayNumber = -1;
1478 int firstOccludedUmbraIndex = -1;
1479 for (int i = 0; i < realUmbraVertexCount; i++) {
1480 indexBuffer[indexBufferIndex++] = slicedUmbraVertexIndex[i];
1481
1482 // If the occludedUmbra vertex has not been added yet, then add it.
1483 // Otherwise, just use the previously added occludedUmbra vertices.
1484 if (rayNumberPerSlicedUmbra[i] != currentRayNumber) {
1485 currentRayNumber++;
1486 indexBuffer[indexBufferIndex++] = vertexBufferIndex;
1487 // We need to remember the begining of the occludedUmbra vertices
1488 // to close this loop.
1489 if (currentRayNumber == 0) {
1490 firstOccludedUmbraIndex = vertexBufferIndex;
1491 }
1492 AlphaVertex::set(&shadowVertices[vertexBufferIndex++],
1493 occludedUmbraVertices[currentRayNumber].x,
1494 occludedUmbraVertices[currentRayNumber].y,
1495 occludedUmbraAlpha);
1496 } else {
1497 indexBuffer[indexBufferIndex++] = (vertexBufferIndex - 1);
1498 }
1499 }
1500 // Close the loop here!
1501 indexBuffer[indexBufferIndex++] = slicedUmbraVertexIndex[0];
1502 indexBuffer[indexBufferIndex++] = firstOccludedUmbraIndex;
1503 } else {
1504 int lastCentroidIndex = vertexBufferIndex;
1505 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], centroid.x,
1506 centroid.y, occludedUmbraAlpha);
1507 for (int i = 0; i < realUmbraVertexCount; i++) {
1508 indexBuffer[indexBufferIndex++] = slicedUmbraVertexIndex[i];
1509 indexBuffer[indexBufferIndex++] = lastCentroidIndex;
1510 }
1511 // Close the loop here!
1512 indexBuffer[indexBufferIndex++] = slicedUmbraVertexIndex[0];
1513 indexBuffer[indexBufferIndex++] = lastCentroidIndex;
1514 }
1515
1516#if DEBUG_SHADOW
1517 ALOGD("allocated IB %d allocated VB is %d", totalIndexCount, totalVertexCount);
1518 ALOGD("IB index %d VB index is %d", indexBufferIndex, vertexBufferIndex);
1519 for (int i = 0; i < vertexBufferIndex; i++) {
1520 ALOGD("vertexBuffer i %d, (%f, %f %f)", i, shadowVertices[i].x, shadowVertices[i].y,
1521 shadowVertices[i].alpha);
1522 }
1523 for (int i = 0; i < indexBufferIndex; i++) {
1524 ALOGD("indexBuffer i %d, indexBuffer[i] %d", i, indexBuffer[i]);
1525 }
1526#endif
1527
1528 // At the end, update the real index and vertex buffer size.
1529 shadowTriangleStrip.updateVertexCount(vertexBufferIndex);
1530 shadowTriangleStrip.updateIndexCount(indexBufferIndex);
1531 ShadowTessellator::checkOverflow(vertexBufferIndex, totalVertexCount, "Spot Vertex Buffer");
1532 ShadowTessellator::checkOverflow(indexBufferIndex, totalIndexCount, "Spot Index Buffer");
1533
1534 shadowTriangleStrip.setMode(VertexBuffer::kIndices);
1535 shadowTriangleStrip.computeBounds<AlphaVertex>();
1536}
1537
ztenghuif5ca8b42014-01-27 15:53:28 -08001538#if DEBUG_SHADOW
1539
1540#define TEST_POINT_NUMBER 128
ztenghuif5ca8b42014-01-27 15:53:28 -08001541/**
1542 * Calculate the bounds for generating random test points.
1543 */
1544void SpotShadow::updateBound(const Vector2 inVector, Vector2& lowerBound,
ztenghui512e6432014-09-10 13:08:20 -07001545 Vector2& upperBound) {
ztenghuif5ca8b42014-01-27 15:53:28 -08001546 if (inVector.x < lowerBound.x) {
1547 lowerBound.x = inVector.x;
1548 }
1549
1550 if (inVector.y < lowerBound.y) {
1551 lowerBound.y = inVector.y;
1552 }
1553
1554 if (inVector.x > upperBound.x) {
1555 upperBound.x = inVector.x;
1556 }
1557
1558 if (inVector.y > upperBound.y) {
1559 upperBound.y = inVector.y;
1560 }
1561}
1562
1563/**
1564 * For debug purpose, when things go wrong, dump the whole polygon data.
1565 */
ztenghuic50a03d2014-08-21 13:47:54 -07001566void SpotShadow::dumpPolygon(const Vector2* poly, int polyLength, const char* polyName) {
1567 for (int i = 0; i < polyLength; i++) {
1568 ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
1569 }
1570}
1571
1572/**
1573 * For debug purpose, when things go wrong, dump the whole polygon data.
1574 */
1575void SpotShadow::dumpPolygon(const Vector3* poly, int polyLength, const char* polyName) {
ztenghuif5ca8b42014-01-27 15:53:28 -08001576 for (int i = 0; i < polyLength; i++) {
1577 ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
1578 }
1579}
1580
1581/**
1582 * Test whether the polygon is convex.
1583 */
1584bool SpotShadow::testConvex(const Vector2* polygon, int polygonLength,
1585 const char* name) {
1586 bool isConvex = true;
1587 for (int i = 0; i < polygonLength; i++) {
1588 Vector2 start = polygon[i];
1589 Vector2 middle = polygon[(i + 1) % polygonLength];
1590 Vector2 end = polygon[(i + 2) % polygonLength];
1591
1592 double delta = (double(middle.x) - start.x) * (double(end.y) - start.y) -
1593 (double(middle.y) - start.y) * (double(end.x) - start.x);
1594 bool isCCWOrCoLinear = (delta >= EPSILON);
1595
1596 if (isCCWOrCoLinear) {
ztenghui50ecf842014-03-11 16:52:30 -07001597 ALOGW("(Error Type 2): polygon (%s) is not a convex b/c start (x %f, y %f),"
ztenghuif5ca8b42014-01-27 15:53:28 -08001598 "middle (x %f, y %f) and end (x %f, y %f) , delta is %f !!!",
1599 name, start.x, start.y, middle.x, middle.y, end.x, end.y, delta);
1600 isConvex = false;
1601 break;
1602 }
1603 }
1604 return isConvex;
1605}
1606
1607/**
1608 * Test whether or not the polygon (intersection) is within the 2 input polygons.
1609 * Using Marte Carlo method, we generate a random point, and if it is inside the
1610 * intersection, then it must be inside both source polygons.
1611 */
1612void SpotShadow::testIntersection(const Vector2* poly1, int poly1Length,
1613 const Vector2* poly2, int poly2Length,
1614 const Vector2* intersection, int intersectionLength) {
1615 // Find the min and max of x and y.
ztenghuic50a03d2014-08-21 13:47:54 -07001616 Vector2 lowerBound = {FLT_MAX, FLT_MAX};
1617 Vector2 upperBound = {-FLT_MAX, -FLT_MAX};
ztenghuif5ca8b42014-01-27 15:53:28 -08001618 for (int i = 0; i < poly1Length; i++) {
1619 updateBound(poly1[i], lowerBound, upperBound);
1620 }
1621 for (int i = 0; i < poly2Length; i++) {
1622 updateBound(poly2[i], lowerBound, upperBound);
1623 }
1624
1625 bool dumpPoly = false;
1626 for (int k = 0; k < TEST_POINT_NUMBER; k++) {
1627 // Generate a random point between minX, minY and maxX, maxY.
1628 double randomX = rand() / double(RAND_MAX);
1629 double randomY = rand() / double(RAND_MAX);
1630
1631 Vector2 testPoint;
1632 testPoint.x = lowerBound.x + randomX * (upperBound.x - lowerBound.x);
1633 testPoint.y = lowerBound.y + randomY * (upperBound.y - lowerBound.y);
1634
1635 // If the random point is in both poly 1 and 2, then it must be intersection.
1636 if (testPointInsidePolygon(testPoint, intersection, intersectionLength)) {
1637 if (!testPointInsidePolygon(testPoint, poly1, poly1Length)) {
1638 dumpPoly = true;
ztenghui50ecf842014-03-11 16:52:30 -07001639 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
ztenghui512e6432014-09-10 13:08:20 -07001640 " not in the poly1",
ztenghuif5ca8b42014-01-27 15:53:28 -08001641 testPoint.x, testPoint.y);
1642 }
1643
1644 if (!testPointInsidePolygon(testPoint, poly2, poly2Length)) {
1645 dumpPoly = true;
ztenghui50ecf842014-03-11 16:52:30 -07001646 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
ztenghui512e6432014-09-10 13:08:20 -07001647 " not in the poly2",
ztenghuif5ca8b42014-01-27 15:53:28 -08001648 testPoint.x, testPoint.y);
1649 }
1650 }
1651 }
1652
1653 if (dumpPoly) {
1654 dumpPolygon(intersection, intersectionLength, "intersection");
1655 for (int i = 1; i < intersectionLength; i++) {
1656 Vector2 delta = intersection[i] - intersection[i - 1];
1657 ALOGD("Intersetion i, %d Vs i-1 is delta %f", i, delta.lengthSquared());
1658 }
1659
1660 dumpPolygon(poly1, poly1Length, "poly 1");
1661 dumpPolygon(poly2, poly2Length, "poly 2");
1662 }
1663}
1664#endif
1665
ztenghui7b4516e2014-01-07 10:42:55 -08001666}; // namespace uirenderer
1667}; // namespace android