blob: 001e22f24901e2d149d40ff59e6f801e753f7514 [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"
Tom Hudson2dc236b2014-10-15 15:46:42 -040055#include "VertexBuffer.h"
ztenghuic50a03d2014-08-21 13:47:54 -070056#include "utils/MathUtils.h"
ztenghui7b4516e2014-01-07 10:42:55 -080057
ztenghuic50a03d2014-08-21 13:47:54 -070058// TODO: After we settle down the new algorithm, we can remove the old one and
59// its utility functions.
60// Right now, we still need to keep it for comparison purpose and future expansion.
ztenghui7b4516e2014-01-07 10:42:55 -080061namespace android {
62namespace uirenderer {
63
ztenghui9122b1b2014-10-03 11:21:11 -070064static const float EPSILON = 1e-7;
Chris Craik726118b2014-03-07 18:27:49 -080065
ztenghui7b4516e2014-01-07 10:42:55 -080066/**
ztenghuic50a03d2014-08-21 13:47:54 -070067 * For each polygon's vertex, the light center will project it to the receiver
68 * as one of the outline vertex.
69 * For each outline vertex, we need to store the position and normal.
70 * Normal here is defined against the edge by the current vertex and the next vertex.
71 */
72struct OutlineData {
73 Vector2 position;
74 Vector2 normal;
75 float radius;
76};
77
78/**
ztenghui512e6432014-09-10 13:08:20 -070079 * For each vertex, we need to keep track of its angle, whether it is penumbra or
80 * umbra, and its corresponding vertex index.
81 */
82struct SpotShadow::VertexAngleData {
83 // The angle to the vertex from the centroid.
84 float mAngle;
85 // True is the vertex comes from penumbra, otherwise it comes from umbra.
86 bool mIsPenumbra;
87 // The index of the vertex described by this data.
88 int mVertexIndex;
89 void set(float angle, bool isPenumbra, int index) {
90 mAngle = angle;
91 mIsPenumbra = isPenumbra;
92 mVertexIndex = index;
93 }
94};
95
96/**
Chris Craik726118b2014-03-07 18:27:49 -080097 * Calculate the angle between and x and a y coordinate.
98 * The atan2 range from -PI to PI.
ztenghui7b4516e2014-01-07 10:42:55 -080099 */
Chris Craikb79a3e32014-03-11 12:20:17 -0700100static float angle(const Vector2& point, const Vector2& center) {
Chris Craik726118b2014-03-07 18:27:49 -0800101 return atan2(point.y - center.y, point.x - center.x);
102}
103
104/**
105 * Calculate the intersection of a ray with the line segment defined by two points.
106 *
107 * Returns a negative value in error conditions.
108
109 * @param rayOrigin The start of the ray
110 * @param dx The x vector of the ray
111 * @param dy The y vector of the ray
112 * @param p1 The first point defining the line segment
113 * @param p2 The second point defining the line segment
114 * @return The distance along the ray if it intersects with the line segment, negative if otherwise
115 */
Chris Craikb79a3e32014-03-11 12:20:17 -0700116static float rayIntersectPoints(const Vector2& rayOrigin, float dx, float dy,
Chris Craik726118b2014-03-07 18:27:49 -0800117 const Vector2& p1, const Vector2& p2) {
118 // The math below is derived from solving this formula, basically the
119 // intersection point should stay on both the ray and the edge of (p1, p2).
120 // solve([p1x+t*(p2x-p1x)=dx*t2+px,p1y+t*(p2y-p1y)=dy*t2+py],[t,t2]);
121
ztenghui9122b1b2014-10-03 11:21:11 -0700122 float divisor = (dx * (p1.y - p2.y) + dy * p2.x - dy * p1.x);
Chris Craik726118b2014-03-07 18:27:49 -0800123 if (divisor == 0) return -1.0f; // error, invalid divisor
124
125#if DEBUG_SHADOW
ztenghui9122b1b2014-10-03 11:21:11 -0700126 float interpVal = (dx * (p1.y - rayOrigin.y) + dy * rayOrigin.x - dy * p1.x) / divisor;
ztenghui99af9422014-03-14 14:35:54 -0700127 if (interpVal < 0 || interpVal > 1) {
128 ALOGW("rayIntersectPoints is hitting outside the segment %f", interpVal);
129 }
Chris Craik726118b2014-03-07 18:27:49 -0800130#endif
131
ztenghui9122b1b2014-10-03 11:21:11 -0700132 float distance = (p1.x * (rayOrigin.y - p2.y) + p2.x * (p1.y - rayOrigin.y) +
Chris Craik726118b2014-03-07 18:27:49 -0800133 rayOrigin.x * (p2.y - p1.y)) / divisor;
134
135 return distance; // may be negative in error cases
ztenghui7b4516e2014-01-07 10:42:55 -0800136}
137
138/**
ztenghui7b4516e2014-01-07 10:42:55 -0800139 * Sort points by their X coordinates
140 *
141 * @param points the points as a Vector2 array.
142 * @param pointsLength the number of vertices of the polygon.
143 */
144void SpotShadow::xsort(Vector2* points, int pointsLength) {
145 quicksortX(points, 0, pointsLength - 1);
146}
147
148/**
149 * compute the convex hull of a collection of Points
150 *
151 * @param points the points as a Vector2 array.
152 * @param pointsLength the number of vertices of the polygon.
153 * @param retPoly pre allocated array of floats to put the vertices
154 * @return the number of points in the polygon 0 if no intersection
155 */
156int SpotShadow::hull(Vector2* points, int pointsLength, Vector2* retPoly) {
157 xsort(points, pointsLength);
158 int n = pointsLength;
159 Vector2 lUpper[n];
160 lUpper[0] = points[0];
161 lUpper[1] = points[1];
162
163 int lUpperSize = 2;
164
165 for (int i = 2; i < n; i++) {
166 lUpper[lUpperSize] = points[i];
167 lUpperSize++;
168
ztenghuif5ca8b42014-01-27 15:53:28 -0800169 while (lUpperSize > 2 && !ccw(
170 lUpper[lUpperSize - 3].x, lUpper[lUpperSize - 3].y,
171 lUpper[lUpperSize - 2].x, lUpper[lUpperSize - 2].y,
172 lUpper[lUpperSize - 1].x, lUpper[lUpperSize - 1].y)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800173 // Remove the middle point of the three last
174 lUpper[lUpperSize - 2].x = lUpper[lUpperSize - 1].x;
175 lUpper[lUpperSize - 2].y = lUpper[lUpperSize - 1].y;
176 lUpperSize--;
177 }
178 }
179
180 Vector2 lLower[n];
181 lLower[0] = points[n - 1];
182 lLower[1] = points[n - 2];
183
184 int lLowerSize = 2;
185
186 for (int i = n - 3; i >= 0; i--) {
187 lLower[lLowerSize] = points[i];
188 lLowerSize++;
189
ztenghuif5ca8b42014-01-27 15:53:28 -0800190 while (lLowerSize > 2 && !ccw(
191 lLower[lLowerSize - 3].x, lLower[lLowerSize - 3].y,
192 lLower[lLowerSize - 2].x, lLower[lLowerSize - 2].y,
193 lLower[lLowerSize - 1].x, lLower[lLowerSize - 1].y)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800194 // Remove the middle point of the three last
195 lLower[lLowerSize - 2] = lLower[lLowerSize - 1];
196 lLowerSize--;
197 }
198 }
ztenghui7b4516e2014-01-07 10:42:55 -0800199
Chris Craik726118b2014-03-07 18:27:49 -0800200 // output points in CW ordering
201 const int total = lUpperSize + lLowerSize - 2;
202 int outIndex = total - 1;
ztenghui7b4516e2014-01-07 10:42:55 -0800203 for (int i = 0; i < lUpperSize; i++) {
Chris Craik726118b2014-03-07 18:27:49 -0800204 retPoly[outIndex] = lUpper[i];
205 outIndex--;
ztenghui7b4516e2014-01-07 10:42:55 -0800206 }
207
208 for (int i = 1; i < lLowerSize - 1; i++) {
Chris Craik726118b2014-03-07 18:27:49 -0800209 retPoly[outIndex] = lLower[i];
210 outIndex--;
ztenghui7b4516e2014-01-07 10:42:55 -0800211 }
212 // TODO: Add test harness which verify that all the points are inside the hull.
Chris Craik726118b2014-03-07 18:27:49 -0800213 return total;
ztenghui7b4516e2014-01-07 10:42:55 -0800214}
215
216/**
ztenghuif5ca8b42014-01-27 15:53:28 -0800217 * Test whether the 3 points form a counter clockwise turn.
ztenghui7b4516e2014-01-07 10:42:55 -0800218 *
ztenghui7b4516e2014-01-07 10:42:55 -0800219 * @return true if a right hand turn
220 */
ztenghui9122b1b2014-10-03 11:21:11 -0700221bool SpotShadow::ccw(float ax, float ay, float bx, float by,
222 float cx, float cy) {
ztenghui7b4516e2014-01-07 10:42:55 -0800223 return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > EPSILON;
224}
225
226/**
ztenghui7b4516e2014-01-07 10:42:55 -0800227 * Sort points about a center point
228 *
229 * @param poly The in and out polyogon as a Vector2 array.
230 * @param polyLength The number of vertices of the polygon.
231 * @param center the center ctr[0] = x , ctr[1] = y to sort around.
232 */
233void SpotShadow::sort(Vector2* poly, int polyLength, const Vector2& center) {
234 quicksortCirc(poly, 0, polyLength - 1, center);
235}
236
237/**
ztenghui7b4516e2014-01-07 10:42:55 -0800238 * Swap points pointed to by i and j
239 */
240void SpotShadow::swap(Vector2* points, int i, int j) {
241 Vector2 temp = points[i];
242 points[i] = points[j];
243 points[j] = temp;
244}
245
246/**
247 * quick sort implementation about the center.
248 */
249void SpotShadow::quicksortCirc(Vector2* points, int low, int high,
250 const Vector2& center) {
251 int i = low, j = high;
252 int p = low + (high - low) / 2;
253 float pivot = angle(points[p], center);
254 while (i <= j) {
Chris Craik726118b2014-03-07 18:27:49 -0800255 while (angle(points[i], center) > pivot) {
ztenghui7b4516e2014-01-07 10:42:55 -0800256 i++;
257 }
Chris Craik726118b2014-03-07 18:27:49 -0800258 while (angle(points[j], center) < pivot) {
ztenghui7b4516e2014-01-07 10:42:55 -0800259 j--;
260 }
261
262 if (i <= j) {
263 swap(points, i, j);
264 i++;
265 j--;
266 }
267 }
268 if (low < j) quicksortCirc(points, low, j, center);
269 if (i < high) quicksortCirc(points, i, high, center);
270}
271
272/**
273 * Sort points by x axis
274 *
275 * @param points points to sort
276 * @param low start index
277 * @param high end index
278 */
279void SpotShadow::quicksortX(Vector2* points, int low, int high) {
280 int i = low, j = high;
281 int p = low + (high - low) / 2;
282 float pivot = points[p].x;
283 while (i <= j) {
284 while (points[i].x < pivot) {
285 i++;
286 }
287 while (points[j].x > pivot) {
288 j--;
289 }
290
291 if (i <= j) {
292 swap(points, i, j);
293 i++;
294 j--;
295 }
296 }
297 if (low < j) quicksortX(points, low, j);
298 if (i < high) quicksortX(points, i, high);
299}
300
301/**
302 * Test whether a point is inside the polygon.
303 *
304 * @param testPoint the point to test
305 * @param poly the polygon
306 * @return true if the testPoint is inside the poly.
307 */
308bool SpotShadow::testPointInsidePolygon(const Vector2 testPoint,
309 const Vector2* poly, int len) {
310 bool c = false;
ztenghui9122b1b2014-10-03 11:21:11 -0700311 float testx = testPoint.x;
312 float testy = testPoint.y;
ztenghui7b4516e2014-01-07 10:42:55 -0800313 for (int i = 0, j = len - 1; i < len; j = i++) {
ztenghui9122b1b2014-10-03 11:21:11 -0700314 float startX = poly[j].x;
315 float startY = poly[j].y;
316 float endX = poly[i].x;
317 float endY = poly[i].y;
ztenghui7b4516e2014-01-07 10:42:55 -0800318
ztenghui512e6432014-09-10 13:08:20 -0700319 if (((endY > testy) != (startY > testy))
320 && (testx < (startX - endX) * (testy - endY)
ztenghui7b4516e2014-01-07 10:42:55 -0800321 / (startY - endY) + endX)) {
322 c = !c;
323 }
324 }
325 return c;
326}
327
328/**
329 * Make the polygon turn clockwise.
330 *
331 * @param polygon the polygon as a Vector2 array.
332 * @param len the number of points of the polygon
333 */
334void SpotShadow::makeClockwise(Vector2* polygon, int len) {
335 if (polygon == 0 || len == 0) {
336 return;
337 }
ztenghui2e023f32014-04-28 16:43:13 -0700338 if (!ShadowTessellator::isClockwise(polygon, len)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800339 reverse(polygon, len);
340 }
341}
342
343/**
ztenghui7b4516e2014-01-07 10:42:55 -0800344 * Reverse the polygon
345 *
346 * @param polygon the polygon as a Vector2 array
347 * @param len the number of points of the polygon
348 */
349void SpotShadow::reverse(Vector2* polygon, int len) {
350 int n = len / 2;
351 for (int i = 0; i < n; i++) {
352 Vector2 tmp = polygon[i];
353 int k = len - 1 - i;
354 polygon[i] = polygon[k];
355 polygon[k] = tmp;
356 }
357}
358
359/**
ztenghui7b4516e2014-01-07 10:42:55 -0800360 * Compute a horizontal circular polygon about point (x , y , height) of radius
361 * (size)
362 *
363 * @param points number of the points of the output polygon.
364 * @param lightCenter the center of the light.
365 * @param size the light size.
366 * @param ret result polygon.
367 */
368void SpotShadow::computeLightPolygon(int points, const Vector3& lightCenter,
369 float size, Vector3* ret) {
370 // TODO: Caching all the sin / cos values and store them in a look up table.
371 for (int i = 0; i < points; i++) {
ztenghui9122b1b2014-10-03 11:21:11 -0700372 float angle = 2 * i * M_PI / points;
Chris Craik726118b2014-03-07 18:27:49 -0800373 ret[i].x = cosf(angle) * size + lightCenter.x;
374 ret[i].y = sinf(angle) * size + lightCenter.y;
ztenghui7b4516e2014-01-07 10:42:55 -0800375 ret[i].z = lightCenter.z;
376 }
377}
378
379/**
ztenghui512e6432014-09-10 13:08:20 -0700380 * From light center, project one vertex to the z=0 surface and get the outline.
ztenghui7b4516e2014-01-07 10:42:55 -0800381 *
ztenghui512e6432014-09-10 13:08:20 -0700382 * @param outline The result which is the outline position.
383 * @param lightCenter The center of light.
384 * @param polyVertex The input polygon's vertex.
385 *
386 * @return float The ratio of (polygon.z / light.z - polygon.z)
ztenghui7b4516e2014-01-07 10:42:55 -0800387 */
ztenghuic50a03d2014-08-21 13:47:54 -0700388float SpotShadow::projectCasterToOutline(Vector2& outline,
389 const Vector3& lightCenter, const Vector3& polyVertex) {
390 float lightToPolyZ = lightCenter.z - polyVertex.z;
391 float ratioZ = CASTER_Z_CAP_RATIO;
392 if (lightToPolyZ != 0) {
393 // If any caster's vertex is almost above the light, we just keep it as 95%
394 // of the height of the light.
ztenghui3bd3fa12014-08-25 14:42:27 -0700395 ratioZ = MathUtils::clamp(polyVertex.z / lightToPolyZ, 0.0f, CASTER_Z_CAP_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700396 }
397
398 outline.x = polyVertex.x - ratioZ * (lightCenter.x - polyVertex.x);
399 outline.y = polyVertex.y - ratioZ * (lightCenter.y - polyVertex.y);
400 return ratioZ;
401}
402
403/**
404 * Generate the shadow spot light of shape lightPoly and a object poly
405 *
406 * @param isCasterOpaque whether the caster is opaque
407 * @param lightCenter the center of the light
408 * @param lightSize the radius of the light
409 * @param poly x,y,z vertexes of a convex polygon that occludes the light source
410 * @param polyLength number of vertexes of the occluding polygon
411 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
412 * empty strip if error.
413 */
414void SpotShadow::createSpotShadow(bool isCasterOpaque, const Vector3& lightCenter,
415 float lightSize, const Vector3* poly, int polyLength, const Vector3& polyCentroid,
416 VertexBuffer& shadowTriangleStrip) {
ztenghui3bd3fa12014-08-25 14:42:27 -0700417 if (CC_UNLIKELY(lightCenter.z <= 0)) {
418 ALOGW("Relative Light Z is not positive. No spot shadow!");
419 return;
420 }
ztenghui512e6432014-09-10 13:08:20 -0700421 if (CC_UNLIKELY(polyLength < 3)) {
422#if DEBUG_SHADOW
423 ALOGW("Invalid polygon length. No spot shadow!");
424#endif
425 return;
426 }
ztenghuic50a03d2014-08-21 13:47:54 -0700427 OutlineData outlineData[polyLength];
428 Vector2 outlineCentroid;
429 // Calculate the projected outline for each polygon's vertices from the light center.
430 //
431 // O Light
432 // /
433 // /
434 // . Polygon vertex
435 // /
436 // /
437 // O Outline vertices
438 //
439 // Ratio = (Poly - Outline) / (Light - Poly)
440 // Outline.x = Poly.x - Ratio * (Light.x - Poly.x)
441 // Outline's radius / Light's radius = Ratio
442
443 // Compute the last outline vertex to make sure we can get the normal and outline
444 // in one single loop.
445 projectCasterToOutline(outlineData[polyLength - 1].position, lightCenter,
446 poly[polyLength - 1]);
447
448 // Take the outline's polygon, calculate the normal for each outline edge.
449 int currentNormalIndex = polyLength - 1;
450 int nextNormalIndex = 0;
451
452 for (int i = 0; i < polyLength; i++) {
453 float ratioZ = projectCasterToOutline(outlineData[i].position,
454 lightCenter, poly[i]);
455 outlineData[i].radius = ratioZ * lightSize;
456
457 outlineData[currentNormalIndex].normal = ShadowTessellator::calculateNormal(
458 outlineData[currentNormalIndex].position,
459 outlineData[nextNormalIndex].position);
460 currentNormalIndex = (currentNormalIndex + 1) % polyLength;
461 nextNormalIndex++;
462 }
463
464 projectCasterToOutline(outlineCentroid, lightCenter, polyCentroid);
465
466 int penumbraIndex = 0;
ztenghui512e6432014-09-10 13:08:20 -0700467 // Then each polygon's vertex produce at minmal 2 penumbra vertices.
468 // Since the size can be dynamic here, we keep track of the size and update
469 // the real size at the end.
470 int allocatedPenumbraLength = 2 * polyLength + SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER;
471 Vector2 penumbra[allocatedPenumbraLength];
472 int totalExtraCornerSliceNumber = 0;
ztenghuic50a03d2014-08-21 13:47:54 -0700473
474 Vector2 umbra[polyLength];
ztenghuic50a03d2014-08-21 13:47:54 -0700475
ztenghui512e6432014-09-10 13:08:20 -0700476 // When centroid is covered by all circles from outline, then we consider
477 // the umbra is invalid, and we will tune down the shadow strength.
ztenghuic50a03d2014-08-21 13:47:54 -0700478 bool hasValidUmbra = true;
ztenghui512e6432014-09-10 13:08:20 -0700479 // We need the minimal of RaitoVI to decrease the spot shadow strength accordingly.
480 float minRaitoVI = FLT_MAX;
ztenghuic50a03d2014-08-21 13:47:54 -0700481
482 for (int i = 0; i < polyLength; i++) {
483 // Generate all the penumbra's vertices only using the (outline vertex + normal * radius)
484 // There is no guarantee that the penumbra is still convex, but for
485 // each outline vertex, it will connect to all its corresponding penumbra vertices as
486 // triangle fans. And for neighber penumbra vertex, it will be a trapezoid.
487 //
488 // Penumbra Vertices marked as Pi
489 // Outline Vertices marked as Vi
490 // (P3)
491 // (P2) | ' (P4)
492 // (P1)' | | '
493 // ' | | '
494 // (P0) ------------------------------------------------(P5)
495 // | (V0) |(V1)
496 // | |
497 // | |
498 // | |
499 // | |
500 // | |
501 // | |
502 // | |
503 // | |
504 // (V3)-----------------------------------(V2)
505 int preNormalIndex = (i + polyLength - 1) % polyLength;
ztenghuic50a03d2014-08-21 13:47:54 -0700506
ztenghui512e6432014-09-10 13:08:20 -0700507 const Vector2& previousNormal = outlineData[preNormalIndex].normal;
508 const Vector2& currentNormal = outlineData[i].normal;
509
510 // Depending on how roundness we want for each corner, we can subdivide
ztenghuic50a03d2014-08-21 13:47:54 -0700511 // further here and/or introduce some heuristic to decide how much the
512 // subdivision should be.
ztenghui512e6432014-09-10 13:08:20 -0700513 int currentExtraSliceNumber = ShadowTessellator::getExtraVertexNumber(
514 previousNormal, currentNormal, SPOT_CORNER_RADIANS_DIVISOR);
ztenghuic50a03d2014-08-21 13:47:54 -0700515
ztenghui512e6432014-09-10 13:08:20 -0700516 int currentCornerSliceNumber = 1 + currentExtraSliceNumber;
517 totalExtraCornerSliceNumber += currentExtraSliceNumber;
518#if DEBUG_SHADOW
519 ALOGD("currentExtraSliceNumber should be %d", currentExtraSliceNumber);
520 ALOGD("currentCornerSliceNumber should be %d", currentCornerSliceNumber);
521 ALOGD("totalCornerSliceNumber is %d", totalExtraCornerSliceNumber);
522#endif
523 if (CC_UNLIKELY(totalExtraCornerSliceNumber > SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER)) {
524 currentCornerSliceNumber = 1;
525 }
526 for (int k = 0; k <= currentCornerSliceNumber; k++) {
527 Vector2 avgNormal =
528 (previousNormal * (currentCornerSliceNumber - k) + currentNormal * k) /
529 currentCornerSliceNumber;
530 avgNormal.normalize();
531 penumbra[penumbraIndex++] = outlineData[i].position +
532 avgNormal * outlineData[i].radius;
533 }
ztenghuic50a03d2014-08-21 13:47:54 -0700534
ztenghuic50a03d2014-08-21 13:47:54 -0700535
536 // Compute the umbra by the intersection from the outline's centroid!
537 //
538 // (V) ------------------------------------
539 // | ' |
540 // | ' |
541 // | ' (I) |
542 // | ' |
543 // | ' (C) |
544 // | |
545 // | |
546 // | |
547 // | |
548 // ------------------------------------
549 //
550 // Connect a line b/t the outline vertex (V) and the centroid (C), it will
551 // intersect with the outline vertex's circle at point (I).
552 // Now, ratioVI = VI / VC, ratioIC = IC / VC
553 // Then the intersetion point can be computed as Ixy = Vxy * ratioIC + Cxy * ratioVI;
554 //
ztenghui512e6432014-09-10 13:08:20 -0700555 // When all of the outline circles cover the the outline centroid, (like I is
ztenghuic50a03d2014-08-21 13:47:54 -0700556 // on the other side of C), there is no real umbra any more, so we just fake
557 // a small area around the centroid as the umbra, and tune down the spot
558 // shadow's umbra strength to simulate the effect the whole shadow will
559 // become lighter in this case.
560 // The ratio can be simulated by using the inverse of maximum of ratioVI for
561 // all (V).
ztenghui512e6432014-09-10 13:08:20 -0700562 float distOutline = (outlineData[i].position - outlineCentroid).length();
ztenghui3bd3fa12014-08-25 14:42:27 -0700563 if (CC_UNLIKELY(distOutline == 0)) {
ztenghuic50a03d2014-08-21 13:47:54 -0700564 // If the outline has 0 area, then there is no spot shadow anyway.
565 ALOGW("Outline has 0 area, no spot shadow!");
566 return;
567 }
ztenghui512e6432014-09-10 13:08:20 -0700568
569 float ratioVI = outlineData[i].radius / distOutline;
570 minRaitoVI = MathUtils::min(minRaitoVI, ratioVI);
571 if (ratioVI >= (1 - FAKE_UMBRA_SIZE_RATIO)) {
572 ratioVI = (1 - FAKE_UMBRA_SIZE_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700573 }
574 // When we know we don't have valid umbra, don't bother to compute the
575 // values below. But we can't skip the loop yet since we want to know the
576 // maximum ratio.
ztenghui512e6432014-09-10 13:08:20 -0700577 float ratioIC = 1 - ratioVI;
578 umbra[i] = outlineData[i].position * ratioIC + outlineCentroid * ratioVI;
ztenghuic50a03d2014-08-21 13:47:54 -0700579 }
580
ztenghui512e6432014-09-10 13:08:20 -0700581 hasValidUmbra = (minRaitoVI <= 1.0);
ztenghuic50a03d2014-08-21 13:47:54 -0700582 float shadowStrengthScale = 1.0;
583 if (!hasValidUmbra) {
ztenghui512e6432014-09-10 13:08:20 -0700584#if DEBUG_SHADOW
ztenghuic50a03d2014-08-21 13:47:54 -0700585 ALOGW("The object is too close to the light or too small, no real umbra!");
ztenghui512e6432014-09-10 13:08:20 -0700586#endif
ztenghuic50a03d2014-08-21 13:47:54 -0700587 for (int i = 0; i < polyLength; i++) {
588 umbra[i] = outlineData[i].position * FAKE_UMBRA_SIZE_RATIO +
ztenghui512e6432014-09-10 13:08:20 -0700589 outlineCentroid * (1 - FAKE_UMBRA_SIZE_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700590 }
ztenghui512e6432014-09-10 13:08:20 -0700591 shadowStrengthScale = 1.0 / minRaitoVI;
ztenghuic50a03d2014-08-21 13:47:54 -0700592 }
593
ztenghui512e6432014-09-10 13:08:20 -0700594 int penumbraLength = penumbraIndex;
595 int umbraLength = polyLength;
596
ztenghuic50a03d2014-08-21 13:47:54 -0700597#if DEBUG_SHADOW
ztenghui512e6432014-09-10 13:08:20 -0700598 ALOGD("penumbraLength is %d , allocatedPenumbraLength %d", penumbraLength, allocatedPenumbraLength);
ztenghuic50a03d2014-08-21 13:47:54 -0700599 dumpPolygon(poly, polyLength, "input poly");
ztenghuic50a03d2014-08-21 13:47:54 -0700600 dumpPolygon(penumbra, penumbraLength, "penumbra");
ztenghui512e6432014-09-10 13:08:20 -0700601 dumpPolygon(umbra, umbraLength, "umbra");
ztenghuic50a03d2014-08-21 13:47:54 -0700602 ALOGD("hasValidUmbra is %d and shadowStrengthScale is %f", hasValidUmbra, shadowStrengthScale);
603#endif
604
ztenghui512e6432014-09-10 13:08:20 -0700605 // The penumbra and umbra needs to be in convex shape to keep consistency
606 // and quality.
607 // Since we are still shooting rays to penumbra, it needs to be convex.
608 // Umbra can be represented as a fan from the centroid, but visually umbra
609 // looks nicer when it is convex.
610 Vector2 finalUmbra[umbraLength];
611 Vector2 finalPenumbra[penumbraLength];
612 int finalUmbraLength = hull(umbra, umbraLength, finalUmbra);
613 int finalPenumbraLength = hull(penumbra, penumbraLength, finalPenumbra);
614
615 generateTriangleStrip(isCasterOpaque, shadowStrengthScale, finalPenumbra,
616 finalPenumbraLength, finalUmbra, finalUmbraLength, poly, polyLength,
617 shadowTriangleStrip, outlineCentroid);
618
ztenghuic50a03d2014-08-21 13:47:54 -0700619}
620
ztenghui7b4516e2014-01-07 10:42:55 -0800621/**
ztenghui7b4516e2014-01-07 10:42:55 -0800622 * This is only for experimental purpose.
623 * After intersections are calculated, we could smooth the polygon if needed.
624 * So far, we don't think it is more appealing yet.
625 *
626 * @param level The level of smoothness.
627 * @param rays The total number of rays.
628 * @param rayDist (In and Out) The distance for each ray.
629 *
630 */
631void SpotShadow::smoothPolygon(int level, int rays, float* rayDist) {
632 for (int k = 0; k < level; k++) {
633 for (int i = 0; i < rays; i++) {
634 float p1 = rayDist[(rays - 1 + i) % rays];
635 float p2 = rayDist[i];
636 float p3 = rayDist[(i + 1) % rays];
637 rayDist[i] = (p1 + p2 * 2 + p3) / 4;
638 }
639 }
640}
641
ztenghuid2dcd6f2014-10-29 16:04:29 -0700642// Index pair is meant for storing the tessellation information for the penumbra
643// area. One index must come from exterior tangent of the circles, the other one
644// must come from the interior tangent of the circles.
645struct IndexPair {
646 int outerIndex;
647 int innerIndex;
648};
ztenghui512e6432014-09-10 13:08:20 -0700649
ztenghuid2dcd6f2014-10-29 16:04:29 -0700650// For one penumbra vertex, find the cloest umbra vertex and return its index.
651inline int getClosestUmbraIndex(const Vector2& pivot, const Vector2* polygon, int polygonLength) {
652 float minLengthSquared = FLT_MAX;
ztenghui512e6432014-09-10 13:08:20 -0700653 int resultIndex = -1;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700654 bool hasDecreased = false;
655 // Starting with some negative offset, assuming both umbra and penumbra are starting
656 // at the same angle, this can help to find the result faster.
657 // Normally, loop 3 times, we can find the closest point.
658 int offset = polygonLength - 2;
659 for (int i = 0; i < polygonLength; i++) {
660 int currentIndex = (i + offset) % polygonLength;
661 float currentLengthSquared = (pivot - polygon[currentIndex]).lengthSquared();
662 if (currentLengthSquared < minLengthSquared) {
663 if (minLengthSquared != FLT_MAX) {
664 hasDecreased = true;
ztenghui512e6432014-09-10 13:08:20 -0700665 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700666 minLengthSquared = currentLengthSquared;
667 resultIndex = currentIndex;
668 } else if (currentLengthSquared > minLengthSquared && hasDecreased) {
669 // Early break b/c we have found the closet one and now the length
670 // is increasing again.
671 break;
ztenghui512e6432014-09-10 13:08:20 -0700672 }
673 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700674 if(resultIndex == -1) {
675 ALOGE("resultIndex is -1, the polygon must be invalid!");
676 resultIndex = 0;
ztenghui512e6432014-09-10 13:08:20 -0700677 }
678 return resultIndex;
679}
680
ztenghuid2dcd6f2014-10-29 16:04:29 -0700681inline bool sameDirections(bool isPositiveCross, float a, float b) {
682 if (isPositiveCross) {
683 return a >= 0 && b >= 0;
684 } else {
685 return a <= 0 && b <= 0;
ztenghui512e6432014-09-10 13:08:20 -0700686 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700687}
ztenghui512e6432014-09-10 13:08:20 -0700688
ztenghuid2dcd6f2014-10-29 16:04:29 -0700689// Find the right polygon edge to shoot the ray at.
690inline int findPolyIndex(bool isPositiveCross, int startPolyIndex, const Vector2& umbraDir,
691 const Vector2* polyToCentroid, int polyLength) {
692 // Make sure we loop with a bound.
693 for (int i = 0; i < polyLength; i++) {
694 int currentIndex = (i + startPolyIndex) % polyLength;
695 const Vector2& currentToCentroid = polyToCentroid[currentIndex];
696 const Vector2& nextToCentroid = polyToCentroid[(currentIndex + 1) % polyLength];
ztenghui512e6432014-09-10 13:08:20 -0700697
ztenghuid2dcd6f2014-10-29 16:04:29 -0700698 float currentCrossUmbra = currentToCentroid.cross(umbraDir);
699 float umbraCrossNext = umbraDir.cross(nextToCentroid);
700 if (sameDirections(isPositiveCross, currentCrossUmbra, umbraCrossNext)) {
ztenghui512e6432014-09-10 13:08:20 -0700701#if DEBUG_SHADOW
ztenghuid2dcd6f2014-10-29 16:04:29 -0700702 ALOGD("findPolyIndex loop %d times , index %d", i, currentIndex );
ztenghui512e6432014-09-10 13:08:20 -0700703#endif
ztenghuid2dcd6f2014-10-29 16:04:29 -0700704 return currentIndex;
ztenghui512e6432014-09-10 13:08:20 -0700705 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700706 }
707 LOG_ALWAYS_FATAL("Can't find the right polygon's edge from startPolyIndex %d", startPolyIndex);
708 return -1;
709}
ztenghui512e6432014-09-10 13:08:20 -0700710
ztenghuid2dcd6f2014-10-29 16:04:29 -0700711// Generate the index pair for penumbra / umbra vertices, and more penumbra vertices
712// if needed.
713inline void genNewPenumbraAndPairWithUmbra(const Vector2* penumbra, int penumbraLength,
714 const Vector2* umbra, int umbraLength, Vector2* newPenumbra, int& newPenumbraIndex,
715 IndexPair* verticesPair, int& verticesPairIndex) {
716 // In order to keep everything in just one loop, we need to pre-compute the
717 // closest umbra vertex for the last penumbra vertex.
718 int previousClosestUmbraIndex = getClosestUmbraIndex(penumbra[penumbraLength - 1],
719 umbra, umbraLength);
720 for (int i = 0; i < penumbraLength; i++) {
721 const Vector2& currentPenumbraVertex = penumbra[i];
722 // For current penumbra vertex, starting from previousClosestUmbraIndex,
723 // then check the next one until the distance increase.
724 // The last one before the increase is the umbra vertex we need to pair with.
725 int currentUmbraIndex = previousClosestUmbraIndex;
726 float currentLengthSquared = (currentPenumbraVertex - umbra[currentUmbraIndex]).lengthSquared();
727 int currentClosestUmbraIndex = -1;
728 int indexDelta = 0;
729 for (int j = 1; j < umbraLength; j++) {
730 int newUmbraIndex = (previousClosestUmbraIndex + j) % umbraLength;
731 float newLengthSquared = (currentPenumbraVertex - umbra[newUmbraIndex]).lengthSquared();
732 if (newLengthSquared > currentLengthSquared) {
733 currentClosestUmbraIndex = (previousClosestUmbraIndex + j - 1) % umbraLength;
734 break;
735 } else {
736 currentLengthSquared = newLengthSquared;
737 indexDelta++;
ztenghui512e6432014-09-10 13:08:20 -0700738 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700739 }
740 LOG_ALWAYS_FATAL_IF(currentClosestUmbraIndex == -1, "Can't find a closet umbra vertext at all");
741
742 if (indexDelta > 1) {
743 // For those umbra don't have penumbra, generate new penumbra vertices by interpolation.
744 //
745 // Assuming Pi for penumbra vertices, and Ui for umbra vertices.
746 // In the case like below P1 paired with U1 and P2 paired with U5.
747 // U2 to U4 are unpaired umbra vertices.
748 //
749 // P1 P2
750 // | |
751 // U1 U2 U3 U4 U5
752 //
753 // We will need to generate 3 more penumbra vertices P1.1, P1.2, P1.3
754 // to pair with U2 to U4.
755 //
756 // P1 P1.1 P1.2 P1.3 P2
757 // | | | | |
758 // U1 U2 U3 U4 U5
759 //
760 // That distance ratio b/t Ui to U1 and Ui to U5 decides its paired penumbra
761 // vertex's location.
762 int newPenumbraNumber = indexDelta - 1;
763
764 float accumulatedDeltaLength[newPenumbraNumber];
765 float totalDeltaLength = 0;
766
767 // To save time, cache the previous umbra vertex info outside the loop
768 // and update each loop.
769 Vector2 previousClosestUmbra = umbra[previousClosestUmbraIndex];
770 Vector2 skippedUmbra;
771 // Use umbra data to precompute the length b/t unpaired umbra vertices,
772 // and its ratio against the total length.
773 for (int k = 0; k < indexDelta; k++) {
774 int skippedUmbraIndex = (previousClosestUmbraIndex + k + 1) % umbraLength;
775 skippedUmbra = umbra[skippedUmbraIndex];
776 float currentDeltaLength = (skippedUmbra - previousClosestUmbra).length();
777
778 totalDeltaLength += currentDeltaLength;
779 accumulatedDeltaLength[k] = totalDeltaLength;
780
781 previousClosestUmbra = skippedUmbra;
782 }
783
784 const Vector2& previousPenumbra = penumbra[(i + penumbraLength - 1) % penumbraLength];
785 // Then for each unpaired umbra vertex, create a new penumbra by the ratio,
786 // and pair them togehter.
787 for (int k = 0; k < newPenumbraNumber; k++) {
788 float weightForCurrentPenumbra = 1.0f;
789 if (totalDeltaLength != 0.0f) {
790 weightForCurrentPenumbra = accumulatedDeltaLength[k] / totalDeltaLength;
791 }
792 float weightForPreviousPenumbra = 1.0f - weightForCurrentPenumbra;
793
794 Vector2 interpolatedPenumbra = currentPenumbraVertex * weightForCurrentPenumbra +
795 previousPenumbra * weightForPreviousPenumbra;
796
797 int skippedUmbraIndex = (previousClosestUmbraIndex + k + 1) % umbraLength;
Andreas Gampeedaecc12014-11-10 20:54:07 -0800798 verticesPair[verticesPairIndex].outerIndex = newPenumbraIndex;
799 verticesPair[verticesPairIndex].innerIndex = skippedUmbraIndex;
800 verticesPairIndex++;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700801 newPenumbra[newPenumbraIndex++] = interpolatedPenumbra;
802 }
803 }
Andreas Gampeedaecc12014-11-10 20:54:07 -0800804 verticesPair[verticesPairIndex].outerIndex = newPenumbraIndex;
805 verticesPair[verticesPairIndex].innerIndex = currentClosestUmbraIndex;
806 verticesPairIndex++;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700807 newPenumbra[newPenumbraIndex++] = currentPenumbraVertex;
808
809 previousClosestUmbraIndex = currentClosestUmbraIndex;
810 }
811}
812
813// Precompute all the polygon's vector, return true if the reference cross product is positive.
814inline bool genPolyToCentroid(const Vector2* poly2d, int polyLength,
815 const Vector2& centroid, Vector2* polyToCentroid) {
816 for (int j = 0; j < polyLength; j++) {
817 polyToCentroid[j] = poly2d[j] - centroid;
818 }
819 float refCrossProduct = 0;
820 for (int j = 0; j < polyLength; j++) {
821 refCrossProduct = polyToCentroid[j].cross(polyToCentroid[(j + 1) % polyLength]);
822 if (refCrossProduct != 0) {
823 break;
ztenghui512e6432014-09-10 13:08:20 -0700824 }
825 }
826
ztenghuid2dcd6f2014-10-29 16:04:29 -0700827 return refCrossProduct > 0;
828}
ztenghui512e6432014-09-10 13:08:20 -0700829
ztenghuid2dcd6f2014-10-29 16:04:29 -0700830// For one umbra vertex, shoot an ray from centroid to it.
831// If the ray hit the polygon first, then return the intersection point as the
832// closer vertex.
833inline Vector2 getCloserVertex(const Vector2& umbraVertex, const Vector2& centroid,
834 const Vector2* poly2d, int polyLength, const Vector2* polyToCentroid,
835 bool isPositiveCross, int& previousPolyIndex) {
836 Vector2 umbraToCentroid = umbraVertex - centroid;
837 float distanceToUmbra = umbraToCentroid.length();
838 umbraToCentroid = umbraToCentroid / distanceToUmbra;
839
840 // previousPolyIndex is updated for each item such that we can minimize the
841 // looping inside findPolyIndex();
842 previousPolyIndex = findPolyIndex(isPositiveCross, previousPolyIndex,
843 umbraToCentroid, polyToCentroid, polyLength);
844
845 float dx = umbraToCentroid.x;
846 float dy = umbraToCentroid.y;
847 float distanceToIntersectPoly = rayIntersectPoints(centroid, dx, dy,
848 poly2d[previousPolyIndex], poly2d[(previousPolyIndex + 1) % polyLength]);
849 if (distanceToIntersectPoly < 0) {
850 distanceToIntersectPoly = 0;
851 }
852
853 // Pick the closer one as the occluded area vertex.
854 Vector2 closerVertex;
855 if (distanceToIntersectPoly < distanceToUmbra) {
856 closerVertex.x = centroid.x + dx * distanceToIntersectPoly;
857 closerVertex.y = centroid.y + dy * distanceToIntersectPoly;
858 } else {
859 closerVertex = umbraVertex;
860 }
861
862 return closerVertex;
ztenghui512e6432014-09-10 13:08:20 -0700863}
864
865/**
866 * Generate a triangle strip given two convex polygon
867**/
868void SpotShadow::generateTriangleStrip(bool isCasterOpaque, float shadowStrengthScale,
869 Vector2* penumbra, int penumbraLength, Vector2* umbra, int umbraLength,
870 const Vector3* poly, int polyLength, VertexBuffer& shadowTriangleStrip,
871 const Vector2& centroid) {
ztenghui512e6432014-09-10 13:08:20 -0700872 bool hasOccludedUmbraArea = false;
873 Vector2 poly2d[polyLength];
874
875 if (isCasterOpaque) {
876 for (int i = 0; i < polyLength; i++) {
877 poly2d[i].x = poly[i].x;
878 poly2d[i].y = poly[i].y;
879 }
880 // Make sure the centroid is inside the umbra, otherwise, fall back to the
881 // approach as if there is no occluded umbra area.
882 if (testPointInsidePolygon(centroid, poly2d, polyLength)) {
883 hasOccludedUmbraArea = true;
884 }
885 }
886
ztenghuid2dcd6f2014-10-29 16:04:29 -0700887 // For each penumbra vertex, find its corresponding closest umbra vertex index.
888 //
889 // Penumbra Vertices marked as Pi
890 // Umbra Vertices marked as Ui
891 // (P3)
892 // (P2) | ' (P4)
893 // (P1)' | | '
894 // ' | | '
895 // (P0) ------------------------------------------------(P5)
896 // | (U0) |(U1)
897 // | |
898 // | |(U2) (P5.1)
899 // | |
900 // | |
901 // | |
902 // | |
903 // | |
904 // | |
905 // (U4)-----------------------------------(U3) (P6)
906 //
907 // At least, like P0, P1, P2, they will find the matching umbra as U0.
908 // If we jump over some umbra vertex without matching penumbra vertex, then
909 // we will generate some new penumbra vertex by interpolation. Like P6 is
910 // matching U3, but U2 is not matched with any penumbra vertex.
911 // So interpolate P5.1 out and match U2.
912 // In this way, every umbra vertex will have a matching penumbra vertex.
913 //
914 // The total pair number can be as high as umbraLength + penumbraLength.
915 const int maxNewPenumbraLength = umbraLength + penumbraLength;
916 IndexPair verticesPair[maxNewPenumbraLength];
917 int verticesPairIndex = 0;
918
919 // Cache all the existing penumbra vertices and newly interpolated vertices into a
920 // a new array.
921 Vector2 newPenumbra[maxNewPenumbraLength];
922 int newPenumbraIndex = 0;
923
924 // For each penumbra vertex, find its closet umbra vertex by comparing the
925 // neighbor umbra vertices.
926 genNewPenumbraAndPairWithUmbra(penumbra, penumbraLength, umbra, umbraLength, newPenumbra,
927 newPenumbraIndex, verticesPair, verticesPairIndex);
928 ShadowTessellator::checkOverflow(verticesPairIndex, maxNewPenumbraLength, "Spot pair");
929 ShadowTessellator::checkOverflow(newPenumbraIndex, maxNewPenumbraLength, "Spot new penumbra");
930#if DEBUG_SHADOW
931 for (int i = 0; i < umbraLength; i++) {
932 ALOGD("umbra i %d, [%f, %f]", i, umbra[i].x, umbra[i].y);
ztenghui512e6432014-09-10 13:08:20 -0700933 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700934 for (int i = 0; i < newPenumbraIndex; i++) {
935 ALOGD("new penumbra i %d, [%f, %f]", i, newPenumbra[i].x, newPenumbra[i].y);
936 }
937 for (int i = 0; i < verticesPairIndex; i++) {
938 ALOGD("index i %d, [%d, %d]", i, verticesPair[i].outerIndex, verticesPair[i].innerIndex);
939 }
940#endif
ztenghui512e6432014-09-10 13:08:20 -0700941
ztenghuid2dcd6f2014-10-29 16:04:29 -0700942 // For the size of vertex buffer, we need 3 rings, one has newPenumbraSize,
943 // one has umbraLength, the last one has at most umbraLength.
944 //
945 // For the size of index buffer, the umbra area needs (2 * umbraLength + 2).
946 // The penumbra one can vary a bit, but it is bounded by (2 * verticesPairIndex + 2).
947 // And 2 more for jumping between penumbra to umbra.
948 const int newPenumbraLength = newPenumbraIndex;
949 const int totalVertexCount = newPenumbraLength + umbraLength * 2;
950 const int totalIndexCount = 2 * umbraLength + 2 * verticesPairIndex + 6;
ztenghui512e6432014-09-10 13:08:20 -0700951 AlphaVertex* shadowVertices =
952 shadowTriangleStrip.alloc<AlphaVertex>(totalVertexCount);
953 uint16_t* indexBuffer =
954 shadowTriangleStrip.allocIndices<uint16_t>(totalIndexCount);
ztenghui512e6432014-09-10 13:08:20 -0700955 int vertexBufferIndex = 0;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700956 int indexBufferIndex = 0;
ztenghui512e6432014-09-10 13:08:20 -0700957
ztenghuid2dcd6f2014-10-29 16:04:29 -0700958 // Fill the IB and VB for the penumbra area.
959 for (int i = 0; i < newPenumbraLength; i++) {
960 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], newPenumbra[i].x,
961 newPenumbra[i].y, 0.0f);
962 }
963 for (int i = 0; i < umbraLength; i++) {
964 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], umbra[i].x, umbra[i].y,
965 M_PI);
ztenghui512e6432014-09-10 13:08:20 -0700966 }
967
ztenghuid2dcd6f2014-10-29 16:04:29 -0700968 for (int i = 0; i < verticesPairIndex; i++) {
969 indexBuffer[indexBufferIndex++] = verticesPair[i].outerIndex;
970 // All umbra index need to be offseted by newPenumbraSize.
971 indexBuffer[indexBufferIndex++] = verticesPair[i].innerIndex + newPenumbraLength;
972 }
973 indexBuffer[indexBufferIndex++] = verticesPair[0].outerIndex;
974 indexBuffer[indexBufferIndex++] = verticesPair[0].innerIndex + newPenumbraLength;
ztenghui512e6432014-09-10 13:08:20 -0700975
ztenghuid2dcd6f2014-10-29 16:04:29 -0700976 // Now fill the IB and VB for the umbra area.
977 // First duplicated the index from previous strip and the first one for the
978 // degenerated triangles.
979 indexBuffer[indexBufferIndex] = indexBuffer[indexBufferIndex - 1];
980 indexBufferIndex++;
981 indexBuffer[indexBufferIndex++] = newPenumbraLength + 0;
982 // Save the first VB index for umbra area in order to close the loop.
983 int savedStartIndex = vertexBufferIndex;
984
ztenghui512e6432014-09-10 13:08:20 -0700985 if (hasOccludedUmbraArea) {
ztenghuid2dcd6f2014-10-29 16:04:29 -0700986 // Precompute all the polygon's vector, and the reference cross product,
987 // in order to find the right polygon edge for the ray to intersect.
988 Vector2 polyToCentroid[polyLength];
989 bool isPositiveCross = genPolyToCentroid(poly2d, polyLength, centroid, polyToCentroid);
ztenghui512e6432014-09-10 13:08:20 -0700990
ztenghuid2dcd6f2014-10-29 16:04:29 -0700991 // Because both the umbra and polygon are going in the same direction,
992 // we can save the previous polygon index to make sure we have less polygon
993 // vertex to compute for each ray.
994 int previousPolyIndex = 0;
995 for (int i = 0; i < umbraLength; i++) {
996 // Shoot a ray from centroid to each umbra vertices and pick the one with
997 // shorter distance to the centroid, b/t the umbra vertex or the intersection point.
998 Vector2 closerVertex = getCloserVertex(umbra[i], centroid, poly2d, polyLength,
999 polyToCentroid, isPositiveCross, previousPolyIndex);
1000
1001 // We already stored the umbra vertices, just need to add the occlued umbra's ones.
1002 indexBuffer[indexBufferIndex++] = newPenumbraLength + i;
1003 indexBuffer[indexBufferIndex++] = vertexBufferIndex;
1004 AlphaVertex::set(&shadowVertices[vertexBufferIndex++],
1005 closerVertex.x, closerVertex.y, M_PI);
ztenghui512e6432014-09-10 13:08:20 -07001006 }
ztenghui512e6432014-09-10 13:08:20 -07001007 } else {
ztenghuid2dcd6f2014-10-29 16:04:29 -07001008 // If there is no occluded umbra at all, then draw the triangle fan
1009 // starting from the centroid to all umbra vertices.
ztenghui512e6432014-09-10 13:08:20 -07001010 int lastCentroidIndex = vertexBufferIndex;
1011 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], centroid.x,
ztenghuid2dcd6f2014-10-29 16:04:29 -07001012 centroid.y, M_PI);
1013 for (int i = 0; i < umbraLength; i++) {
1014 indexBuffer[indexBufferIndex++] = newPenumbraLength + i;
ztenghui512e6432014-09-10 13:08:20 -07001015 indexBuffer[indexBufferIndex++] = lastCentroidIndex;
1016 }
ztenghui512e6432014-09-10 13:08:20 -07001017 }
ztenghuid2dcd6f2014-10-29 16:04:29 -07001018 // Closing the umbra area triangle's loop here.
1019 indexBuffer[indexBufferIndex++] = newPenumbraLength;
1020 indexBuffer[indexBufferIndex++] = savedStartIndex;
ztenghui512e6432014-09-10 13:08:20 -07001021
1022 // At the end, update the real index and vertex buffer size.
1023 shadowTriangleStrip.updateVertexCount(vertexBufferIndex);
1024 shadowTriangleStrip.updateIndexCount(indexBufferIndex);
1025 ShadowTessellator::checkOverflow(vertexBufferIndex, totalVertexCount, "Spot Vertex Buffer");
1026 ShadowTessellator::checkOverflow(indexBufferIndex, totalIndexCount, "Spot Index Buffer");
1027
1028 shadowTriangleStrip.setMode(VertexBuffer::kIndices);
1029 shadowTriangleStrip.computeBounds<AlphaVertex>();
1030}
1031
ztenghuif5ca8b42014-01-27 15:53:28 -08001032#if DEBUG_SHADOW
1033
1034#define TEST_POINT_NUMBER 128
ztenghuif5ca8b42014-01-27 15:53:28 -08001035/**
1036 * Calculate the bounds for generating random test points.
1037 */
1038void SpotShadow::updateBound(const Vector2 inVector, Vector2& lowerBound,
ztenghui512e6432014-09-10 13:08:20 -07001039 Vector2& upperBound) {
ztenghuif5ca8b42014-01-27 15:53:28 -08001040 if (inVector.x < lowerBound.x) {
1041 lowerBound.x = inVector.x;
1042 }
1043
1044 if (inVector.y < lowerBound.y) {
1045 lowerBound.y = inVector.y;
1046 }
1047
1048 if (inVector.x > upperBound.x) {
1049 upperBound.x = inVector.x;
1050 }
1051
1052 if (inVector.y > upperBound.y) {
1053 upperBound.y = inVector.y;
1054 }
1055}
1056
1057/**
1058 * For debug purpose, when things go wrong, dump the whole polygon data.
1059 */
ztenghuic50a03d2014-08-21 13:47:54 -07001060void SpotShadow::dumpPolygon(const Vector2* poly, int polyLength, const char* polyName) {
1061 for (int i = 0; i < polyLength; i++) {
1062 ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
1063 }
1064}
1065
1066/**
1067 * For debug purpose, when things go wrong, dump the whole polygon data.
1068 */
1069void SpotShadow::dumpPolygon(const Vector3* poly, int polyLength, const char* polyName) {
ztenghuif5ca8b42014-01-27 15:53:28 -08001070 for (int i = 0; i < polyLength; i++) {
1071 ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
1072 }
1073}
1074
1075/**
1076 * Test whether the polygon is convex.
1077 */
1078bool SpotShadow::testConvex(const Vector2* polygon, int polygonLength,
1079 const char* name) {
1080 bool isConvex = true;
1081 for (int i = 0; i < polygonLength; i++) {
1082 Vector2 start = polygon[i];
1083 Vector2 middle = polygon[(i + 1) % polygonLength];
1084 Vector2 end = polygon[(i + 2) % polygonLength];
1085
ztenghui9122b1b2014-10-03 11:21:11 -07001086 float delta = (float(middle.x) - start.x) * (float(end.y) - start.y) -
1087 (float(middle.y) - start.y) * (float(end.x) - start.x);
ztenghuif5ca8b42014-01-27 15:53:28 -08001088 bool isCCWOrCoLinear = (delta >= EPSILON);
1089
1090 if (isCCWOrCoLinear) {
ztenghui50ecf842014-03-11 16:52:30 -07001091 ALOGW("(Error Type 2): polygon (%s) is not a convex b/c start (x %f, y %f),"
ztenghuif5ca8b42014-01-27 15:53:28 -08001092 "middle (x %f, y %f) and end (x %f, y %f) , delta is %f !!!",
1093 name, start.x, start.y, middle.x, middle.y, end.x, end.y, delta);
1094 isConvex = false;
1095 break;
1096 }
1097 }
1098 return isConvex;
1099}
1100
1101/**
1102 * Test whether or not the polygon (intersection) is within the 2 input polygons.
1103 * Using Marte Carlo method, we generate a random point, and if it is inside the
1104 * intersection, then it must be inside both source polygons.
1105 */
1106void SpotShadow::testIntersection(const Vector2* poly1, int poly1Length,
1107 const Vector2* poly2, int poly2Length,
1108 const Vector2* intersection, int intersectionLength) {
1109 // Find the min and max of x and y.
ztenghuic50a03d2014-08-21 13:47:54 -07001110 Vector2 lowerBound = {FLT_MAX, FLT_MAX};
1111 Vector2 upperBound = {-FLT_MAX, -FLT_MAX};
ztenghuif5ca8b42014-01-27 15:53:28 -08001112 for (int i = 0; i < poly1Length; i++) {
1113 updateBound(poly1[i], lowerBound, upperBound);
1114 }
1115 for (int i = 0; i < poly2Length; i++) {
1116 updateBound(poly2[i], lowerBound, upperBound);
1117 }
1118
1119 bool dumpPoly = false;
1120 for (int k = 0; k < TEST_POINT_NUMBER; k++) {
1121 // Generate a random point between minX, minY and maxX, maxY.
ztenghui9122b1b2014-10-03 11:21:11 -07001122 float randomX = rand() / float(RAND_MAX);
1123 float randomY = rand() / float(RAND_MAX);
ztenghuif5ca8b42014-01-27 15:53:28 -08001124
1125 Vector2 testPoint;
1126 testPoint.x = lowerBound.x + randomX * (upperBound.x - lowerBound.x);
1127 testPoint.y = lowerBound.y + randomY * (upperBound.y - lowerBound.y);
1128
1129 // If the random point is in both poly 1 and 2, then it must be intersection.
1130 if (testPointInsidePolygon(testPoint, intersection, intersectionLength)) {
1131 if (!testPointInsidePolygon(testPoint, poly1, poly1Length)) {
1132 dumpPoly = true;
ztenghui50ecf842014-03-11 16:52:30 -07001133 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
ztenghui512e6432014-09-10 13:08:20 -07001134 " not in the poly1",
ztenghuif5ca8b42014-01-27 15:53:28 -08001135 testPoint.x, testPoint.y);
1136 }
1137
1138 if (!testPointInsidePolygon(testPoint, poly2, poly2Length)) {
1139 dumpPoly = true;
ztenghui50ecf842014-03-11 16:52:30 -07001140 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
ztenghui512e6432014-09-10 13:08:20 -07001141 " not in the poly2",
ztenghuif5ca8b42014-01-27 15:53:28 -08001142 testPoint.x, testPoint.y);
1143 }
1144 }
1145 }
1146
1147 if (dumpPoly) {
1148 dumpPolygon(intersection, intersectionLength, "intersection");
1149 for (int i = 1; i < intersectionLength; i++) {
1150 Vector2 delta = intersection[i] - intersection[i - 1];
1151 ALOGD("Intersetion i, %d Vs i-1 is delta %f", i, delta.lengthSquared());
1152 }
1153
1154 dumpPolygon(poly1, poly1Length, "poly 1");
1155 dumpPolygon(poly2, poly2Length, "poly 2");
1156 }
1157}
1158#endif
1159
ztenghui7b4516e2014-01-07 10:42:55 -08001160}; // namespace uirenderer
1161}; // namespace android