blob: db3c2d9a5060a5389e171c254cbd65672ef1ec87 [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
ztenghuiecf091e2015-02-17 13:26:10 -080047// For performance, we use (1 - alpha) value for the shader input.
48#define TRANSFORMED_PENUMBRA_ALPHA 1.0f
49#define TRANSFORMED_UMBRA_ALPHA 0.0f
ztenghui7b4516e2014-01-07 10:42:55 -080050
51#include <math.h>
ztenghuif5ca8b42014-01-27 15:53:28 -080052#include <stdlib.h>
ztenghui7b4516e2014-01-07 10:42:55 -080053#include <utils/Log.h>
54
ztenghui63d41ab2014-02-14 13:13:41 -080055#include "ShadowTessellator.h"
ztenghui7b4516e2014-01-07 10:42:55 -080056#include "SpotShadow.h"
57#include "Vertex.h"
Tom Hudson2dc236b2014-10-15 15:46:42 -040058#include "VertexBuffer.h"
ztenghuic50a03d2014-08-21 13:47:54 -070059#include "utils/MathUtils.h"
ztenghui7b4516e2014-01-07 10:42:55 -080060
ztenghuic50a03d2014-08-21 13:47:54 -070061// TODO: After we settle down the new algorithm, we can remove the old one and
62// its utility functions.
63// Right now, we still need to keep it for comparison purpose and future expansion.
ztenghui7b4516e2014-01-07 10:42:55 -080064namespace android {
65namespace uirenderer {
66
ztenghui9122b1b2014-10-03 11:21:11 -070067static const float EPSILON = 1e-7;
Chris Craik726118b2014-03-07 18:27:49 -080068
ztenghui7b4516e2014-01-07 10:42:55 -080069/**
ztenghuic50a03d2014-08-21 13:47:54 -070070 * For each polygon's vertex, the light center will project it to the receiver
71 * as one of the outline vertex.
72 * For each outline vertex, we need to store the position and normal.
73 * Normal here is defined against the edge by the current vertex and the next vertex.
74 */
75struct OutlineData {
76 Vector2 position;
77 Vector2 normal;
78 float radius;
79};
80
81/**
ztenghui512e6432014-09-10 13:08:20 -070082 * For each vertex, we need to keep track of its angle, whether it is penumbra or
83 * umbra, and its corresponding vertex index.
84 */
85struct SpotShadow::VertexAngleData {
86 // The angle to the vertex from the centroid.
87 float mAngle;
88 // True is the vertex comes from penumbra, otherwise it comes from umbra.
89 bool mIsPenumbra;
90 // The index of the vertex described by this data.
91 int mVertexIndex;
92 void set(float angle, bool isPenumbra, int index) {
93 mAngle = angle;
94 mIsPenumbra = isPenumbra;
95 mVertexIndex = index;
96 }
97};
98
99/**
Chris Craik726118b2014-03-07 18:27:49 -0800100 * Calculate the angle between and x and a y coordinate.
101 * The atan2 range from -PI to PI.
ztenghui7b4516e2014-01-07 10:42:55 -0800102 */
Chris Craikb79a3e32014-03-11 12:20:17 -0700103static float angle(const Vector2& point, const Vector2& center) {
Chris Craik726118b2014-03-07 18:27:49 -0800104 return atan2(point.y - center.y, point.x - center.x);
105}
106
107/**
108 * Calculate the intersection of a ray with the line segment defined by two points.
109 *
110 * Returns a negative value in error conditions.
111
112 * @param rayOrigin The start of the ray
113 * @param dx The x vector of the ray
114 * @param dy The y vector of the ray
115 * @param p1 The first point defining the line segment
116 * @param p2 The second point defining the line segment
117 * @return The distance along the ray if it intersects with the line segment, negative if otherwise
118 */
Chris Craikb79a3e32014-03-11 12:20:17 -0700119static float rayIntersectPoints(const Vector2& rayOrigin, float dx, float dy,
Chris Craik726118b2014-03-07 18:27:49 -0800120 const Vector2& p1, const Vector2& p2) {
121 // The math below is derived from solving this formula, basically the
122 // intersection point should stay on both the ray and the edge of (p1, p2).
123 // solve([p1x+t*(p2x-p1x)=dx*t2+px,p1y+t*(p2y-p1y)=dy*t2+py],[t,t2]);
124
ztenghui9122b1b2014-10-03 11:21:11 -0700125 float divisor = (dx * (p1.y - p2.y) + dy * p2.x - dy * p1.x);
Chris Craik726118b2014-03-07 18:27:49 -0800126 if (divisor == 0) return -1.0f; // error, invalid divisor
127
128#if DEBUG_SHADOW
ztenghui9122b1b2014-10-03 11:21:11 -0700129 float interpVal = (dx * (p1.y - rayOrigin.y) + dy * rayOrigin.x - dy * p1.x) / divisor;
ztenghui99af9422014-03-14 14:35:54 -0700130 if (interpVal < 0 || interpVal > 1) {
131 ALOGW("rayIntersectPoints is hitting outside the segment %f", interpVal);
132 }
Chris Craik726118b2014-03-07 18:27:49 -0800133#endif
134
ztenghui9122b1b2014-10-03 11:21:11 -0700135 float distance = (p1.x * (rayOrigin.y - p2.y) + p2.x * (p1.y - rayOrigin.y) +
Chris Craik726118b2014-03-07 18:27:49 -0800136 rayOrigin.x * (p2.y - p1.y)) / divisor;
137
138 return distance; // may be negative in error cases
ztenghui7b4516e2014-01-07 10:42:55 -0800139}
140
141/**
ztenghui7b4516e2014-01-07 10:42:55 -0800142 * Sort points by their X coordinates
143 *
144 * @param points the points as a Vector2 array.
145 * @param pointsLength the number of vertices of the polygon.
146 */
147void SpotShadow::xsort(Vector2* points, int pointsLength) {
148 quicksortX(points, 0, pointsLength - 1);
149}
150
151/**
152 * compute the convex hull of a collection of Points
153 *
154 * @param points the points as a Vector2 array.
155 * @param pointsLength the number of vertices of the polygon.
156 * @param retPoly pre allocated array of floats to put the vertices
157 * @return the number of points in the polygon 0 if no intersection
158 */
159int SpotShadow::hull(Vector2* points, int pointsLength, Vector2* retPoly) {
160 xsort(points, pointsLength);
161 int n = pointsLength;
162 Vector2 lUpper[n];
163 lUpper[0] = points[0];
164 lUpper[1] = points[1];
165
166 int lUpperSize = 2;
167
168 for (int i = 2; i < n; i++) {
169 lUpper[lUpperSize] = points[i];
170 lUpperSize++;
171
ztenghuif5ca8b42014-01-27 15:53:28 -0800172 while (lUpperSize > 2 && !ccw(
173 lUpper[lUpperSize - 3].x, lUpper[lUpperSize - 3].y,
174 lUpper[lUpperSize - 2].x, lUpper[lUpperSize - 2].y,
175 lUpper[lUpperSize - 1].x, lUpper[lUpperSize - 1].y)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800176 // Remove the middle point of the three last
177 lUpper[lUpperSize - 2].x = lUpper[lUpperSize - 1].x;
178 lUpper[lUpperSize - 2].y = lUpper[lUpperSize - 1].y;
179 lUpperSize--;
180 }
181 }
182
183 Vector2 lLower[n];
184 lLower[0] = points[n - 1];
185 lLower[1] = points[n - 2];
186
187 int lLowerSize = 2;
188
189 for (int i = n - 3; i >= 0; i--) {
190 lLower[lLowerSize] = points[i];
191 lLowerSize++;
192
ztenghuif5ca8b42014-01-27 15:53:28 -0800193 while (lLowerSize > 2 && !ccw(
194 lLower[lLowerSize - 3].x, lLower[lLowerSize - 3].y,
195 lLower[lLowerSize - 2].x, lLower[lLowerSize - 2].y,
196 lLower[lLowerSize - 1].x, lLower[lLowerSize - 1].y)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800197 // Remove the middle point of the three last
198 lLower[lLowerSize - 2] = lLower[lLowerSize - 1];
199 lLowerSize--;
200 }
201 }
ztenghui7b4516e2014-01-07 10:42:55 -0800202
Chris Craik726118b2014-03-07 18:27:49 -0800203 // output points in CW ordering
204 const int total = lUpperSize + lLowerSize - 2;
205 int outIndex = total - 1;
ztenghui7b4516e2014-01-07 10:42:55 -0800206 for (int i = 0; i < lUpperSize; i++) {
Chris Craik726118b2014-03-07 18:27:49 -0800207 retPoly[outIndex] = lUpper[i];
208 outIndex--;
ztenghui7b4516e2014-01-07 10:42:55 -0800209 }
210
211 for (int i = 1; i < lLowerSize - 1; i++) {
Chris Craik726118b2014-03-07 18:27:49 -0800212 retPoly[outIndex] = lLower[i];
213 outIndex--;
ztenghui7b4516e2014-01-07 10:42:55 -0800214 }
215 // TODO: Add test harness which verify that all the points are inside the hull.
Chris Craik726118b2014-03-07 18:27:49 -0800216 return total;
ztenghui7b4516e2014-01-07 10:42:55 -0800217}
218
219/**
ztenghuif5ca8b42014-01-27 15:53:28 -0800220 * Test whether the 3 points form a counter clockwise turn.
ztenghui7b4516e2014-01-07 10:42:55 -0800221 *
ztenghui7b4516e2014-01-07 10:42:55 -0800222 * @return true if a right hand turn
223 */
ztenghui9122b1b2014-10-03 11:21:11 -0700224bool SpotShadow::ccw(float ax, float ay, float bx, float by,
225 float cx, float cy) {
ztenghui7b4516e2014-01-07 10:42:55 -0800226 return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > EPSILON;
227}
228
229/**
ztenghui7b4516e2014-01-07 10:42:55 -0800230 * Sort points about a center point
231 *
232 * @param poly The in and out polyogon as a Vector2 array.
233 * @param polyLength The number of vertices of the polygon.
234 * @param center the center ctr[0] = x , ctr[1] = y to sort around.
235 */
236void SpotShadow::sort(Vector2* poly, int polyLength, const Vector2& center) {
237 quicksortCirc(poly, 0, polyLength - 1, center);
238}
239
240/**
ztenghui7b4516e2014-01-07 10:42:55 -0800241 * Swap points pointed to by i and j
242 */
243void SpotShadow::swap(Vector2* points, int i, int j) {
244 Vector2 temp = points[i];
245 points[i] = points[j];
246 points[j] = temp;
247}
248
249/**
250 * quick sort implementation about the center.
251 */
252void SpotShadow::quicksortCirc(Vector2* points, int low, int high,
253 const Vector2& center) {
254 int i = low, j = high;
255 int p = low + (high - low) / 2;
256 float pivot = angle(points[p], center);
257 while (i <= j) {
Chris Craik726118b2014-03-07 18:27:49 -0800258 while (angle(points[i], center) > pivot) {
ztenghui7b4516e2014-01-07 10:42:55 -0800259 i++;
260 }
Chris Craik726118b2014-03-07 18:27:49 -0800261 while (angle(points[j], center) < pivot) {
ztenghui7b4516e2014-01-07 10:42:55 -0800262 j--;
263 }
264
265 if (i <= j) {
266 swap(points, i, j);
267 i++;
268 j--;
269 }
270 }
271 if (low < j) quicksortCirc(points, low, j, center);
272 if (i < high) quicksortCirc(points, i, high, center);
273}
274
275/**
276 * Sort points by x axis
277 *
278 * @param points points to sort
279 * @param low start index
280 * @param high end index
281 */
282void SpotShadow::quicksortX(Vector2* points, int low, int high) {
283 int i = low, j = high;
284 int p = low + (high - low) / 2;
285 float pivot = points[p].x;
286 while (i <= j) {
287 while (points[i].x < pivot) {
288 i++;
289 }
290 while (points[j].x > pivot) {
291 j--;
292 }
293
294 if (i <= j) {
295 swap(points, i, j);
296 i++;
297 j--;
298 }
299 }
300 if (low < j) quicksortX(points, low, j);
301 if (i < high) quicksortX(points, i, high);
302}
303
304/**
305 * Test whether a point is inside the polygon.
306 *
307 * @param testPoint the point to test
308 * @param poly the polygon
309 * @return true if the testPoint is inside the poly.
310 */
311bool SpotShadow::testPointInsidePolygon(const Vector2 testPoint,
312 const Vector2* poly, int len) {
313 bool c = false;
ztenghui9122b1b2014-10-03 11:21:11 -0700314 float testx = testPoint.x;
315 float testy = testPoint.y;
ztenghui7b4516e2014-01-07 10:42:55 -0800316 for (int i = 0, j = len - 1; i < len; j = i++) {
ztenghui9122b1b2014-10-03 11:21:11 -0700317 float startX = poly[j].x;
318 float startY = poly[j].y;
319 float endX = poly[i].x;
320 float endY = poly[i].y;
ztenghui7b4516e2014-01-07 10:42:55 -0800321
ztenghui512e6432014-09-10 13:08:20 -0700322 if (((endY > testy) != (startY > testy))
323 && (testx < (startX - endX) * (testy - endY)
ztenghui7b4516e2014-01-07 10:42:55 -0800324 / (startY - endY) + endX)) {
325 c = !c;
326 }
327 }
328 return c;
329}
330
331/**
332 * Make the polygon turn clockwise.
333 *
334 * @param polygon the polygon as a Vector2 array.
335 * @param len the number of points of the polygon
336 */
337void SpotShadow::makeClockwise(Vector2* polygon, int len) {
Chris Craikd41c4d82015-01-05 15:51:13 -0800338 if (polygon == nullptr || len == 0) {
ztenghui7b4516e2014-01-07 10:42:55 -0800339 return;
340 }
ztenghui2e023f32014-04-28 16:43:13 -0700341 if (!ShadowTessellator::isClockwise(polygon, len)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800342 reverse(polygon, len);
343 }
344}
345
346/**
ztenghui7b4516e2014-01-07 10:42:55 -0800347 * Reverse the polygon
348 *
349 * @param polygon the polygon as a Vector2 array
350 * @param len the number of points of the polygon
351 */
352void SpotShadow::reverse(Vector2* polygon, int len) {
353 int n = len / 2;
354 for (int i = 0; i < n; i++) {
355 Vector2 tmp = polygon[i];
356 int k = len - 1 - i;
357 polygon[i] = polygon[k];
358 polygon[k] = tmp;
359 }
360}
361
362/**
ztenghui7b4516e2014-01-07 10:42:55 -0800363 * Compute a horizontal circular polygon about point (x , y , height) of radius
364 * (size)
365 *
366 * @param points number of the points of the output polygon.
367 * @param lightCenter the center of the light.
368 * @param size the light size.
369 * @param ret result polygon.
370 */
371void SpotShadow::computeLightPolygon(int points, const Vector3& lightCenter,
372 float size, Vector3* ret) {
373 // TODO: Caching all the sin / cos values and store them in a look up table.
374 for (int i = 0; i < points; i++) {
ztenghui9122b1b2014-10-03 11:21:11 -0700375 float angle = 2 * i * M_PI / points;
Chris Craik726118b2014-03-07 18:27:49 -0800376 ret[i].x = cosf(angle) * size + lightCenter.x;
377 ret[i].y = sinf(angle) * size + lightCenter.y;
ztenghui7b4516e2014-01-07 10:42:55 -0800378 ret[i].z = lightCenter.z;
379 }
380}
381
382/**
ztenghui512e6432014-09-10 13:08:20 -0700383 * From light center, project one vertex to the z=0 surface and get the outline.
ztenghui7b4516e2014-01-07 10:42:55 -0800384 *
ztenghui512e6432014-09-10 13:08:20 -0700385 * @param outline The result which is the outline position.
386 * @param lightCenter The center of light.
387 * @param polyVertex The input polygon's vertex.
388 *
389 * @return float The ratio of (polygon.z / light.z - polygon.z)
ztenghui7b4516e2014-01-07 10:42:55 -0800390 */
ztenghuic50a03d2014-08-21 13:47:54 -0700391float SpotShadow::projectCasterToOutline(Vector2& outline,
392 const Vector3& lightCenter, const Vector3& polyVertex) {
393 float lightToPolyZ = lightCenter.z - polyVertex.z;
394 float ratioZ = CASTER_Z_CAP_RATIO;
395 if (lightToPolyZ != 0) {
396 // If any caster's vertex is almost above the light, we just keep it as 95%
397 // of the height of the light.
ztenghui3bd3fa12014-08-25 14:42:27 -0700398 ratioZ = MathUtils::clamp(polyVertex.z / lightToPolyZ, 0.0f, CASTER_Z_CAP_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700399 }
400
401 outline.x = polyVertex.x - ratioZ * (lightCenter.x - polyVertex.x);
402 outline.y = polyVertex.y - ratioZ * (lightCenter.y - polyVertex.y);
403 return ratioZ;
404}
405
406/**
407 * Generate the shadow spot light of shape lightPoly and a object poly
408 *
409 * @param isCasterOpaque whether the caster is opaque
410 * @param lightCenter the center of the light
411 * @param lightSize the radius of the light
412 * @param poly x,y,z vertexes of a convex polygon that occludes the light source
413 * @param polyLength number of vertexes of the occluding polygon
414 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
415 * empty strip if error.
416 */
417void SpotShadow::createSpotShadow(bool isCasterOpaque, const Vector3& lightCenter,
418 float lightSize, const Vector3* poly, int polyLength, const Vector3& polyCentroid,
419 VertexBuffer& shadowTriangleStrip) {
ztenghui3bd3fa12014-08-25 14:42:27 -0700420 if (CC_UNLIKELY(lightCenter.z <= 0)) {
421 ALOGW("Relative Light Z is not positive. No spot shadow!");
422 return;
423 }
ztenghui512e6432014-09-10 13:08:20 -0700424 if (CC_UNLIKELY(polyLength < 3)) {
425#if DEBUG_SHADOW
426 ALOGW("Invalid polygon length. No spot shadow!");
427#endif
428 return;
429 }
ztenghuic50a03d2014-08-21 13:47:54 -0700430 OutlineData outlineData[polyLength];
431 Vector2 outlineCentroid;
432 // Calculate the projected outline for each polygon's vertices from the light center.
433 //
434 // O Light
435 // /
436 // /
437 // . Polygon vertex
438 // /
439 // /
440 // O Outline vertices
441 //
442 // Ratio = (Poly - Outline) / (Light - Poly)
443 // Outline.x = Poly.x - Ratio * (Light.x - Poly.x)
444 // Outline's radius / Light's radius = Ratio
445
446 // Compute the last outline vertex to make sure we can get the normal and outline
447 // in one single loop.
448 projectCasterToOutline(outlineData[polyLength - 1].position, lightCenter,
449 poly[polyLength - 1]);
450
451 // Take the outline's polygon, calculate the normal for each outline edge.
452 int currentNormalIndex = polyLength - 1;
453 int nextNormalIndex = 0;
454
455 for (int i = 0; i < polyLength; i++) {
456 float ratioZ = projectCasterToOutline(outlineData[i].position,
457 lightCenter, poly[i]);
458 outlineData[i].radius = ratioZ * lightSize;
459
460 outlineData[currentNormalIndex].normal = ShadowTessellator::calculateNormal(
461 outlineData[currentNormalIndex].position,
462 outlineData[nextNormalIndex].position);
463 currentNormalIndex = (currentNormalIndex + 1) % polyLength;
464 nextNormalIndex++;
465 }
466
467 projectCasterToOutline(outlineCentroid, lightCenter, polyCentroid);
468
469 int penumbraIndex = 0;
ztenghui512e6432014-09-10 13:08:20 -0700470 // Then each polygon's vertex produce at minmal 2 penumbra vertices.
471 // Since the size can be dynamic here, we keep track of the size and update
472 // the real size at the end.
473 int allocatedPenumbraLength = 2 * polyLength + SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER;
474 Vector2 penumbra[allocatedPenumbraLength];
475 int totalExtraCornerSliceNumber = 0;
ztenghuic50a03d2014-08-21 13:47:54 -0700476
477 Vector2 umbra[polyLength];
ztenghuic50a03d2014-08-21 13:47:54 -0700478
ztenghui512e6432014-09-10 13:08:20 -0700479 // When centroid is covered by all circles from outline, then we consider
480 // the umbra is invalid, and we will tune down the shadow strength.
ztenghuic50a03d2014-08-21 13:47:54 -0700481 bool hasValidUmbra = true;
ztenghui512e6432014-09-10 13:08:20 -0700482 // We need the minimal of RaitoVI to decrease the spot shadow strength accordingly.
483 float minRaitoVI = FLT_MAX;
ztenghuic50a03d2014-08-21 13:47:54 -0700484
485 for (int i = 0; i < polyLength; i++) {
486 // Generate all the penumbra's vertices only using the (outline vertex + normal * radius)
487 // There is no guarantee that the penumbra is still convex, but for
488 // each outline vertex, it will connect to all its corresponding penumbra vertices as
489 // triangle fans. And for neighber penumbra vertex, it will be a trapezoid.
490 //
491 // Penumbra Vertices marked as Pi
492 // Outline Vertices marked as Vi
493 // (P3)
494 // (P2) | ' (P4)
495 // (P1)' | | '
496 // ' | | '
497 // (P0) ------------------------------------------------(P5)
498 // | (V0) |(V1)
499 // | |
500 // | |
501 // | |
502 // | |
503 // | |
504 // | |
505 // | |
506 // | |
507 // (V3)-----------------------------------(V2)
508 int preNormalIndex = (i + polyLength - 1) % polyLength;
ztenghuic50a03d2014-08-21 13:47:54 -0700509
ztenghui512e6432014-09-10 13:08:20 -0700510 const Vector2& previousNormal = outlineData[preNormalIndex].normal;
511 const Vector2& currentNormal = outlineData[i].normal;
512
513 // Depending on how roundness we want for each corner, we can subdivide
ztenghuic50a03d2014-08-21 13:47:54 -0700514 // further here and/or introduce some heuristic to decide how much the
515 // subdivision should be.
ztenghui512e6432014-09-10 13:08:20 -0700516 int currentExtraSliceNumber = ShadowTessellator::getExtraVertexNumber(
517 previousNormal, currentNormal, SPOT_CORNER_RADIANS_DIVISOR);
ztenghuic50a03d2014-08-21 13:47:54 -0700518
ztenghui512e6432014-09-10 13:08:20 -0700519 int currentCornerSliceNumber = 1 + currentExtraSliceNumber;
520 totalExtraCornerSliceNumber += currentExtraSliceNumber;
521#if DEBUG_SHADOW
522 ALOGD("currentExtraSliceNumber should be %d", currentExtraSliceNumber);
523 ALOGD("currentCornerSliceNumber should be %d", currentCornerSliceNumber);
524 ALOGD("totalCornerSliceNumber is %d", totalExtraCornerSliceNumber);
525#endif
526 if (CC_UNLIKELY(totalExtraCornerSliceNumber > SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER)) {
527 currentCornerSliceNumber = 1;
528 }
529 for (int k = 0; k <= currentCornerSliceNumber; k++) {
530 Vector2 avgNormal =
531 (previousNormal * (currentCornerSliceNumber - k) + currentNormal * k) /
532 currentCornerSliceNumber;
533 avgNormal.normalize();
534 penumbra[penumbraIndex++] = outlineData[i].position +
535 avgNormal * outlineData[i].radius;
536 }
ztenghuic50a03d2014-08-21 13:47:54 -0700537
ztenghuic50a03d2014-08-21 13:47:54 -0700538
539 // Compute the umbra by the intersection from the outline's centroid!
540 //
541 // (V) ------------------------------------
542 // | ' |
543 // | ' |
544 // | ' (I) |
545 // | ' |
546 // | ' (C) |
547 // | |
548 // | |
549 // | |
550 // | |
551 // ------------------------------------
552 //
553 // Connect a line b/t the outline vertex (V) and the centroid (C), it will
554 // intersect with the outline vertex's circle at point (I).
555 // Now, ratioVI = VI / VC, ratioIC = IC / VC
556 // Then the intersetion point can be computed as Ixy = Vxy * ratioIC + Cxy * ratioVI;
557 //
ztenghui512e6432014-09-10 13:08:20 -0700558 // When all of the outline circles cover the the outline centroid, (like I is
ztenghuic50a03d2014-08-21 13:47:54 -0700559 // on the other side of C), there is no real umbra any more, so we just fake
560 // a small area around the centroid as the umbra, and tune down the spot
561 // shadow's umbra strength to simulate the effect the whole shadow will
562 // become lighter in this case.
563 // The ratio can be simulated by using the inverse of maximum of ratioVI for
564 // all (V).
ztenghui512e6432014-09-10 13:08:20 -0700565 float distOutline = (outlineData[i].position - outlineCentroid).length();
ztenghui3bd3fa12014-08-25 14:42:27 -0700566 if (CC_UNLIKELY(distOutline == 0)) {
ztenghuic50a03d2014-08-21 13:47:54 -0700567 // If the outline has 0 area, then there is no spot shadow anyway.
568 ALOGW("Outline has 0 area, no spot shadow!");
569 return;
570 }
ztenghui512e6432014-09-10 13:08:20 -0700571
572 float ratioVI = outlineData[i].radius / distOutline;
573 minRaitoVI = MathUtils::min(minRaitoVI, ratioVI);
574 if (ratioVI >= (1 - FAKE_UMBRA_SIZE_RATIO)) {
575 ratioVI = (1 - FAKE_UMBRA_SIZE_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700576 }
577 // When we know we don't have valid umbra, don't bother to compute the
578 // values below. But we can't skip the loop yet since we want to know the
579 // maximum ratio.
ztenghui512e6432014-09-10 13:08:20 -0700580 float ratioIC = 1 - ratioVI;
581 umbra[i] = outlineData[i].position * ratioIC + outlineCentroid * ratioVI;
ztenghuic50a03d2014-08-21 13:47:54 -0700582 }
583
ztenghui512e6432014-09-10 13:08:20 -0700584 hasValidUmbra = (minRaitoVI <= 1.0);
ztenghuic50a03d2014-08-21 13:47:54 -0700585 float shadowStrengthScale = 1.0;
586 if (!hasValidUmbra) {
ztenghui512e6432014-09-10 13:08:20 -0700587#if DEBUG_SHADOW
ztenghuic50a03d2014-08-21 13:47:54 -0700588 ALOGW("The object is too close to the light or too small, no real umbra!");
ztenghui512e6432014-09-10 13:08:20 -0700589#endif
ztenghuic50a03d2014-08-21 13:47:54 -0700590 for (int i = 0; i < polyLength; i++) {
591 umbra[i] = outlineData[i].position * FAKE_UMBRA_SIZE_RATIO +
ztenghui512e6432014-09-10 13:08:20 -0700592 outlineCentroid * (1 - FAKE_UMBRA_SIZE_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700593 }
ztenghui512e6432014-09-10 13:08:20 -0700594 shadowStrengthScale = 1.0 / minRaitoVI;
ztenghuic50a03d2014-08-21 13:47:54 -0700595 }
596
ztenghui512e6432014-09-10 13:08:20 -0700597 int penumbraLength = penumbraIndex;
598 int umbraLength = polyLength;
599
ztenghuic50a03d2014-08-21 13:47:54 -0700600#if DEBUG_SHADOW
ztenghui512e6432014-09-10 13:08:20 -0700601 ALOGD("penumbraLength is %d , allocatedPenumbraLength %d", penumbraLength, allocatedPenumbraLength);
ztenghuic50a03d2014-08-21 13:47:54 -0700602 dumpPolygon(poly, polyLength, "input poly");
ztenghuic50a03d2014-08-21 13:47:54 -0700603 dumpPolygon(penumbra, penumbraLength, "penumbra");
ztenghui512e6432014-09-10 13:08:20 -0700604 dumpPolygon(umbra, umbraLength, "umbra");
ztenghuic50a03d2014-08-21 13:47:54 -0700605 ALOGD("hasValidUmbra is %d and shadowStrengthScale is %f", hasValidUmbra, shadowStrengthScale);
606#endif
607
ztenghui512e6432014-09-10 13:08:20 -0700608 // The penumbra and umbra needs to be in convex shape to keep consistency
609 // and quality.
610 // Since we are still shooting rays to penumbra, it needs to be convex.
611 // Umbra can be represented as a fan from the centroid, but visually umbra
612 // looks nicer when it is convex.
613 Vector2 finalUmbra[umbraLength];
614 Vector2 finalPenumbra[penumbraLength];
615 int finalUmbraLength = hull(umbra, umbraLength, finalUmbra);
616 int finalPenumbraLength = hull(penumbra, penumbraLength, finalPenumbra);
617
618 generateTriangleStrip(isCasterOpaque, shadowStrengthScale, finalPenumbra,
619 finalPenumbraLength, finalUmbra, finalUmbraLength, poly, polyLength,
620 shadowTriangleStrip, outlineCentroid);
621
ztenghuic50a03d2014-08-21 13:47:54 -0700622}
623
ztenghui7b4516e2014-01-07 10:42:55 -0800624/**
ztenghui7b4516e2014-01-07 10:42:55 -0800625 * This is only for experimental purpose.
626 * After intersections are calculated, we could smooth the polygon if needed.
627 * So far, we don't think it is more appealing yet.
628 *
629 * @param level The level of smoothness.
630 * @param rays The total number of rays.
631 * @param rayDist (In and Out) The distance for each ray.
632 *
633 */
634void SpotShadow::smoothPolygon(int level, int rays, float* rayDist) {
635 for (int k = 0; k < level; k++) {
636 for (int i = 0; i < rays; i++) {
637 float p1 = rayDist[(rays - 1 + i) % rays];
638 float p2 = rayDist[i];
639 float p3 = rayDist[(i + 1) % rays];
640 rayDist[i] = (p1 + p2 * 2 + p3) / 4;
641 }
642 }
643}
644
ztenghuid2dcd6f2014-10-29 16:04:29 -0700645// Index pair is meant for storing the tessellation information for the penumbra
646// area. One index must come from exterior tangent of the circles, the other one
647// must come from the interior tangent of the circles.
648struct IndexPair {
649 int outerIndex;
650 int innerIndex;
651};
ztenghui512e6432014-09-10 13:08:20 -0700652
ztenghuid2dcd6f2014-10-29 16:04:29 -0700653// For one penumbra vertex, find the cloest umbra vertex and return its index.
654inline int getClosestUmbraIndex(const Vector2& pivot, const Vector2* polygon, int polygonLength) {
655 float minLengthSquared = FLT_MAX;
ztenghui512e6432014-09-10 13:08:20 -0700656 int resultIndex = -1;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700657 bool hasDecreased = false;
658 // Starting with some negative offset, assuming both umbra and penumbra are starting
659 // at the same angle, this can help to find the result faster.
660 // Normally, loop 3 times, we can find the closest point.
661 int offset = polygonLength - 2;
662 for (int i = 0; i < polygonLength; i++) {
663 int currentIndex = (i + offset) % polygonLength;
664 float currentLengthSquared = (pivot - polygon[currentIndex]).lengthSquared();
665 if (currentLengthSquared < minLengthSquared) {
666 if (minLengthSquared != FLT_MAX) {
667 hasDecreased = true;
ztenghui512e6432014-09-10 13:08:20 -0700668 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700669 minLengthSquared = currentLengthSquared;
670 resultIndex = currentIndex;
671 } else if (currentLengthSquared > minLengthSquared && hasDecreased) {
672 // Early break b/c we have found the closet one and now the length
673 // is increasing again.
674 break;
ztenghui512e6432014-09-10 13:08:20 -0700675 }
676 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700677 if(resultIndex == -1) {
678 ALOGE("resultIndex is -1, the polygon must be invalid!");
679 resultIndex = 0;
ztenghui512e6432014-09-10 13:08:20 -0700680 }
681 return resultIndex;
682}
683
ztenghui39320632014-11-12 10:56:15 -0800684// Allow some epsilon here since the later ray intersection did allow for some small
685// floating point error, when the intersection point is slightly outside the segment.
ztenghuid2dcd6f2014-10-29 16:04:29 -0700686inline bool sameDirections(bool isPositiveCross, float a, float b) {
687 if (isPositiveCross) {
ztenghui39320632014-11-12 10:56:15 -0800688 return a >= -EPSILON && b >= -EPSILON;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700689 } else {
ztenghui39320632014-11-12 10:56:15 -0800690 return a <= EPSILON && b <= EPSILON;
ztenghui512e6432014-09-10 13:08:20 -0700691 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700692}
ztenghui512e6432014-09-10 13:08:20 -0700693
ztenghuid2dcd6f2014-10-29 16:04:29 -0700694// Find the right polygon edge to shoot the ray at.
695inline int findPolyIndex(bool isPositiveCross, int startPolyIndex, const Vector2& umbraDir,
696 const Vector2* polyToCentroid, int polyLength) {
697 // Make sure we loop with a bound.
698 for (int i = 0; i < polyLength; i++) {
699 int currentIndex = (i + startPolyIndex) % polyLength;
700 const Vector2& currentToCentroid = polyToCentroid[currentIndex];
701 const Vector2& nextToCentroid = polyToCentroid[(currentIndex + 1) % polyLength];
ztenghui512e6432014-09-10 13:08:20 -0700702
ztenghuid2dcd6f2014-10-29 16:04:29 -0700703 float currentCrossUmbra = currentToCentroid.cross(umbraDir);
704 float umbraCrossNext = umbraDir.cross(nextToCentroid);
705 if (sameDirections(isPositiveCross, currentCrossUmbra, umbraCrossNext)) {
ztenghui512e6432014-09-10 13:08:20 -0700706#if DEBUG_SHADOW
ztenghuid2dcd6f2014-10-29 16:04:29 -0700707 ALOGD("findPolyIndex loop %d times , index %d", i, currentIndex );
ztenghui512e6432014-09-10 13:08:20 -0700708#endif
ztenghuid2dcd6f2014-10-29 16:04:29 -0700709 return currentIndex;
ztenghui512e6432014-09-10 13:08:20 -0700710 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700711 }
712 LOG_ALWAYS_FATAL("Can't find the right polygon's edge from startPolyIndex %d", startPolyIndex);
713 return -1;
714}
ztenghui512e6432014-09-10 13:08:20 -0700715
ztenghuid2dcd6f2014-10-29 16:04:29 -0700716// Generate the index pair for penumbra / umbra vertices, and more penumbra vertices
717// if needed.
718inline void genNewPenumbraAndPairWithUmbra(const Vector2* penumbra, int penumbraLength,
719 const Vector2* umbra, int umbraLength, Vector2* newPenumbra, int& newPenumbraIndex,
720 IndexPair* verticesPair, int& verticesPairIndex) {
721 // In order to keep everything in just one loop, we need to pre-compute the
722 // closest umbra vertex for the last penumbra vertex.
723 int previousClosestUmbraIndex = getClosestUmbraIndex(penumbra[penumbraLength - 1],
724 umbra, umbraLength);
725 for (int i = 0; i < penumbraLength; i++) {
726 const Vector2& currentPenumbraVertex = penumbra[i];
727 // For current penumbra vertex, starting from previousClosestUmbraIndex,
728 // then check the next one until the distance increase.
729 // The last one before the increase is the umbra vertex we need to pair with.
ztenghui39320632014-11-12 10:56:15 -0800730 float currentLengthSquared =
731 (currentPenumbraVertex - umbra[previousClosestUmbraIndex]).lengthSquared();
732 int currentClosestUmbraIndex = previousClosestUmbraIndex;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700733 int indexDelta = 0;
734 for (int j = 1; j < umbraLength; j++) {
735 int newUmbraIndex = (previousClosestUmbraIndex + j) % umbraLength;
736 float newLengthSquared = (currentPenumbraVertex - umbra[newUmbraIndex]).lengthSquared();
737 if (newLengthSquared > currentLengthSquared) {
ztenghui39320632014-11-12 10:56:15 -0800738 // currentClosestUmbraIndex is the umbra vertex's index which has
739 // currently found smallest distance, so we can simply break here.
ztenghuid2dcd6f2014-10-29 16:04:29 -0700740 break;
741 } else {
742 currentLengthSquared = newLengthSquared;
743 indexDelta++;
ztenghui39320632014-11-12 10:56:15 -0800744 currentClosestUmbraIndex = newUmbraIndex;
ztenghui512e6432014-09-10 13:08:20 -0700745 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700746 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700747
748 if (indexDelta > 1) {
749 // For those umbra don't have penumbra, generate new penumbra vertices by interpolation.
750 //
751 // Assuming Pi for penumbra vertices, and Ui for umbra vertices.
752 // In the case like below P1 paired with U1 and P2 paired with U5.
753 // U2 to U4 are unpaired umbra vertices.
754 //
755 // P1 P2
756 // | |
757 // U1 U2 U3 U4 U5
758 //
759 // We will need to generate 3 more penumbra vertices P1.1, P1.2, P1.3
760 // to pair with U2 to U4.
761 //
762 // P1 P1.1 P1.2 P1.3 P2
763 // | | | | |
764 // U1 U2 U3 U4 U5
765 //
766 // That distance ratio b/t Ui to U1 and Ui to U5 decides its paired penumbra
767 // vertex's location.
768 int newPenumbraNumber = indexDelta - 1;
769
770 float accumulatedDeltaLength[newPenumbraNumber];
771 float totalDeltaLength = 0;
772
773 // To save time, cache the previous umbra vertex info outside the loop
774 // and update each loop.
775 Vector2 previousClosestUmbra = umbra[previousClosestUmbraIndex];
776 Vector2 skippedUmbra;
777 // Use umbra data to precompute the length b/t unpaired umbra vertices,
778 // and its ratio against the total length.
779 for (int k = 0; k < indexDelta; k++) {
780 int skippedUmbraIndex = (previousClosestUmbraIndex + k + 1) % umbraLength;
781 skippedUmbra = umbra[skippedUmbraIndex];
782 float currentDeltaLength = (skippedUmbra - previousClosestUmbra).length();
783
784 totalDeltaLength += currentDeltaLength;
785 accumulatedDeltaLength[k] = totalDeltaLength;
786
787 previousClosestUmbra = skippedUmbra;
788 }
789
790 const Vector2& previousPenumbra = penumbra[(i + penumbraLength - 1) % penumbraLength];
791 // Then for each unpaired umbra vertex, create a new penumbra by the ratio,
792 // and pair them togehter.
793 for (int k = 0; k < newPenumbraNumber; k++) {
794 float weightForCurrentPenumbra = 1.0f;
795 if (totalDeltaLength != 0.0f) {
796 weightForCurrentPenumbra = accumulatedDeltaLength[k] / totalDeltaLength;
797 }
798 float weightForPreviousPenumbra = 1.0f - weightForCurrentPenumbra;
799
800 Vector2 interpolatedPenumbra = currentPenumbraVertex * weightForCurrentPenumbra +
801 previousPenumbra * weightForPreviousPenumbra;
802
803 int skippedUmbraIndex = (previousClosestUmbraIndex + k + 1) % umbraLength;
Andreas Gampeedaecc12014-11-10 20:54:07 -0800804 verticesPair[verticesPairIndex].outerIndex = newPenumbraIndex;
805 verticesPair[verticesPairIndex].innerIndex = skippedUmbraIndex;
806 verticesPairIndex++;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700807 newPenumbra[newPenumbraIndex++] = interpolatedPenumbra;
808 }
809 }
Andreas Gampeedaecc12014-11-10 20:54:07 -0800810 verticesPair[verticesPairIndex].outerIndex = newPenumbraIndex;
811 verticesPair[verticesPairIndex].innerIndex = currentClosestUmbraIndex;
812 verticesPairIndex++;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700813 newPenumbra[newPenumbraIndex++] = currentPenumbraVertex;
814
815 previousClosestUmbraIndex = currentClosestUmbraIndex;
816 }
817}
818
819// Precompute all the polygon's vector, return true if the reference cross product is positive.
820inline bool genPolyToCentroid(const Vector2* poly2d, int polyLength,
821 const Vector2& centroid, Vector2* polyToCentroid) {
822 for (int j = 0; j < polyLength; j++) {
823 polyToCentroid[j] = poly2d[j] - centroid;
ztenghui39320632014-11-12 10:56:15 -0800824 // Normalize these vectors such that we can use epsilon comparison after
825 // computing their cross products with another normalized vector.
826 polyToCentroid[j].normalize();
ztenghuid2dcd6f2014-10-29 16:04:29 -0700827 }
828 float refCrossProduct = 0;
829 for (int j = 0; j < polyLength; j++) {
830 refCrossProduct = polyToCentroid[j].cross(polyToCentroid[(j + 1) % polyLength]);
831 if (refCrossProduct != 0) {
832 break;
ztenghui512e6432014-09-10 13:08:20 -0700833 }
834 }
835
ztenghuid2dcd6f2014-10-29 16:04:29 -0700836 return refCrossProduct > 0;
837}
ztenghui512e6432014-09-10 13:08:20 -0700838
ztenghuid2dcd6f2014-10-29 16:04:29 -0700839// For one umbra vertex, shoot an ray from centroid to it.
840// If the ray hit the polygon first, then return the intersection point as the
841// closer vertex.
842inline Vector2 getCloserVertex(const Vector2& umbraVertex, const Vector2& centroid,
843 const Vector2* poly2d, int polyLength, const Vector2* polyToCentroid,
844 bool isPositiveCross, int& previousPolyIndex) {
845 Vector2 umbraToCentroid = umbraVertex - centroid;
846 float distanceToUmbra = umbraToCentroid.length();
847 umbraToCentroid = umbraToCentroid / distanceToUmbra;
848
849 // previousPolyIndex is updated for each item such that we can minimize the
850 // looping inside findPolyIndex();
851 previousPolyIndex = findPolyIndex(isPositiveCross, previousPolyIndex,
852 umbraToCentroid, polyToCentroid, polyLength);
853
854 float dx = umbraToCentroid.x;
855 float dy = umbraToCentroid.y;
856 float distanceToIntersectPoly = rayIntersectPoints(centroid, dx, dy,
857 poly2d[previousPolyIndex], poly2d[(previousPolyIndex + 1) % polyLength]);
858 if (distanceToIntersectPoly < 0) {
859 distanceToIntersectPoly = 0;
860 }
861
862 // Pick the closer one as the occluded area vertex.
863 Vector2 closerVertex;
864 if (distanceToIntersectPoly < distanceToUmbra) {
865 closerVertex.x = centroid.x + dx * distanceToIntersectPoly;
866 closerVertex.y = centroid.y + dy * distanceToIntersectPoly;
867 } else {
868 closerVertex = umbraVertex;
869 }
870
871 return closerVertex;
ztenghui512e6432014-09-10 13:08:20 -0700872}
873
874/**
875 * Generate a triangle strip given two convex polygon
876**/
Andreas Gampe64bb4132014-11-22 00:35:09 +0000877void SpotShadow::generateTriangleStrip(bool isCasterOpaque, float shadowStrengthScale,
ztenghui512e6432014-09-10 13:08:20 -0700878 Vector2* penumbra, int penumbraLength, Vector2* umbra, int umbraLength,
879 const Vector3* poly, int polyLength, VertexBuffer& shadowTriangleStrip,
880 const Vector2& centroid) {
ztenghui512e6432014-09-10 13:08:20 -0700881 bool hasOccludedUmbraArea = false;
882 Vector2 poly2d[polyLength];
883
884 if (isCasterOpaque) {
885 for (int i = 0; i < polyLength; i++) {
886 poly2d[i].x = poly[i].x;
887 poly2d[i].y = poly[i].y;
888 }
889 // Make sure the centroid is inside the umbra, otherwise, fall back to the
890 // approach as if there is no occluded umbra area.
891 if (testPointInsidePolygon(centroid, poly2d, polyLength)) {
892 hasOccludedUmbraArea = true;
893 }
894 }
895
ztenghuid2dcd6f2014-10-29 16:04:29 -0700896 // For each penumbra vertex, find its corresponding closest umbra vertex index.
897 //
898 // Penumbra Vertices marked as Pi
899 // Umbra Vertices marked as Ui
900 // (P3)
901 // (P2) | ' (P4)
902 // (P1)' | | '
903 // ' | | '
904 // (P0) ------------------------------------------------(P5)
905 // | (U0) |(U1)
906 // | |
907 // | |(U2) (P5.1)
908 // | |
909 // | |
910 // | |
911 // | |
912 // | |
913 // | |
914 // (U4)-----------------------------------(U3) (P6)
915 //
916 // At least, like P0, P1, P2, they will find the matching umbra as U0.
917 // If we jump over some umbra vertex without matching penumbra vertex, then
918 // we will generate some new penumbra vertex by interpolation. Like P6 is
919 // matching U3, but U2 is not matched with any penumbra vertex.
920 // So interpolate P5.1 out and match U2.
921 // In this way, every umbra vertex will have a matching penumbra vertex.
922 //
923 // The total pair number can be as high as umbraLength + penumbraLength.
924 const int maxNewPenumbraLength = umbraLength + penumbraLength;
925 IndexPair verticesPair[maxNewPenumbraLength];
926 int verticesPairIndex = 0;
927
928 // Cache all the existing penumbra vertices and newly interpolated vertices into a
929 // a new array.
930 Vector2 newPenumbra[maxNewPenumbraLength];
931 int newPenumbraIndex = 0;
932
933 // For each penumbra vertex, find its closet umbra vertex by comparing the
934 // neighbor umbra vertices.
935 genNewPenumbraAndPairWithUmbra(penumbra, penumbraLength, umbra, umbraLength, newPenumbra,
936 newPenumbraIndex, verticesPair, verticesPairIndex);
937 ShadowTessellator::checkOverflow(verticesPairIndex, maxNewPenumbraLength, "Spot pair");
938 ShadowTessellator::checkOverflow(newPenumbraIndex, maxNewPenumbraLength, "Spot new penumbra");
939#if DEBUG_SHADOW
940 for (int i = 0; i < umbraLength; i++) {
941 ALOGD("umbra i %d, [%f, %f]", i, umbra[i].x, umbra[i].y);
ztenghui512e6432014-09-10 13:08:20 -0700942 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700943 for (int i = 0; i < newPenumbraIndex; i++) {
944 ALOGD("new penumbra i %d, [%f, %f]", i, newPenumbra[i].x, newPenumbra[i].y);
945 }
946 for (int i = 0; i < verticesPairIndex; i++) {
947 ALOGD("index i %d, [%d, %d]", i, verticesPair[i].outerIndex, verticesPair[i].innerIndex);
948 }
949#endif
ztenghui512e6432014-09-10 13:08:20 -0700950
ztenghuid2dcd6f2014-10-29 16:04:29 -0700951 // For the size of vertex buffer, we need 3 rings, one has newPenumbraSize,
952 // one has umbraLength, the last one has at most umbraLength.
953 //
954 // For the size of index buffer, the umbra area needs (2 * umbraLength + 2).
955 // The penumbra one can vary a bit, but it is bounded by (2 * verticesPairIndex + 2).
956 // And 2 more for jumping between penumbra to umbra.
957 const int newPenumbraLength = newPenumbraIndex;
958 const int totalVertexCount = newPenumbraLength + umbraLength * 2;
959 const int totalIndexCount = 2 * umbraLength + 2 * verticesPairIndex + 6;
ztenghui512e6432014-09-10 13:08:20 -0700960 AlphaVertex* shadowVertices =
961 shadowTriangleStrip.alloc<AlphaVertex>(totalVertexCount);
962 uint16_t* indexBuffer =
963 shadowTriangleStrip.allocIndices<uint16_t>(totalIndexCount);
ztenghui512e6432014-09-10 13:08:20 -0700964 int vertexBufferIndex = 0;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700965 int indexBufferIndex = 0;
ztenghui512e6432014-09-10 13:08:20 -0700966
ztenghuid2dcd6f2014-10-29 16:04:29 -0700967 // Fill the IB and VB for the penumbra area.
968 for (int i = 0; i < newPenumbraLength; i++) {
969 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], newPenumbra[i].x,
ztenghuiecf091e2015-02-17 13:26:10 -0800970 newPenumbra[i].y, TRANSFORMED_PENUMBRA_ALPHA);
ztenghuid2dcd6f2014-10-29 16:04:29 -0700971 }
972 for (int i = 0; i < umbraLength; i++) {
973 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], umbra[i].x, umbra[i].y,
ztenghuiecf091e2015-02-17 13:26:10 -0800974 TRANSFORMED_UMBRA_ALPHA);
ztenghui512e6432014-09-10 13:08:20 -0700975 }
976
ztenghuid2dcd6f2014-10-29 16:04:29 -0700977 for (int i = 0; i < verticesPairIndex; i++) {
978 indexBuffer[indexBufferIndex++] = verticesPair[i].outerIndex;
979 // All umbra index need to be offseted by newPenumbraSize.
980 indexBuffer[indexBufferIndex++] = verticesPair[i].innerIndex + newPenumbraLength;
981 }
982 indexBuffer[indexBufferIndex++] = verticesPair[0].outerIndex;
983 indexBuffer[indexBufferIndex++] = verticesPair[0].innerIndex + newPenumbraLength;
ztenghui512e6432014-09-10 13:08:20 -0700984
ztenghuid2dcd6f2014-10-29 16:04:29 -0700985 // Now fill the IB and VB for the umbra area.
986 // First duplicated the index from previous strip and the first one for the
987 // degenerated triangles.
988 indexBuffer[indexBufferIndex] = indexBuffer[indexBufferIndex - 1];
989 indexBufferIndex++;
990 indexBuffer[indexBufferIndex++] = newPenumbraLength + 0;
991 // Save the first VB index for umbra area in order to close the loop.
992 int savedStartIndex = vertexBufferIndex;
993
ztenghui512e6432014-09-10 13:08:20 -0700994 if (hasOccludedUmbraArea) {
ztenghuid2dcd6f2014-10-29 16:04:29 -0700995 // Precompute all the polygon's vector, and the reference cross product,
996 // in order to find the right polygon edge for the ray to intersect.
997 Vector2 polyToCentroid[polyLength];
998 bool isPositiveCross = genPolyToCentroid(poly2d, polyLength, centroid, polyToCentroid);
ztenghui512e6432014-09-10 13:08:20 -0700999
ztenghuid2dcd6f2014-10-29 16:04:29 -07001000 // Because both the umbra and polygon are going in the same direction,
1001 // we can save the previous polygon index to make sure we have less polygon
1002 // vertex to compute for each ray.
1003 int previousPolyIndex = 0;
1004 for (int i = 0; i < umbraLength; i++) {
1005 // Shoot a ray from centroid to each umbra vertices and pick the one with
1006 // shorter distance to the centroid, b/t the umbra vertex or the intersection point.
1007 Vector2 closerVertex = getCloserVertex(umbra[i], centroid, poly2d, polyLength,
1008 polyToCentroid, isPositiveCross, previousPolyIndex);
1009
1010 // We already stored the umbra vertices, just need to add the occlued umbra's ones.
1011 indexBuffer[indexBufferIndex++] = newPenumbraLength + i;
1012 indexBuffer[indexBufferIndex++] = vertexBufferIndex;
1013 AlphaVertex::set(&shadowVertices[vertexBufferIndex++],
ztenghuiecf091e2015-02-17 13:26:10 -08001014 closerVertex.x, closerVertex.y, TRANSFORMED_UMBRA_ALPHA);
ztenghui512e6432014-09-10 13:08:20 -07001015 }
ztenghui512e6432014-09-10 13:08:20 -07001016 } else {
ztenghuid2dcd6f2014-10-29 16:04:29 -07001017 // If there is no occluded umbra at all, then draw the triangle fan
1018 // starting from the centroid to all umbra vertices.
ztenghui512e6432014-09-10 13:08:20 -07001019 int lastCentroidIndex = vertexBufferIndex;
1020 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], centroid.x,
ztenghuiecf091e2015-02-17 13:26:10 -08001021 centroid.y, TRANSFORMED_UMBRA_ALPHA);
ztenghuid2dcd6f2014-10-29 16:04:29 -07001022 for (int i = 0; i < umbraLength; i++) {
1023 indexBuffer[indexBufferIndex++] = newPenumbraLength + i;
ztenghui512e6432014-09-10 13:08:20 -07001024 indexBuffer[indexBufferIndex++] = lastCentroidIndex;
1025 }
ztenghui512e6432014-09-10 13:08:20 -07001026 }
ztenghuid2dcd6f2014-10-29 16:04:29 -07001027 // Closing the umbra area triangle's loop here.
1028 indexBuffer[indexBufferIndex++] = newPenumbraLength;
1029 indexBuffer[indexBufferIndex++] = savedStartIndex;
ztenghui512e6432014-09-10 13:08:20 -07001030
1031 // At the end, update the real index and vertex buffer size.
1032 shadowTriangleStrip.updateVertexCount(vertexBufferIndex);
1033 shadowTriangleStrip.updateIndexCount(indexBufferIndex);
1034 ShadowTessellator::checkOverflow(vertexBufferIndex, totalVertexCount, "Spot Vertex Buffer");
1035 ShadowTessellator::checkOverflow(indexBufferIndex, totalIndexCount, "Spot Index Buffer");
1036
Chris Craik117bdbc2015-02-05 10:12:38 -08001037 shadowTriangleStrip.setMeshFeatureFlags(VertexBuffer::kAlpha | VertexBuffer::kIndices);
ztenghui512e6432014-09-10 13:08:20 -07001038 shadowTriangleStrip.computeBounds<AlphaVertex>();
1039}
1040
ztenghuif5ca8b42014-01-27 15:53:28 -08001041#if DEBUG_SHADOW
1042
1043#define TEST_POINT_NUMBER 128
ztenghuif5ca8b42014-01-27 15:53:28 -08001044/**
1045 * Calculate the bounds for generating random test points.
1046 */
1047void SpotShadow::updateBound(const Vector2 inVector, Vector2& lowerBound,
ztenghui512e6432014-09-10 13:08:20 -07001048 Vector2& upperBound) {
ztenghuif5ca8b42014-01-27 15:53:28 -08001049 if (inVector.x < lowerBound.x) {
1050 lowerBound.x = inVector.x;
1051 }
1052
1053 if (inVector.y < lowerBound.y) {
1054 lowerBound.y = inVector.y;
1055 }
1056
1057 if (inVector.x > upperBound.x) {
1058 upperBound.x = inVector.x;
1059 }
1060
1061 if (inVector.y > upperBound.y) {
1062 upperBound.y = inVector.y;
1063 }
1064}
1065
1066/**
1067 * For debug purpose, when things go wrong, dump the whole polygon data.
1068 */
ztenghuic50a03d2014-08-21 13:47:54 -07001069void SpotShadow::dumpPolygon(const Vector2* poly, int polyLength, const char* polyName) {
1070 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 * For debug purpose, when things go wrong, dump the whole polygon data.
1077 */
1078void SpotShadow::dumpPolygon(const Vector3* poly, int polyLength, const char* polyName) {
ztenghuif5ca8b42014-01-27 15:53:28 -08001079 for (int i = 0; i < polyLength; i++) {
1080 ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
1081 }
1082}
1083
1084/**
1085 * Test whether the polygon is convex.
1086 */
1087bool SpotShadow::testConvex(const Vector2* polygon, int polygonLength,
1088 const char* name) {
1089 bool isConvex = true;
1090 for (int i = 0; i < polygonLength; i++) {
1091 Vector2 start = polygon[i];
1092 Vector2 middle = polygon[(i + 1) % polygonLength];
1093 Vector2 end = polygon[(i + 2) % polygonLength];
1094
ztenghui9122b1b2014-10-03 11:21:11 -07001095 float delta = (float(middle.x) - start.x) * (float(end.y) - start.y) -
1096 (float(middle.y) - start.y) * (float(end.x) - start.x);
ztenghuif5ca8b42014-01-27 15:53:28 -08001097 bool isCCWOrCoLinear = (delta >= EPSILON);
1098
1099 if (isCCWOrCoLinear) {
ztenghui50ecf842014-03-11 16:52:30 -07001100 ALOGW("(Error Type 2): polygon (%s) is not a convex b/c start (x %f, y %f),"
ztenghuif5ca8b42014-01-27 15:53:28 -08001101 "middle (x %f, y %f) and end (x %f, y %f) , delta is %f !!!",
1102 name, start.x, start.y, middle.x, middle.y, end.x, end.y, delta);
1103 isConvex = false;
1104 break;
1105 }
1106 }
1107 return isConvex;
1108}
1109
1110/**
1111 * Test whether or not the polygon (intersection) is within the 2 input polygons.
1112 * Using Marte Carlo method, we generate a random point, and if it is inside the
1113 * intersection, then it must be inside both source polygons.
1114 */
1115void SpotShadow::testIntersection(const Vector2* poly1, int poly1Length,
1116 const Vector2* poly2, int poly2Length,
1117 const Vector2* intersection, int intersectionLength) {
1118 // Find the min and max of x and y.
ztenghuic50a03d2014-08-21 13:47:54 -07001119 Vector2 lowerBound = {FLT_MAX, FLT_MAX};
1120 Vector2 upperBound = {-FLT_MAX, -FLT_MAX};
ztenghuif5ca8b42014-01-27 15:53:28 -08001121 for (int i = 0; i < poly1Length; i++) {
1122 updateBound(poly1[i], lowerBound, upperBound);
1123 }
1124 for (int i = 0; i < poly2Length; i++) {
1125 updateBound(poly2[i], lowerBound, upperBound);
1126 }
1127
1128 bool dumpPoly = false;
1129 for (int k = 0; k < TEST_POINT_NUMBER; k++) {
1130 // Generate a random point between minX, minY and maxX, maxY.
ztenghui9122b1b2014-10-03 11:21:11 -07001131 float randomX = rand() / float(RAND_MAX);
1132 float randomY = rand() / float(RAND_MAX);
ztenghuif5ca8b42014-01-27 15:53:28 -08001133
1134 Vector2 testPoint;
1135 testPoint.x = lowerBound.x + randomX * (upperBound.x - lowerBound.x);
1136 testPoint.y = lowerBound.y + randomY * (upperBound.y - lowerBound.y);
1137
1138 // If the random point is in both poly 1 and 2, then it must be intersection.
1139 if (testPointInsidePolygon(testPoint, intersection, intersectionLength)) {
1140 if (!testPointInsidePolygon(testPoint, poly1, poly1Length)) {
1141 dumpPoly = true;
ztenghui50ecf842014-03-11 16:52:30 -07001142 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
ztenghui512e6432014-09-10 13:08:20 -07001143 " not in the poly1",
ztenghuif5ca8b42014-01-27 15:53:28 -08001144 testPoint.x, testPoint.y);
1145 }
1146
1147 if (!testPointInsidePolygon(testPoint, poly2, poly2Length)) {
1148 dumpPoly = true;
ztenghui50ecf842014-03-11 16:52:30 -07001149 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
ztenghui512e6432014-09-10 13:08:20 -07001150 " not in the poly2",
ztenghuif5ca8b42014-01-27 15:53:28 -08001151 testPoint.x, testPoint.y);
1152 }
1153 }
1154 }
1155
1156 if (dumpPoly) {
1157 dumpPolygon(intersection, intersectionLength, "intersection");
1158 for (int i = 1; i < intersectionLength; i++) {
1159 Vector2 delta = intersection[i] - intersection[i - 1];
1160 ALOGD("Intersetion i, %d Vs i-1 is delta %f", i, delta.lengthSquared());
1161 }
1162
1163 dumpPolygon(poly1, poly1Length, "poly 1");
1164 dumpPolygon(poly2, poly2Length, "poly 2");
1165 }
1166}
1167#endif
1168
ztenghui7b4516e2014-01-07 10:42:55 -08001169}; // namespace uirenderer
1170}; // namespace android