blob: 8538b295c86ea2e593541b6e4a3d634a5f76129f [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
19#define SHADOW_SHRINK_SCALE 0.1f
20
21#include <math.h>
ztenghuif5ca8b42014-01-27 15:53:28 -080022#include <stdlib.h>
ztenghui7b4516e2014-01-07 10:42:55 -080023#include <utils/Log.h>
24
ztenghui63d41ab2014-02-14 13:13:41 -080025#include "ShadowTessellator.h"
ztenghui7b4516e2014-01-07 10:42:55 -080026#include "SpotShadow.h"
27#include "Vertex.h"
28
29namespace android {
30namespace uirenderer {
31
Chris Craik726118b2014-03-07 18:27:49 -080032static const double EPSILON = 1e-7;
33
ztenghui7b4516e2014-01-07 10:42:55 -080034/**
Chris Craik726118b2014-03-07 18:27:49 -080035 * Calculate the angle between and x and a y coordinate.
36 * The atan2 range from -PI to PI.
ztenghui7b4516e2014-01-07 10:42:55 -080037 */
Chris Craikb79a3e32014-03-11 12:20:17 -070038static float angle(const Vector2& point, const Vector2& center) {
Chris Craik726118b2014-03-07 18:27:49 -080039 return atan2(point.y - center.y, point.x - center.x);
40}
41
42/**
43 * Calculate the intersection of a ray with the line segment defined by two points.
44 *
45 * Returns a negative value in error conditions.
46
47 * @param rayOrigin The start of the ray
48 * @param dx The x vector of the ray
49 * @param dy The y vector of the ray
50 * @param p1 The first point defining the line segment
51 * @param p2 The second point defining the line segment
52 * @return The distance along the ray if it intersects with the line segment, negative if otherwise
53 */
Chris Craikb79a3e32014-03-11 12:20:17 -070054static float rayIntersectPoints(const Vector2& rayOrigin, float dx, float dy,
Chris Craik726118b2014-03-07 18:27:49 -080055 const Vector2& p1, const Vector2& p2) {
56 // The math below is derived from solving this formula, basically the
57 // intersection point should stay on both the ray and the edge of (p1, p2).
58 // solve([p1x+t*(p2x-p1x)=dx*t2+px,p1y+t*(p2y-p1y)=dy*t2+py],[t,t2]);
59
60 double divisor = (dx * (p1.y - p2.y) + dy * p2.x - dy * p1.x);
61 if (divisor == 0) return -1.0f; // error, invalid divisor
62
63#if DEBUG_SHADOW
64 double interpVal = (dx * (p1.y - rayOrigin.y) + dy * rayOrigin.x - dy * p1.x) / divisor;
65 if (interpVal < 0 || interpVal > 1) return -1.0f; // error, doesn't intersect between points
66#endif
67
68 double distance = (p1.x * (rayOrigin.y - p2.y) + p2.x * (p1.y - rayOrigin.y) +
69 rayOrigin.x * (p2.y - p1.y)) / divisor;
70
71 return distance; // may be negative in error cases
ztenghui7b4516e2014-01-07 10:42:55 -080072}
73
74/**
ztenghui7b4516e2014-01-07 10:42:55 -080075 * Sort points by their X coordinates
76 *
77 * @param points the points as a Vector2 array.
78 * @param pointsLength the number of vertices of the polygon.
79 */
80void SpotShadow::xsort(Vector2* points, int pointsLength) {
81 quicksortX(points, 0, pointsLength - 1);
82}
83
84/**
85 * compute the convex hull of a collection of Points
86 *
87 * @param points the points as a Vector2 array.
88 * @param pointsLength the number of vertices of the polygon.
89 * @param retPoly pre allocated array of floats to put the vertices
90 * @return the number of points in the polygon 0 if no intersection
91 */
92int SpotShadow::hull(Vector2* points, int pointsLength, Vector2* retPoly) {
93 xsort(points, pointsLength);
94 int n = pointsLength;
95 Vector2 lUpper[n];
96 lUpper[0] = points[0];
97 lUpper[1] = points[1];
98
99 int lUpperSize = 2;
100
101 for (int i = 2; i < n; i++) {
102 lUpper[lUpperSize] = points[i];
103 lUpperSize++;
104
ztenghuif5ca8b42014-01-27 15:53:28 -0800105 while (lUpperSize > 2 && !ccw(
106 lUpper[lUpperSize - 3].x, lUpper[lUpperSize - 3].y,
107 lUpper[lUpperSize - 2].x, lUpper[lUpperSize - 2].y,
108 lUpper[lUpperSize - 1].x, lUpper[lUpperSize - 1].y)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800109 // Remove the middle point of the three last
110 lUpper[lUpperSize - 2].x = lUpper[lUpperSize - 1].x;
111 lUpper[lUpperSize - 2].y = lUpper[lUpperSize - 1].y;
112 lUpperSize--;
113 }
114 }
115
116 Vector2 lLower[n];
117 lLower[0] = points[n - 1];
118 lLower[1] = points[n - 2];
119
120 int lLowerSize = 2;
121
122 for (int i = n - 3; i >= 0; i--) {
123 lLower[lLowerSize] = points[i];
124 lLowerSize++;
125
ztenghuif5ca8b42014-01-27 15:53:28 -0800126 while (lLowerSize > 2 && !ccw(
127 lLower[lLowerSize - 3].x, lLower[lLowerSize - 3].y,
128 lLower[lLowerSize - 2].x, lLower[lLowerSize - 2].y,
129 lLower[lLowerSize - 1].x, lLower[lLowerSize - 1].y)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800130 // Remove the middle point of the three last
131 lLower[lLowerSize - 2] = lLower[lLowerSize - 1];
132 lLowerSize--;
133 }
134 }
ztenghui7b4516e2014-01-07 10:42:55 -0800135
Chris Craik726118b2014-03-07 18:27:49 -0800136 // output points in CW ordering
137 const int total = lUpperSize + lLowerSize - 2;
138 int outIndex = total - 1;
ztenghui7b4516e2014-01-07 10:42:55 -0800139 for (int i = 0; i < lUpperSize; i++) {
Chris Craik726118b2014-03-07 18:27:49 -0800140 retPoly[outIndex] = lUpper[i];
141 outIndex--;
ztenghui7b4516e2014-01-07 10:42:55 -0800142 }
143
144 for (int i = 1; i < lLowerSize - 1; i++) {
Chris Craik726118b2014-03-07 18:27:49 -0800145 retPoly[outIndex] = lLower[i];
146 outIndex--;
ztenghui7b4516e2014-01-07 10:42:55 -0800147 }
148 // TODO: Add test harness which verify that all the points are inside the hull.
Chris Craik726118b2014-03-07 18:27:49 -0800149 return total;
ztenghui7b4516e2014-01-07 10:42:55 -0800150}
151
152/**
ztenghuif5ca8b42014-01-27 15:53:28 -0800153 * Test whether the 3 points form a counter clockwise turn.
ztenghui7b4516e2014-01-07 10:42:55 -0800154 *
ztenghui7b4516e2014-01-07 10:42:55 -0800155 * @return true if a right hand turn
156 */
ztenghuif5ca8b42014-01-27 15:53:28 -0800157bool SpotShadow::ccw(double ax, double ay, double bx, double by,
ztenghui7b4516e2014-01-07 10:42:55 -0800158 double cx, double cy) {
159 return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > EPSILON;
160}
161
162/**
163 * Calculates the intersection of poly1 with poly2 and put in poly2.
164 *
165 *
166 * @param poly1 The 1st polygon, as a Vector2 array.
167 * @param poly1Length The number of vertices of 1st polygon.
168 * @param poly2 The 2nd and output polygon, as a Vector2 array.
169 * @param poly2Length The number of vertices of 2nd polygon.
170 * @return number of vertices in output polygon as poly2.
171 */
172int SpotShadow::intersection(Vector2* poly1, int poly1Length,
173 Vector2* poly2, int poly2Length) {
174 makeClockwise(poly1, poly1Length);
175 makeClockwise(poly2, poly2Length);
ztenghuif5ca8b42014-01-27 15:53:28 -0800176
ztenghui7b4516e2014-01-07 10:42:55 -0800177 Vector2 poly[poly1Length * poly2Length + 2];
178 int count = 0;
179 int pcount = 0;
180
181 // If one vertex from one polygon sits inside another polygon, add it and
182 // count them.
183 for (int i = 0; i < poly1Length; i++) {
184 if (testPointInsidePolygon(poly1[i], poly2, poly2Length)) {
185 poly[count] = poly1[i];
186 count++;
187 pcount++;
188
189 }
190 }
191
192 int insidePoly2 = pcount;
193 for (int i = 0; i < poly2Length; i++) {
194 if (testPointInsidePolygon(poly2[i], poly1, poly1Length)) {
195 poly[count] = poly2[i];
196 count++;
197 }
198 }
199
200 int insidePoly1 = count - insidePoly2;
201 // If all vertices from poly1 are inside poly2, then just return poly1.
202 if (insidePoly2 == poly1Length) {
203 memcpy(poly2, poly1, poly1Length * sizeof(Vector2));
204 return poly1Length;
205 }
206
207 // If all vertices from poly2 are inside poly1, then just return poly2.
208 if (insidePoly1 == poly2Length) {
209 return poly2Length;
210 }
211
212 // Since neither polygon fully contain the other one, we need to add all the
213 // intersection points.
214 Vector2 intersection;
215 for (int i = 0; i < poly2Length; i++) {
216 for (int j = 0; j < poly1Length; j++) {
217 int poly2LineStart = i;
218 int poly2LineEnd = ((i + 1) % poly2Length);
219 int poly1LineStart = j;
220 int poly1LineEnd = ((j + 1) % poly1Length);
221 bool found = lineIntersection(
222 poly2[poly2LineStart].x, poly2[poly2LineStart].y,
223 poly2[poly2LineEnd].x, poly2[poly2LineEnd].y,
224 poly1[poly1LineStart].x, poly1[poly1LineStart].y,
225 poly1[poly1LineEnd].x, poly1[poly1LineEnd].y,
226 intersection);
227 if (found) {
228 poly[count].x = intersection.x;
229 poly[count].y = intersection.y;
230 count++;
231 } else {
232 Vector2 delta = poly2[i] - poly1[j];
ztenghuif5ca8b42014-01-27 15:53:28 -0800233 if (delta.lengthSquared() < EPSILON) {
ztenghui7b4516e2014-01-07 10:42:55 -0800234 poly[count] = poly2[i];
235 count++;
236 }
237 }
238 }
239 }
240
241 if (count == 0) {
242 return 0;
243 }
244
245 // Sort the result polygon around the center.
246 Vector2 center(0.0f, 0.0f);
247 for (int i = 0; i < count; i++) {
248 center += poly[i];
249 }
250 center /= count;
251 sort(poly, count, center);
252
ztenghuif5ca8b42014-01-27 15:53:28 -0800253#if DEBUG_SHADOW
254 // Since poly2 is overwritten as the result, we need to save a copy to do
255 // our verification.
256 Vector2 oldPoly2[poly2Length];
257 int oldPoly2Length = poly2Length;
258 memcpy(oldPoly2, poly2, sizeof(Vector2) * poly2Length);
259#endif
ztenghui7b4516e2014-01-07 10:42:55 -0800260
ztenghuif5ca8b42014-01-27 15:53:28 -0800261 // Filter the result out from poly and put it into poly2.
ztenghui7b4516e2014-01-07 10:42:55 -0800262 poly2[0] = poly[0];
ztenghuif5ca8b42014-01-27 15:53:28 -0800263 int lastOutputIndex = 0;
ztenghui7b4516e2014-01-07 10:42:55 -0800264 for (int i = 1; i < count; i++) {
ztenghuif5ca8b42014-01-27 15:53:28 -0800265 Vector2 delta = poly[i] - poly2[lastOutputIndex];
266 if (delta.lengthSquared() >= EPSILON) {
267 poly2[++lastOutputIndex] = poly[i];
268 } else {
269 // If the vertices are too close, pick the inner one, because the
270 // inner one is more likely to be an intersection point.
271 Vector2 delta1 = poly[i] - center;
272 Vector2 delta2 = poly2[lastOutputIndex] - center;
273 if (delta1.lengthSquared() < delta2.lengthSquared()) {
274 poly2[lastOutputIndex] = poly[i];
275 }
ztenghui7b4516e2014-01-07 10:42:55 -0800276 }
277 }
ztenghuif5ca8b42014-01-27 15:53:28 -0800278 int resultLength = lastOutputIndex + 1;
279
280#if DEBUG_SHADOW
281 testConvex(poly2, resultLength, "intersection");
282 testConvex(poly1, poly1Length, "input poly1");
283 testConvex(oldPoly2, oldPoly2Length, "input poly2");
284
285 testIntersection(poly1, poly1Length, oldPoly2, oldPoly2Length, poly2, resultLength);
286#endif
ztenghui7b4516e2014-01-07 10:42:55 -0800287
288 return resultLength;
289}
290
291/**
292 * Sort points about a center point
293 *
294 * @param poly The in and out polyogon as a Vector2 array.
295 * @param polyLength The number of vertices of the polygon.
296 * @param center the center ctr[0] = x , ctr[1] = y to sort around.
297 */
298void SpotShadow::sort(Vector2* poly, int polyLength, const Vector2& center) {
299 quicksortCirc(poly, 0, polyLength - 1, center);
300}
301
302/**
ztenghui7b4516e2014-01-07 10:42:55 -0800303 * Swap points pointed to by i and j
304 */
305void SpotShadow::swap(Vector2* points, int i, int j) {
306 Vector2 temp = points[i];
307 points[i] = points[j];
308 points[j] = temp;
309}
310
311/**
312 * quick sort implementation about the center.
313 */
314void SpotShadow::quicksortCirc(Vector2* points, int low, int high,
315 const Vector2& center) {
316 int i = low, j = high;
317 int p = low + (high - low) / 2;
318 float pivot = angle(points[p], center);
319 while (i <= j) {
Chris Craik726118b2014-03-07 18:27:49 -0800320 while (angle(points[i], center) > pivot) {
ztenghui7b4516e2014-01-07 10:42:55 -0800321 i++;
322 }
Chris Craik726118b2014-03-07 18:27:49 -0800323 while (angle(points[j], center) < pivot) {
ztenghui7b4516e2014-01-07 10:42:55 -0800324 j--;
325 }
326
327 if (i <= j) {
328 swap(points, i, j);
329 i++;
330 j--;
331 }
332 }
333 if (low < j) quicksortCirc(points, low, j, center);
334 if (i < high) quicksortCirc(points, i, high, center);
335}
336
337/**
338 * Sort points by x axis
339 *
340 * @param points points to sort
341 * @param low start index
342 * @param high end index
343 */
344void SpotShadow::quicksortX(Vector2* points, int low, int high) {
345 int i = low, j = high;
346 int p = low + (high - low) / 2;
347 float pivot = points[p].x;
348 while (i <= j) {
349 while (points[i].x < pivot) {
350 i++;
351 }
352 while (points[j].x > pivot) {
353 j--;
354 }
355
356 if (i <= j) {
357 swap(points, i, j);
358 i++;
359 j--;
360 }
361 }
362 if (low < j) quicksortX(points, low, j);
363 if (i < high) quicksortX(points, i, high);
364}
365
366/**
367 * Test whether a point is inside the polygon.
368 *
369 * @param testPoint the point to test
370 * @param poly the polygon
371 * @return true if the testPoint is inside the poly.
372 */
373bool SpotShadow::testPointInsidePolygon(const Vector2 testPoint,
374 const Vector2* poly, int len) {
375 bool c = false;
376 double testx = testPoint.x;
377 double testy = testPoint.y;
378 for (int i = 0, j = len - 1; i < len; j = i++) {
379 double startX = poly[j].x;
380 double startY = poly[j].y;
381 double endX = poly[i].x;
382 double endY = poly[i].y;
383
384 if (((endY > testy) != (startY > testy)) &&
385 (testx < (startX - endX) * (testy - endY)
386 / (startY - endY) + endX)) {
387 c = !c;
388 }
389 }
390 return c;
391}
392
393/**
394 * Make the polygon turn clockwise.
395 *
396 * @param polygon the polygon as a Vector2 array.
397 * @param len the number of points of the polygon
398 */
399void SpotShadow::makeClockwise(Vector2* polygon, int len) {
400 if (polygon == 0 || len == 0) {
401 return;
402 }
403 if (!isClockwise(polygon, len)) {
404 reverse(polygon, len);
405 }
406}
407
408/**
409 * Test whether the polygon is order in clockwise.
410 *
411 * @param polygon the polygon as a Vector2 array
412 * @param len the number of points of the polygon
413 */
414bool SpotShadow::isClockwise(Vector2* polygon, int len) {
415 double sum = 0;
416 double p1x = polygon[len - 1].x;
417 double p1y = polygon[len - 1].y;
418 for (int i = 0; i < len; i++) {
419
420 double p2x = polygon[i].x;
421 double p2y = polygon[i].y;
422 sum += p1x * p2y - p2x * p1y;
423 p1x = p2x;
424 p1y = p2y;
425 }
426 return sum < 0;
427}
428
429/**
430 * Reverse the polygon
431 *
432 * @param polygon the polygon as a Vector2 array
433 * @param len the number of points of the polygon
434 */
435void SpotShadow::reverse(Vector2* polygon, int len) {
436 int n = len / 2;
437 for (int i = 0; i < n; i++) {
438 Vector2 tmp = polygon[i];
439 int k = len - 1 - i;
440 polygon[i] = polygon[k];
441 polygon[k] = tmp;
442 }
443}
444
445/**
446 * Intersects two lines in parametric form. This function is called in a tight
447 * loop, and we need double precision to get things right.
448 *
449 * @param x1 the x coordinate point 1 of line 1
450 * @param y1 the y coordinate point 1 of line 1
451 * @param x2 the x coordinate point 2 of line 1
452 * @param y2 the y coordinate point 2 of line 1
453 * @param x3 the x coordinate point 1 of line 2
454 * @param y3 the y coordinate point 1 of line 2
455 * @param x4 the x coordinate point 2 of line 2
456 * @param y4 the y coordinate point 2 of line 2
457 * @param ret the x,y location of the intersection
458 * @return true if it found an intersection
459 */
460inline bool SpotShadow::lineIntersection(double x1, double y1, double x2, double y2,
461 double x3, double y3, double x4, double y4, Vector2& ret) {
462 double d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
463 if (d == 0.0) return false;
464
465 double dx = (x1 * y2 - y1 * x2);
466 double dy = (x3 * y4 - y3 * x4);
467 double x = (dx * (x3 - x4) - (x1 - x2) * dy) / d;
468 double y = (dx * (y3 - y4) - (y1 - y2) * dy) / d;
469
470 // The intersection should be in the middle of the point 1 and point 2,
471 // likewise point 3 and point 4.
472 if (((x - x1) * (x - x2) > EPSILON)
473 || ((x - x3) * (x - x4) > EPSILON)
474 || ((y - y1) * (y - y2) > EPSILON)
475 || ((y - y3) * (y - y4) > EPSILON)) {
476 // Not interesected
477 return false;
478 }
479 ret.x = x;
480 ret.y = y;
481 return true;
482
483}
484
485/**
486 * Compute a horizontal circular polygon about point (x , y , height) of radius
487 * (size)
488 *
489 * @param points number of the points of the output polygon.
490 * @param lightCenter the center of the light.
491 * @param size the light size.
492 * @param ret result polygon.
493 */
494void SpotShadow::computeLightPolygon(int points, const Vector3& lightCenter,
495 float size, Vector3* ret) {
496 // TODO: Caching all the sin / cos values and store them in a look up table.
497 for (int i = 0; i < points; i++) {
498 double angle = 2 * i * M_PI / points;
Chris Craik726118b2014-03-07 18:27:49 -0800499 ret[i].x = cosf(angle) * size + lightCenter.x;
500 ret[i].y = sinf(angle) * size + lightCenter.y;
ztenghui7b4516e2014-01-07 10:42:55 -0800501 ret[i].z = lightCenter.z;
502 }
503}
504
505/**
506* Generate the shadow from a spot light.
507*
508* @param poly x,y,z vertexes of a convex polygon that occludes the light source
509* @param polyLength number of vertexes of the occluding polygon
510* @param lightCenter the center of the light
511* @param lightSize the radius of the light source
512* @param lightVertexCount the vertex counter for the light polygon
ztenghui7b4516e2014-01-07 10:42:55 -0800513* @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
514* empty strip if error.
515*
516*/
517void SpotShadow::createSpotShadow(const Vector3* poly, int polyLength,
518 const Vector3& lightCenter, float lightSize, int lightVertexCount,
ztenghui63d41ab2014-02-14 13:13:41 -0800519 VertexBuffer& retStrips) {
ztenghui7b4516e2014-01-07 10:42:55 -0800520 Vector3 light[lightVertexCount * 3];
521 computeLightPolygon(lightVertexCount, lightCenter, lightSize, light);
ztenghui63d41ab2014-02-14 13:13:41 -0800522 computeSpotShadow(light, lightVertexCount, lightCenter, poly, polyLength,
523 retStrips);
ztenghui7b4516e2014-01-07 10:42:55 -0800524}
525
526/**
527 * Generate the shadow spot light of shape lightPoly and a object poly
528 *
529 * @param lightPoly x,y,z vertex of a convex polygon that is the light source
530 * @param lightPolyLength number of vertexes of the light source polygon
531 * @param poly x,y,z vertexes of a convex polygon that occludes the light source
532 * @param polyLength number of vertexes of the occluding polygon
ztenghui7b4516e2014-01-07 10:42:55 -0800533 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
534 * empty strip if error.
535 */
536void SpotShadow::computeSpotShadow(const Vector3* lightPoly, int lightPolyLength,
537 const Vector3& lightCenter, const Vector3* poly, int polyLength,
ztenghui63d41ab2014-02-14 13:13:41 -0800538 VertexBuffer& shadowTriangleStrip) {
ztenghui7b4516e2014-01-07 10:42:55 -0800539 // Point clouds for all the shadowed vertices
540 Vector2 shadowRegion[lightPolyLength * polyLength];
541 // Shadow polygon from one point light.
542 Vector2 outline[polyLength];
543 Vector2 umbraMem[polyLength * lightPolyLength];
544 Vector2* umbra = umbraMem;
545
546 int umbraLength = 0;
547
548 // Validate input, receiver is always at z = 0 plane.
549 bool inputPolyPositionValid = true;
550 for (int i = 0; i < polyLength; i++) {
ztenghui7b4516e2014-01-07 10:42:55 -0800551 if (poly[i].z >= lightPoly[0].z) {
552 inputPolyPositionValid = false;
Chris Craikb79a3e32014-03-11 12:20:17 -0700553 ALOGW("polygon above the light");
ztenghui7b4516e2014-01-07 10:42:55 -0800554 break;
555 }
556 }
557
558 // If the caster's position is invalid, don't draw anything.
559 if (!inputPolyPositionValid) {
560 return;
561 }
562
563 // Calculate the umbra polygon based on intersections of all outlines
564 int k = 0;
565 for (int j = 0; j < lightPolyLength; j++) {
566 int m = 0;
567 for (int i = 0; i < polyLength; i++) {
568 float t = lightPoly[j].z - poly[i].z;
569 if (t == 0) {
570 return;
571 }
572 t = lightPoly[j].z / t;
573 float x = lightPoly[j].x - t * (lightPoly[j].x - poly[i].x);
574 float y = lightPoly[j].y - t * (lightPoly[j].y - poly[i].y);
575
576 Vector2 newPoint = Vector2(x, y);
577 shadowRegion[k] = newPoint;
578 outline[m] = newPoint;
579
580 k++;
581 m++;
582 }
583
584 // For the first light polygon's vertex, use the outline as the umbra.
585 // Later on, use the intersection of the outline and existing umbra.
586 if (umbraLength == 0) {
587 for (int i = 0; i < polyLength; i++) {
588 umbra[i] = outline[i];
589 }
590 umbraLength = polyLength;
591 } else {
592 int col = ((j * 255) / lightPolyLength);
593 umbraLength = intersection(outline, polyLength, umbra, umbraLength);
594 if (umbraLength == 0) {
595 break;
596 }
597 }
598 }
599
600 // Generate the penumbra area using the hull of all shadow regions.
601 int shadowRegionLength = k;
602 Vector2 penumbra[k];
603 int penumbraLength = hull(shadowRegion, shadowRegionLength, penumbra);
604
ztenghui5176c972014-01-31 17:17:55 -0800605 Vector2 fakeUmbra[polyLength];
ztenghui7b4516e2014-01-07 10:42:55 -0800606 if (umbraLength < 3) {
ztenghui5176c972014-01-31 17:17:55 -0800607 // If there is no real umbra, make a fake one.
ztenghui7b4516e2014-01-07 10:42:55 -0800608 for (int i = 0; i < polyLength; i++) {
609 float t = lightCenter.z - poly[i].z;
610 if (t == 0) {
611 return;
612 }
613 t = lightCenter.z / t;
614 float x = lightCenter.x - t * (lightCenter.x - poly[i].x);
615 float y = lightCenter.y - t * (lightCenter.y - poly[i].y);
616
ztenghui5176c972014-01-31 17:17:55 -0800617 fakeUmbra[i].x = x;
618 fakeUmbra[i].y = y;
ztenghui7b4516e2014-01-07 10:42:55 -0800619 }
620
621 // Shrink the centroid's shadow by 10%.
622 // TODO: Study the magic number of 10%.
ztenghui63d41ab2014-02-14 13:13:41 -0800623 Vector2 shadowCentroid =
624 ShadowTessellator::centroid2d(fakeUmbra, polyLength);
ztenghui7b4516e2014-01-07 10:42:55 -0800625 for (int i = 0; i < polyLength; i++) {
ztenghui5176c972014-01-31 17:17:55 -0800626 fakeUmbra[i] = shadowCentroid * (1.0f - SHADOW_SHRINK_SCALE) +
627 fakeUmbra[i] * SHADOW_SHRINK_SCALE;
ztenghui7b4516e2014-01-07 10:42:55 -0800628 }
629#if DEBUG_SHADOW
630 ALOGD("No real umbra make a fake one, centroid2d = %f , %f",
631 shadowCentroid.x, shadowCentroid.y);
632#endif
633 // Set the fake umbra, whose size is the same as the original polygon.
ztenghui5176c972014-01-31 17:17:55 -0800634 umbra = fakeUmbra;
ztenghui7b4516e2014-01-07 10:42:55 -0800635 umbraLength = polyLength;
636 }
637
638 generateTriangleStrip(penumbra, penumbraLength, umbra, umbraLength,
ztenghui63d41ab2014-02-14 13:13:41 -0800639 shadowTriangleStrip);
ztenghui7b4516e2014-01-07 10:42:55 -0800640}
641
642/**
Chris Craik726118b2014-03-07 18:27:49 -0800643 * Converts a polygon specified with CW vertices into an array of distance-from-centroid values.
644 *
645 * Returns false in error conditions
646 *
647 * @param poly Array of vertices. Note that these *must* be CW.
648 * @param polyLength The number of vertices in the polygon.
649 * @param polyCentroid The centroid of the polygon, from which rays will be cast
650 * @param rayDist The output array for the calculated distances, must be SHADOW_RAY_COUNT in size
651 */
652bool convertPolyToRayDist(const Vector2* poly, int polyLength, const Vector2& polyCentroid,
653 float* rayDist) {
654 const int rays = SHADOW_RAY_COUNT;
655 const float step = M_PI * 2 / rays;
656
657 const Vector2* lastVertex = &(poly[polyLength - 1]);
658 float startAngle = angle(*lastVertex, polyCentroid);
659
660 // Start with the ray that's closest to and less than startAngle
661 int rayIndex = floor((startAngle - EPSILON) / step);
662 rayIndex = (rayIndex + rays) % rays; // ensure positive
663
664 for (int polyIndex = 0; polyIndex < polyLength; polyIndex++) {
665 /*
666 * For a given pair of vertices on the polygon, poly[i-1] and poly[i], the rays that
667 * intersect these will be those that are between the two angles from the centroid that the
668 * vertices define.
669 *
670 * Because the polygon vertices are stored clockwise, the closest ray with an angle
671 * *smaller* than that defined by angle(poly[i], centroid) will be the first ray that does
672 * not intersect with poly[i-1], poly[i].
673 */
674 float currentAngle = angle(poly[polyIndex], polyCentroid);
675
676 // find first ray that will not intersect the line segment poly[i-1] & poly[i]
677 int firstRayIndexOnNextSegment = floor((currentAngle - EPSILON) / step);
678 firstRayIndexOnNextSegment = (firstRayIndexOnNextSegment + rays) % rays; // ensure positive
679
680 // Iterate through all rays that intersect with poly[i-1], poly[i] line segment.
681 // This may be 0 rays.
682 while (rayIndex != firstRayIndexOnNextSegment) {
683 float distanceToIntersect = rayIntersectPoints(polyCentroid,
684 cos(rayIndex * step),
685 sin(rayIndex * step),
686 *lastVertex, poly[polyIndex]);
687 if (distanceToIntersect < 0) return false; // error case, abort
688
689 rayDist[rayIndex] = distanceToIntersect;
690
691 rayIndex = (rayIndex - 1 + rays) % rays;
692 }
693 lastVertex = &poly[polyIndex];
694 }
695
696 return true;
697}
698
699/**
ztenghui7b4516e2014-01-07 10:42:55 -0800700 * Generate a triangle strip given two convex polygons
701 *
702 * @param penumbra The outer polygon x,y vertexes
703 * @param penumbraLength The number of vertexes in the outer polygon
704 * @param umbra The inner outer polygon x,y vertexes
705 * @param umbraLength The number of vertexes in the inner polygon
ztenghui7b4516e2014-01-07 10:42:55 -0800706 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
707 * empty strip if error.
708**/
709void SpotShadow::generateTriangleStrip(const Vector2* penumbra, int penumbraLength,
ztenghui63d41ab2014-02-14 13:13:41 -0800710 const Vector2* umbra, int umbraLength, VertexBuffer& shadowTriangleStrip) {
711 const int rays = SHADOW_RAY_COUNT;
ztenghui7b4516e2014-01-07 10:42:55 -0800712
Chris Craik726118b2014-03-07 18:27:49 -0800713 const int size = 2 * rays;
714 const float step = M_PI * 2 / rays;
ztenghui7b4516e2014-01-07 10:42:55 -0800715 // Centroid of the umbra.
ztenghui63d41ab2014-02-14 13:13:41 -0800716 Vector2 centroid = ShadowTessellator::centroid2d(umbra, umbraLength);
ztenghui7b4516e2014-01-07 10:42:55 -0800717#if DEBUG_SHADOW
718 ALOGD("centroid2d = %f , %f", centroid.x, centroid.y);
719#endif
720 // Intersection to the penumbra.
721 float penumbraDistPerRay[rays];
722 // Intersection to the umbra.
723 float umbraDistPerRay[rays];
724
Chris Craik726118b2014-03-07 18:27:49 -0800725 // convert CW polygons to ray distance encoding, aborting on conversion failure
726 if (!convertPolyToRayDist(umbra, umbraLength, centroid, umbraDistPerRay)) return;
727 if (!convertPolyToRayDist(penumbra, penumbraLength, centroid, penumbraDistPerRay)) return;
ztenghui7b4516e2014-01-07 10:42:55 -0800728
Chris Craik726118b2014-03-07 18:27:49 -0800729 AlphaVertex* shadowVertices = shadowTriangleStrip.alloc<AlphaVertex>(getStripSize(rays));
ztenghui7b4516e2014-01-07 10:42:55 -0800730
ztenghui63d41ab2014-02-14 13:13:41 -0800731 // Calculate the vertices (x, y, alpha) in the shadow area.
Chris Craik726118b2014-03-07 18:27:49 -0800732 for (int rayIndex = 0; rayIndex < rays; rayIndex++) {
733 float dx = cosf(step * rayIndex);
734 float dy = sinf(step * rayIndex);
735
736 // outer ring
737 float currentDist = penumbraDistPerRay[rayIndex];
738 AlphaVertex::set(&shadowVertices[rayIndex],
739 dx * currentDist + centroid.x, dy * currentDist + centroid.y, 0.0f);
740
741 // inner ring
742 float deltaDist = umbraDistPerRay[rayIndex] - penumbraDistPerRay[rayIndex];
743 currentDist += deltaDist;
744 AlphaVertex::set(&shadowVertices[rays + rayIndex],
745 dx * currentDist + centroid.x, dy * currentDist + centroid.y, 1.0f);
ztenghui7b4516e2014-01-07 10:42:55 -0800746 }
ztenghui63d41ab2014-02-14 13:13:41 -0800747 // The centroid is in the umbra area, so the opacity is considered as 1.0.
Chris Craik726118b2014-03-07 18:27:49 -0800748 AlphaVertex::set(&shadowVertices[SHADOW_VERTEX_COUNT - 1], centroid.x, centroid.y, 1.0f);
ztenghui7b4516e2014-01-07 10:42:55 -0800749#if DEBUG_SHADOW
750 for (int i = 0; i < currentIndex; i++) {
ztenghui63d41ab2014-02-14 13:13:41 -0800751 ALOGD("spot shadow value: i %d, (x:%f, y:%f, a:%f)", i, shadowVertices[i].x,
ztenghui7b4516e2014-01-07 10:42:55 -0800752 shadowVertices[i].y, shadowVertices[i].alpha);
753 }
754#endif
755}
756
757/**
758 * This is only for experimental purpose.
759 * After intersections are calculated, we could smooth the polygon if needed.
760 * So far, we don't think it is more appealing yet.
761 *
762 * @param level The level of smoothness.
763 * @param rays The total number of rays.
764 * @param rayDist (In and Out) The distance for each ray.
765 *
766 */
767void SpotShadow::smoothPolygon(int level, int rays, float* rayDist) {
768 for (int k = 0; k < level; k++) {
769 for (int i = 0; i < rays; i++) {
770 float p1 = rayDist[(rays - 1 + i) % rays];
771 float p2 = rayDist[i];
772 float p3 = rayDist[(i + 1) % rays];
773 rayDist[i] = (p1 + p2 * 2 + p3) / 4;
774 }
775 }
776}
777
778/**
ztenghui7b4516e2014-01-07 10:42:55 -0800779 * Calculate the number of vertex we will create given a number of rays and layers
780 *
781 * @param rays number of points around the polygons you want
782 * @param layers number of layers of triangle strips you need
783 * @return number of vertex (multiply by 3 for number of floats)
784 */
Chris Craik726118b2014-03-07 18:27:49 -0800785int SpotShadow::getStripSize(int rays) {
786 return (2 + rays + (2 * (rays + 1)));
ztenghui7b4516e2014-01-07 10:42:55 -0800787}
788
ztenghuif5ca8b42014-01-27 15:53:28 -0800789#if DEBUG_SHADOW
790
791#define TEST_POINT_NUMBER 128
792
793/**
794 * Calculate the bounds for generating random test points.
795 */
796void SpotShadow::updateBound(const Vector2 inVector, Vector2& lowerBound,
797 Vector2& upperBound ) {
798 if (inVector.x < lowerBound.x) {
799 lowerBound.x = inVector.x;
800 }
801
802 if (inVector.y < lowerBound.y) {
803 lowerBound.y = inVector.y;
804 }
805
806 if (inVector.x > upperBound.x) {
807 upperBound.x = inVector.x;
808 }
809
810 if (inVector.y > upperBound.y) {
811 upperBound.y = inVector.y;
812 }
813}
814
815/**
816 * For debug purpose, when things go wrong, dump the whole polygon data.
817 */
818static void dumpPolygon(const Vector2* poly, int polyLength, const char* polyName) {
819 for (int i = 0; i < polyLength; i++) {
820 ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
821 }
822}
823
824/**
825 * Test whether the polygon is convex.
826 */
827bool SpotShadow::testConvex(const Vector2* polygon, int polygonLength,
828 const char* name) {
829 bool isConvex = true;
830 for (int i = 0; i < polygonLength; i++) {
831 Vector2 start = polygon[i];
832 Vector2 middle = polygon[(i + 1) % polygonLength];
833 Vector2 end = polygon[(i + 2) % polygonLength];
834
835 double delta = (double(middle.x) - start.x) * (double(end.y) - start.y) -
836 (double(middle.y) - start.y) * (double(end.x) - start.x);
837 bool isCCWOrCoLinear = (delta >= EPSILON);
838
839 if (isCCWOrCoLinear) {
840 ALOGE("(Error Type 2): polygon (%s) is not a convex b/c start (x %f, y %f),"
841 "middle (x %f, y %f) and end (x %f, y %f) , delta is %f !!!",
842 name, start.x, start.y, middle.x, middle.y, end.x, end.y, delta);
843 isConvex = false;
844 break;
845 }
846 }
847 return isConvex;
848}
849
850/**
851 * Test whether or not the polygon (intersection) is within the 2 input polygons.
852 * Using Marte Carlo method, we generate a random point, and if it is inside the
853 * intersection, then it must be inside both source polygons.
854 */
855void SpotShadow::testIntersection(const Vector2* poly1, int poly1Length,
856 const Vector2* poly2, int poly2Length,
857 const Vector2* intersection, int intersectionLength) {
858 // Find the min and max of x and y.
859 Vector2 lowerBound(FLT_MAX, FLT_MAX);
860 Vector2 upperBound(-FLT_MAX, -FLT_MAX);
861 for (int i = 0; i < poly1Length; i++) {
862 updateBound(poly1[i], lowerBound, upperBound);
863 }
864 for (int i = 0; i < poly2Length; i++) {
865 updateBound(poly2[i], lowerBound, upperBound);
866 }
867
868 bool dumpPoly = false;
869 for (int k = 0; k < TEST_POINT_NUMBER; k++) {
870 // Generate a random point between minX, minY and maxX, maxY.
871 double randomX = rand() / double(RAND_MAX);
872 double randomY = rand() / double(RAND_MAX);
873
874 Vector2 testPoint;
875 testPoint.x = lowerBound.x + randomX * (upperBound.x - lowerBound.x);
876 testPoint.y = lowerBound.y + randomY * (upperBound.y - lowerBound.y);
877
878 // If the random point is in both poly 1 and 2, then it must be intersection.
879 if (testPointInsidePolygon(testPoint, intersection, intersectionLength)) {
880 if (!testPointInsidePolygon(testPoint, poly1, poly1Length)) {
881 dumpPoly = true;
882 ALOGE("(Error Type 1): one point (%f, %f) in the intersection is"
883 " not in the poly1",
884 testPoint.x, testPoint.y);
885 }
886
887 if (!testPointInsidePolygon(testPoint, poly2, poly2Length)) {
888 dumpPoly = true;
889 ALOGE("(Error Type 1): one point (%f, %f) in the intersection is"
890 " not in the poly2",
891 testPoint.x, testPoint.y);
892 }
893 }
894 }
895
896 if (dumpPoly) {
897 dumpPolygon(intersection, intersectionLength, "intersection");
898 for (int i = 1; i < intersectionLength; i++) {
899 Vector2 delta = intersection[i] - intersection[i - 1];
900 ALOGD("Intersetion i, %d Vs i-1 is delta %f", i, delta.lengthSquared());
901 }
902
903 dumpPolygon(poly1, poly1Length, "poly 1");
904 dumpPolygon(poly2, poly2Length, "poly 2");
905 }
906}
907#endif
908
ztenghui7b4516e2014-01-07 10:42:55 -0800909}; // namespace uirenderer
910}; // namespace android