blob: e371ac8da1e56e8186816fd022f4924fb4f0b003 [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
ztenghui512e6432014-09-10 13:08:20 -070017// The highest z value can't be higher than (CASTER_Z_CAP_RATIO * light.z)
ztenghuic50a03d2014-08-21 13:47:54 -070018#define CASTER_Z_CAP_RATIO 0.95f
ztenghui512e6432014-09-10 13:08:20 -070019
20// When there is no umbra, then just fake the umbra using
21// centroid * (1 - FAKE_UMBRA_SIZE_RATIO) + outline * FAKE_UMBRA_SIZE_RATIO
22#define FAKE_UMBRA_SIZE_RATIO 0.05f
23
24// When the polygon is about 90 vertices, the penumbra + umbra can reach 270 rays.
25// That is consider pretty fine tessllated polygon so far.
26// This is just to prevent using too much some memory when edge slicing is not
27// needed any more.
28#define FINE_TESSELLATED_POLYGON_RAY_NUMBER 270
29/**
30 * Extra vertices for the corner for smoother corner.
31 * Only for outer loop.
32 * Note that we use such extra memory to avoid an extra loop.
33 */
34// For half circle, we could add EXTRA_VERTEX_PER_PI vertices.
35// Set to 1 if we don't want to have any.
36#define SPOT_EXTRA_CORNER_VERTEX_PER_PI 18
37
38// For the whole polygon, the sum of all the deltas b/t normals is 2 * M_PI,
39// therefore, the maximum number of extra vertices will be twice bigger.
John Reck1bcacfd2017-11-03 10:12:19 -070040#define SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER (2 * SPOT_EXTRA_CORNER_VERTEX_PER_PI)
ztenghui512e6432014-09-10 13:08:20 -070041
42// For each RADIANS_DIVISOR, we would allocate one more vertex b/t the normals.
43#define SPOT_CORNER_RADIANS_DIVISOR (M_PI / SPOT_EXTRA_CORNER_VERTEX_PER_PI)
44
Chris Craik138c21f2016-04-28 16:59:42 -070045#define PENUMBRA_ALPHA 0.0f
46#define UMBRA_ALPHA 1.0f
ztenghui7b4516e2014-01-07 10:42:55 -080047
Chris Craik9db58c02015-08-19 15:19:18 -070048#include "SpotShadow.h"
49
50#include "ShadowTessellator.h"
51#include "Vertex.h"
52#include "VertexBuffer.h"
53#include "utils/MathUtils.h"
54
ztenghui7b4516e2014-01-07 10:42:55 -080055#include <math.h>
ztenghuif5ca8b42014-01-27 15:53:28 -080056#include <stdlib.h>
ztenghui7b4516e2014-01-07 10:42:55 -080057#include <utils/Log.h>
John Reck1bcacfd2017-11-03 10:12:19 -070058#include <algorithm>
ztenghui7b4516e2014-01-07 10:42:55 -080059
ztenghuic50a03d2014-08-21 13:47:54 -070060// TODO: After we settle down the new algorithm, we can remove the old one and
61// its utility functions.
62// Right now, we still need to keep it for comparison purpose and future expansion.
ztenghui7b4516e2014-01-07 10:42:55 -080063namespace android {
64namespace uirenderer {
65
ztenghui9122b1b2014-10-03 11:21:11 -070066static const float EPSILON = 1e-7;
Chris Craik726118b2014-03-07 18:27:49 -080067
ztenghui7b4516e2014-01-07 10:42:55 -080068/**
ztenghuic50a03d2014-08-21 13:47:54 -070069 * For each polygon's vertex, the light center will project it to the receiver
70 * as one of the outline vertex.
71 * For each outline vertex, we need to store the position and normal.
72 * Normal here is defined against the edge by the current vertex and the next vertex.
73 */
74struct OutlineData {
75 Vector2 position;
76 Vector2 normal;
77 float radius;
78};
79
80/**
ztenghui512e6432014-09-10 13:08:20 -070081 * For each vertex, we need to keep track of its angle, whether it is penumbra or
82 * umbra, and its corresponding vertex index.
83 */
84struct SpotShadow::VertexAngleData {
85 // The angle to the vertex from the centroid.
86 float mAngle;
87 // True is the vertex comes from penumbra, otherwise it comes from umbra.
88 bool mIsPenumbra;
89 // The index of the vertex described by this data.
90 int mVertexIndex;
91 void set(float angle, bool isPenumbra, int index) {
92 mAngle = angle;
93 mIsPenumbra = isPenumbra;
94 mVertexIndex = index;
95 }
96};
97
98/**
Chris Craik726118b2014-03-07 18:27:49 -080099 * Calculate the angle between and x and a y coordinate.
100 * The atan2 range from -PI to PI.
ztenghui7b4516e2014-01-07 10:42:55 -0800101 */
Chris Craikb79a3e32014-03-11 12:20:17 -0700102static float angle(const Vector2& point, const Vector2& center) {
Chris Craik726118b2014-03-07 18:27:49 -0800103 return atan2(point.y - center.y, point.x - center.x);
104}
105
106/**
107 * Calculate the intersection of a ray with the line segment defined by two points.
108 *
109 * Returns a negative value in error conditions.
110
111 * @param rayOrigin The start of the ray
112 * @param dx The x vector of the ray
113 * @param dy The y vector of the ray
114 * @param p1 The first point defining the line segment
115 * @param p2 The second point defining the line segment
116 * @return The distance along the ray if it intersects with the line segment, negative if otherwise
117 */
John Reck1bcacfd2017-11-03 10:12:19 -0700118static float rayIntersectPoints(const Vector2& rayOrigin, float dx, float dy, const Vector2& p1,
119 const Vector2& p2) {
Chris Craik726118b2014-03-07 18:27:49 -0800120 // The math below is derived from solving this formula, basically the
121 // intersection point should stay on both the ray and the edge of (p1, p2).
122 // solve([p1x+t*(p2x-p1x)=dx*t2+px,p1y+t*(p2y-p1y)=dy*t2+py],[t,t2]);
123
ztenghui9122b1b2014-10-03 11:21:11 -0700124 float divisor = (dx * (p1.y - p2.y) + dy * p2.x - dy * p1.x);
John Reck1bcacfd2017-11-03 10:12:19 -0700125 if (divisor == 0) return -1.0f; // error, invalid divisor
Chris Craik726118b2014-03-07 18:27:49 -0800126
127#if DEBUG_SHADOW
ztenghui9122b1b2014-10-03 11:21:11 -0700128 float interpVal = (dx * (p1.y - rayOrigin.y) + dy * rayOrigin.x - dy * p1.x) / divisor;
ztenghui99af9422014-03-14 14:35:54 -0700129 if (interpVal < 0 || interpVal > 1) {
130 ALOGW("rayIntersectPoints is hitting outside the segment %f", interpVal);
131 }
Chris Craik726118b2014-03-07 18:27:49 -0800132#endif
133
ztenghui9122b1b2014-10-03 11:21:11 -0700134 float distance = (p1.x * (rayOrigin.y - p2.y) + p2.x * (p1.y - rayOrigin.y) +
John Reck1bcacfd2017-11-03 10:12:19 -0700135 rayOrigin.x * (p2.y - p1.y)) /
136 divisor;
Chris Craik726118b2014-03-07 18:27:49 -0800137
John Reck1bcacfd2017-11-03 10:12:19 -0700138 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) {
John Reck1bcacfd2017-11-03 10:12:19 -0700148 auto cmp = [](const Vector2& a, const Vector2& b) -> bool { return a.x < b.x; };
John Reck1e4209e2015-07-01 09:54:47 -0700149 std::sort(points, points + pointsLength, cmp);
ztenghui7b4516e2014-01-07 10:42:55 -0800150}
151
152/**
153 * compute the convex hull of a collection of Points
154 *
155 * @param points the points as a Vector2 array.
156 * @param pointsLength the number of vertices of the polygon.
157 * @param retPoly pre allocated array of floats to put the vertices
158 * @return the number of points in the polygon 0 if no intersection
159 */
160int SpotShadow::hull(Vector2* points, int pointsLength, Vector2* retPoly) {
161 xsort(points, pointsLength);
162 int n = pointsLength;
163 Vector2 lUpper[n];
164 lUpper[0] = points[0];
165 lUpper[1] = points[1];
166
167 int lUpperSize = 2;
168
169 for (int i = 2; i < n; i++) {
170 lUpper[lUpperSize] = points[i];
171 lUpperSize++;
172
John Reck1bcacfd2017-11-03 10:12:19 -0700173 while (lUpperSize > 2 &&
174 !ccw(lUpper[lUpperSize - 3].x, lUpper[lUpperSize - 3].y, lUpper[lUpperSize - 2].x,
175 lUpper[lUpperSize - 2].y, 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
John Reck1bcacfd2017-11-03 10:12:19 -0700193 while (lLowerSize > 2 &&
194 !ccw(lLower[lLowerSize - 3].x, lLower[lLowerSize - 3].y, lLower[lLowerSize - 2].x,
195 lLower[lLowerSize - 2].y, lLower[lLowerSize - 1].x, lLower[lLowerSize - 1].y)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800196 // Remove the middle point of the three last
197 lLower[lLowerSize - 2] = lLower[lLowerSize - 1];
198 lLowerSize--;
199 }
200 }
ztenghui7b4516e2014-01-07 10:42:55 -0800201
Chris Craik726118b2014-03-07 18:27:49 -0800202 // output points in CW ordering
203 const int total = lUpperSize + lLowerSize - 2;
204 int outIndex = total - 1;
ztenghui7b4516e2014-01-07 10:42:55 -0800205 for (int i = 0; i < lUpperSize; i++) {
Chris Craik726118b2014-03-07 18:27:49 -0800206 retPoly[outIndex] = lUpper[i];
207 outIndex--;
ztenghui7b4516e2014-01-07 10:42:55 -0800208 }
209
210 for (int i = 1; i < lLowerSize - 1; i++) {
Chris Craik726118b2014-03-07 18:27:49 -0800211 retPoly[outIndex] = lLower[i];
212 outIndex--;
ztenghui7b4516e2014-01-07 10:42:55 -0800213 }
214 // TODO: Add test harness which verify that all the points are inside the hull.
Chris Craik726118b2014-03-07 18:27:49 -0800215 return total;
ztenghui7b4516e2014-01-07 10:42:55 -0800216}
217
218/**
ztenghuif5ca8b42014-01-27 15:53:28 -0800219 * Test whether the 3 points form a counter clockwise turn.
ztenghui7b4516e2014-01-07 10:42:55 -0800220 *
ztenghui7b4516e2014-01-07 10:42:55 -0800221 * @return true if a right hand turn
222 */
John Reck1bcacfd2017-11-03 10:12:19 -0700223bool SpotShadow::ccw(float ax, float ay, float bx, float by, float cx, float cy) {
ztenghui7b4516e2014-01-07 10:42:55 -0800224 return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > EPSILON;
225}
226
227/**
ztenghui7b4516e2014-01-07 10:42:55 -0800228 * Sort points about a center point
229 *
230 * @param poly The in and out polyogon as a Vector2 array.
231 * @param polyLength The number of vertices of the polygon.
232 * @param center the center ctr[0] = x , ctr[1] = y to sort around.
233 */
234void SpotShadow::sort(Vector2* poly, int polyLength, const Vector2& center) {
235 quicksortCirc(poly, 0, polyLength - 1, center);
236}
237
238/**
ztenghui7b4516e2014-01-07 10:42:55 -0800239 * Swap points pointed to by i and j
240 */
241void SpotShadow::swap(Vector2* points, int i, int j) {
242 Vector2 temp = points[i];
243 points[i] = points[j];
244 points[j] = temp;
245}
246
247/**
248 * quick sort implementation about the center.
249 */
John Reck1bcacfd2017-11-03 10:12:19 -0700250void SpotShadow::quicksortCirc(Vector2* points, int low, int high, const Vector2& center) {
ztenghui7b4516e2014-01-07 10:42:55 -0800251 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/**
ztenghui7b4516e2014-01-07 10:42:55 -0800273 * Test whether a point is inside the polygon.
274 *
275 * @param testPoint the point to test
276 * @param poly the polygon
277 * @return true if the testPoint is inside the poly.
278 */
John Reck1bcacfd2017-11-03 10:12:19 -0700279bool SpotShadow::testPointInsidePolygon(const Vector2 testPoint, const Vector2* poly, int len) {
ztenghui7b4516e2014-01-07 10:42:55 -0800280 bool c = false;
ztenghui9122b1b2014-10-03 11:21:11 -0700281 float testx = testPoint.x;
282 float testy = testPoint.y;
ztenghui7b4516e2014-01-07 10:42:55 -0800283 for (int i = 0, j = len - 1; i < len; j = i++) {
ztenghui9122b1b2014-10-03 11:21:11 -0700284 float startX = poly[j].x;
285 float startY = poly[j].y;
286 float endX = poly[i].x;
287 float endY = poly[i].y;
ztenghui7b4516e2014-01-07 10:42:55 -0800288
John Reck1bcacfd2017-11-03 10:12:19 -0700289 if (((endY > testy) != (startY > testy)) &&
290 (testx < (startX - endX) * (testy - endY) / (startY - endY) + endX)) {
ztenghui7b4516e2014-01-07 10:42:55 -0800291 c = !c;
292 }
293 }
294 return c;
295}
296
297/**
ztenghui7b4516e2014-01-07 10:42:55 -0800298 * Reverse the polygon
299 *
300 * @param polygon the polygon as a Vector2 array
301 * @param len the number of points of the polygon
302 */
303void SpotShadow::reverse(Vector2* polygon, int len) {
304 int n = len / 2;
305 for (int i = 0; i < n; i++) {
306 Vector2 tmp = polygon[i];
307 int k = len - 1 - i;
308 polygon[i] = polygon[k];
309 polygon[k] = tmp;
310 }
311}
312
313/**
ztenghui7b4516e2014-01-07 10:42:55 -0800314 * Compute a horizontal circular polygon about point (x , y , height) of radius
315 * (size)
316 *
317 * @param points number of the points of the output polygon.
318 * @param lightCenter the center of the light.
319 * @param size the light size.
320 * @param ret result polygon.
321 */
John Reck1bcacfd2017-11-03 10:12:19 -0700322void SpotShadow::computeLightPolygon(int points, const Vector3& lightCenter, float size,
323 Vector3* ret) {
ztenghui7b4516e2014-01-07 10:42:55 -0800324 // TODO: Caching all the sin / cos values and store them in a look up table.
325 for (int i = 0; i < points; i++) {
ztenghui9122b1b2014-10-03 11:21:11 -0700326 float angle = 2 * i * M_PI / points;
Chris Craik726118b2014-03-07 18:27:49 -0800327 ret[i].x = cosf(angle) * size + lightCenter.x;
328 ret[i].y = sinf(angle) * size + lightCenter.y;
ztenghui7b4516e2014-01-07 10:42:55 -0800329 ret[i].z = lightCenter.z;
330 }
331}
332
333/**
ztenghui512e6432014-09-10 13:08:20 -0700334 * From light center, project one vertex to the z=0 surface and get the outline.
ztenghui7b4516e2014-01-07 10:42:55 -0800335 *
ztenghui512e6432014-09-10 13:08:20 -0700336 * @param outline The result which is the outline position.
337 * @param lightCenter The center of light.
338 * @param polyVertex The input polygon's vertex.
339 *
340 * @return float The ratio of (polygon.z / light.z - polygon.z)
ztenghui7b4516e2014-01-07 10:42:55 -0800341 */
John Reck1bcacfd2017-11-03 10:12:19 -0700342float SpotShadow::projectCasterToOutline(Vector2& outline, const Vector3& lightCenter,
343 const Vector3& polyVertex) {
ztenghuic50a03d2014-08-21 13:47:54 -0700344 float lightToPolyZ = lightCenter.z - polyVertex.z;
345 float ratioZ = CASTER_Z_CAP_RATIO;
346 if (lightToPolyZ != 0) {
347 // If any caster's vertex is almost above the light, we just keep it as 95%
348 // of the height of the light.
ztenghui3bd3fa12014-08-25 14:42:27 -0700349 ratioZ = MathUtils::clamp(polyVertex.z / lightToPolyZ, 0.0f, CASTER_Z_CAP_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700350 }
351
352 outline.x = polyVertex.x - ratioZ * (lightCenter.x - polyVertex.x);
353 outline.y = polyVertex.y - ratioZ * (lightCenter.y - polyVertex.y);
354 return ratioZ;
355}
356
357/**
358 * Generate the shadow spot light of shape lightPoly and a object poly
359 *
360 * @param isCasterOpaque whether the caster is opaque
361 * @param lightCenter the center of the light
362 * @param lightSize the radius of the light
363 * @param poly x,y,z vertexes of a convex polygon that occludes the light source
364 * @param polyLength number of vertexes of the occluding polygon
365 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
366 * empty strip if error.
367 */
John Reck1bcacfd2017-11-03 10:12:19 -0700368void SpotShadow::createSpotShadow(bool isCasterOpaque, const Vector3& lightCenter, float lightSize,
369 const Vector3* poly, int polyLength, const Vector3& polyCentroid,
370 VertexBuffer& shadowTriangleStrip) {
ztenghui3bd3fa12014-08-25 14:42:27 -0700371 if (CC_UNLIKELY(lightCenter.z <= 0)) {
372 ALOGW("Relative Light Z is not positive. No spot shadow!");
373 return;
374 }
ztenghui512e6432014-09-10 13:08:20 -0700375 if (CC_UNLIKELY(polyLength < 3)) {
376#if DEBUG_SHADOW
377 ALOGW("Invalid polygon length. No spot shadow!");
378#endif
379 return;
380 }
ztenghuic50a03d2014-08-21 13:47:54 -0700381 OutlineData outlineData[polyLength];
382 Vector2 outlineCentroid;
383 // Calculate the projected outline for each polygon's vertices from the light center.
384 //
385 // O Light
386 // /
387 // /
388 // . Polygon vertex
389 // /
390 // /
391 // O Outline vertices
392 //
393 // Ratio = (Poly - Outline) / (Light - Poly)
394 // Outline.x = Poly.x - Ratio * (Light.x - Poly.x)
395 // Outline's radius / Light's radius = Ratio
396
397 // Compute the last outline vertex to make sure we can get the normal and outline
398 // in one single loop.
John Reck1bcacfd2017-11-03 10:12:19 -0700399 projectCasterToOutline(outlineData[polyLength - 1].position, lightCenter, poly[polyLength - 1]);
ztenghuic50a03d2014-08-21 13:47:54 -0700400
401 // Take the outline's polygon, calculate the normal for each outline edge.
402 int currentNormalIndex = polyLength - 1;
403 int nextNormalIndex = 0;
404
405 for (int i = 0; i < polyLength; i++) {
John Reck1bcacfd2017-11-03 10:12:19 -0700406 float ratioZ = projectCasterToOutline(outlineData[i].position, lightCenter, poly[i]);
ztenghuic50a03d2014-08-21 13:47:54 -0700407 outlineData[i].radius = ratioZ * lightSize;
408
409 outlineData[currentNormalIndex].normal = ShadowTessellator::calculateNormal(
John Reck1bcacfd2017-11-03 10:12:19 -0700410 outlineData[currentNormalIndex].position, outlineData[nextNormalIndex].position);
ztenghuic50a03d2014-08-21 13:47:54 -0700411 currentNormalIndex = (currentNormalIndex + 1) % polyLength;
412 nextNormalIndex++;
413 }
414
415 projectCasterToOutline(outlineCentroid, lightCenter, polyCentroid);
416
417 int penumbraIndex = 0;
ztenghui512e6432014-09-10 13:08:20 -0700418 // Then each polygon's vertex produce at minmal 2 penumbra vertices.
419 // Since the size can be dynamic here, we keep track of the size and update
420 // the real size at the end.
421 int allocatedPenumbraLength = 2 * polyLength + SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER;
422 Vector2 penumbra[allocatedPenumbraLength];
423 int totalExtraCornerSliceNumber = 0;
ztenghuic50a03d2014-08-21 13:47:54 -0700424
425 Vector2 umbra[polyLength];
ztenghuic50a03d2014-08-21 13:47:54 -0700426
ztenghui512e6432014-09-10 13:08:20 -0700427 // When centroid is covered by all circles from outline, then we consider
428 // the umbra is invalid, and we will tune down the shadow strength.
ztenghuic50a03d2014-08-21 13:47:54 -0700429 bool hasValidUmbra = true;
ztenghui512e6432014-09-10 13:08:20 -0700430 // We need the minimal of RaitoVI to decrease the spot shadow strength accordingly.
431 float minRaitoVI = FLT_MAX;
ztenghuic50a03d2014-08-21 13:47:54 -0700432
433 for (int i = 0; i < polyLength; i++) {
434 // Generate all the penumbra's vertices only using the (outline vertex + normal * radius)
435 // There is no guarantee that the penumbra is still convex, but for
436 // each outline vertex, it will connect to all its corresponding penumbra vertices as
437 // triangle fans. And for neighber penumbra vertex, it will be a trapezoid.
438 //
439 // Penumbra Vertices marked as Pi
440 // Outline Vertices marked as Vi
441 // (P3)
442 // (P2) | ' (P4)
443 // (P1)' | | '
444 // ' | | '
445 // (P0) ------------------------------------------------(P5)
446 // | (V0) |(V1)
447 // | |
448 // | |
449 // | |
450 // | |
451 // | |
452 // | |
453 // | |
454 // | |
455 // (V3)-----------------------------------(V2)
456 int preNormalIndex = (i + polyLength - 1) % polyLength;
ztenghuic50a03d2014-08-21 13:47:54 -0700457
ztenghui512e6432014-09-10 13:08:20 -0700458 const Vector2& previousNormal = outlineData[preNormalIndex].normal;
459 const Vector2& currentNormal = outlineData[i].normal;
460
461 // Depending on how roundness we want for each corner, we can subdivide
ztenghuic50a03d2014-08-21 13:47:54 -0700462 // further here and/or introduce some heuristic to decide how much the
463 // subdivision should be.
ztenghui512e6432014-09-10 13:08:20 -0700464 int currentExtraSliceNumber = ShadowTessellator::getExtraVertexNumber(
465 previousNormal, currentNormal, SPOT_CORNER_RADIANS_DIVISOR);
ztenghuic50a03d2014-08-21 13:47:54 -0700466
ztenghui512e6432014-09-10 13:08:20 -0700467 int currentCornerSliceNumber = 1 + currentExtraSliceNumber;
468 totalExtraCornerSliceNumber += currentExtraSliceNumber;
469#if DEBUG_SHADOW
470 ALOGD("currentExtraSliceNumber should be %d", currentExtraSliceNumber);
471 ALOGD("currentCornerSliceNumber should be %d", currentCornerSliceNumber);
472 ALOGD("totalCornerSliceNumber is %d", totalExtraCornerSliceNumber);
473#endif
474 if (CC_UNLIKELY(totalExtraCornerSliceNumber > SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER)) {
475 currentCornerSliceNumber = 1;
476 }
477 for (int k = 0; k <= currentCornerSliceNumber; k++) {
478 Vector2 avgNormal =
479 (previousNormal * (currentCornerSliceNumber - k) + currentNormal * k) /
480 currentCornerSliceNumber;
481 avgNormal.normalize();
John Reck1bcacfd2017-11-03 10:12:19 -0700482 penumbra[penumbraIndex++] = outlineData[i].position + avgNormal * outlineData[i].radius;
ztenghui512e6432014-09-10 13:08:20 -0700483 }
ztenghuic50a03d2014-08-21 13:47:54 -0700484
ztenghuic50a03d2014-08-21 13:47:54 -0700485 // Compute the umbra by the intersection from the outline's centroid!
486 //
487 // (V) ------------------------------------
488 // | ' |
489 // | ' |
490 // | ' (I) |
491 // | ' |
492 // | ' (C) |
493 // | |
494 // | |
495 // | |
496 // | |
497 // ------------------------------------
498 //
499 // Connect a line b/t the outline vertex (V) and the centroid (C), it will
500 // intersect with the outline vertex's circle at point (I).
501 // Now, ratioVI = VI / VC, ratioIC = IC / VC
502 // Then the intersetion point can be computed as Ixy = Vxy * ratioIC + Cxy * ratioVI;
503 //
ztenghui512e6432014-09-10 13:08:20 -0700504 // When all of the outline circles cover the the outline centroid, (like I is
ztenghuic50a03d2014-08-21 13:47:54 -0700505 // on the other side of C), there is no real umbra any more, so we just fake
506 // a small area around the centroid as the umbra, and tune down the spot
507 // shadow's umbra strength to simulate the effect the whole shadow will
508 // become lighter in this case.
509 // The ratio can be simulated by using the inverse of maximum of ratioVI for
510 // all (V).
ztenghui512e6432014-09-10 13:08:20 -0700511 float distOutline = (outlineData[i].position - outlineCentroid).length();
ztenghui3bd3fa12014-08-25 14:42:27 -0700512 if (CC_UNLIKELY(distOutline == 0)) {
ztenghuic50a03d2014-08-21 13:47:54 -0700513 // If the outline has 0 area, then there is no spot shadow anyway.
514 ALOGW("Outline has 0 area, no spot shadow!");
515 return;
516 }
ztenghui512e6432014-09-10 13:08:20 -0700517
518 float ratioVI = outlineData[i].radius / distOutline;
Chris Craik9db58c02015-08-19 15:19:18 -0700519 minRaitoVI = std::min(minRaitoVI, ratioVI);
ztenghui512e6432014-09-10 13:08:20 -0700520 if (ratioVI >= (1 - FAKE_UMBRA_SIZE_RATIO)) {
521 ratioVI = (1 - FAKE_UMBRA_SIZE_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700522 }
523 // When we know we don't have valid umbra, don't bother to compute the
524 // values below. But we can't skip the loop yet since we want to know the
525 // maximum ratio.
ztenghui512e6432014-09-10 13:08:20 -0700526 float ratioIC = 1 - ratioVI;
527 umbra[i] = outlineData[i].position * ratioIC + outlineCentroid * ratioVI;
ztenghuic50a03d2014-08-21 13:47:54 -0700528 }
529
ztenghui512e6432014-09-10 13:08:20 -0700530 hasValidUmbra = (minRaitoVI <= 1.0);
ztenghuic50a03d2014-08-21 13:47:54 -0700531 float shadowStrengthScale = 1.0;
532 if (!hasValidUmbra) {
ztenghui512e6432014-09-10 13:08:20 -0700533#if DEBUG_SHADOW
ztenghuic50a03d2014-08-21 13:47:54 -0700534 ALOGW("The object is too close to the light or too small, no real umbra!");
ztenghui512e6432014-09-10 13:08:20 -0700535#endif
ztenghuic50a03d2014-08-21 13:47:54 -0700536 for (int i = 0; i < polyLength; i++) {
537 umbra[i] = outlineData[i].position * FAKE_UMBRA_SIZE_RATIO +
John Reck1bcacfd2017-11-03 10:12:19 -0700538 outlineCentroid * (1 - FAKE_UMBRA_SIZE_RATIO);
ztenghuic50a03d2014-08-21 13:47:54 -0700539 }
ztenghui512e6432014-09-10 13:08:20 -0700540 shadowStrengthScale = 1.0 / minRaitoVI;
ztenghuic50a03d2014-08-21 13:47:54 -0700541 }
542
ztenghui512e6432014-09-10 13:08:20 -0700543 int penumbraLength = penumbraIndex;
544 int umbraLength = polyLength;
545
ztenghuic50a03d2014-08-21 13:47:54 -0700546#if DEBUG_SHADOW
John Reck1bcacfd2017-11-03 10:12:19 -0700547 ALOGD("penumbraLength is %d , allocatedPenumbraLength %d", penumbraLength,
548 allocatedPenumbraLength);
ztenghuic50a03d2014-08-21 13:47:54 -0700549 dumpPolygon(poly, polyLength, "input poly");
ztenghuic50a03d2014-08-21 13:47:54 -0700550 dumpPolygon(penumbra, penumbraLength, "penumbra");
ztenghui512e6432014-09-10 13:08:20 -0700551 dumpPolygon(umbra, umbraLength, "umbra");
ztenghuic50a03d2014-08-21 13:47:54 -0700552 ALOGD("hasValidUmbra is %d and shadowStrengthScale is %f", hasValidUmbra, shadowStrengthScale);
553#endif
554
ztenghui512e6432014-09-10 13:08:20 -0700555 // The penumbra and umbra needs to be in convex shape to keep consistency
556 // and quality.
557 // Since we are still shooting rays to penumbra, it needs to be convex.
558 // Umbra can be represented as a fan from the centroid, but visually umbra
559 // looks nicer when it is convex.
560 Vector2 finalUmbra[umbraLength];
561 Vector2 finalPenumbra[penumbraLength];
562 int finalUmbraLength = hull(umbra, umbraLength, finalUmbra);
563 int finalPenumbraLength = hull(penumbra, penumbraLength, finalPenumbra);
564
John Reck1bcacfd2017-11-03 10:12:19 -0700565 generateTriangleStrip(isCasterOpaque, shadowStrengthScale, finalPenumbra, finalPenumbraLength,
566 finalUmbra, finalUmbraLength, poly, polyLength, shadowTriangleStrip,
567 outlineCentroid);
ztenghuic50a03d2014-08-21 13:47:54 -0700568}
569
ztenghui7b4516e2014-01-07 10:42:55 -0800570/**
ztenghui7b4516e2014-01-07 10:42:55 -0800571 * This is only for experimental purpose.
572 * After intersections are calculated, we could smooth the polygon if needed.
573 * So far, we don't think it is more appealing yet.
574 *
575 * @param level The level of smoothness.
576 * @param rays The total number of rays.
577 * @param rayDist (In and Out) The distance for each ray.
578 *
579 */
580void SpotShadow::smoothPolygon(int level, int rays, float* rayDist) {
581 for (int k = 0; k < level; k++) {
582 for (int i = 0; i < rays; i++) {
583 float p1 = rayDist[(rays - 1 + i) % rays];
584 float p2 = rayDist[i];
585 float p3 = rayDist[(i + 1) % rays];
586 rayDist[i] = (p1 + p2 * 2 + p3) / 4;
587 }
588 }
589}
590
ztenghuid2dcd6f2014-10-29 16:04:29 -0700591// Index pair is meant for storing the tessellation information for the penumbra
592// area. One index must come from exterior tangent of the circles, the other one
593// must come from the interior tangent of the circles.
594struct IndexPair {
595 int outerIndex;
596 int innerIndex;
597};
ztenghui512e6432014-09-10 13:08:20 -0700598
ztenghuid2dcd6f2014-10-29 16:04:29 -0700599// For one penumbra vertex, find the cloest umbra vertex and return its index.
600inline int getClosestUmbraIndex(const Vector2& pivot, const Vector2* polygon, int polygonLength) {
601 float minLengthSquared = FLT_MAX;
ztenghui512e6432014-09-10 13:08:20 -0700602 int resultIndex = -1;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700603 bool hasDecreased = false;
604 // Starting with some negative offset, assuming both umbra and penumbra are starting
605 // at the same angle, this can help to find the result faster.
606 // Normally, loop 3 times, we can find the closest point.
607 int offset = polygonLength - 2;
608 for (int i = 0; i < polygonLength; i++) {
609 int currentIndex = (i + offset) % polygonLength;
610 float currentLengthSquared = (pivot - polygon[currentIndex]).lengthSquared();
611 if (currentLengthSquared < minLengthSquared) {
612 if (minLengthSquared != FLT_MAX) {
613 hasDecreased = true;
ztenghui512e6432014-09-10 13:08:20 -0700614 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700615 minLengthSquared = currentLengthSquared;
616 resultIndex = currentIndex;
617 } else if (currentLengthSquared > minLengthSquared && hasDecreased) {
618 // Early break b/c we have found the closet one and now the length
619 // is increasing again.
620 break;
ztenghui512e6432014-09-10 13:08:20 -0700621 }
622 }
John Reck1bcacfd2017-11-03 10:12:19 -0700623 if (resultIndex == -1) {
ztenghuid2dcd6f2014-10-29 16:04:29 -0700624 ALOGE("resultIndex is -1, the polygon must be invalid!");
625 resultIndex = 0;
ztenghui512e6432014-09-10 13:08:20 -0700626 }
627 return resultIndex;
628}
629
ztenghui39320632014-11-12 10:56:15 -0800630// Allow some epsilon here since the later ray intersection did allow for some small
631// floating point error, when the intersection point is slightly outside the segment.
ztenghuid2dcd6f2014-10-29 16:04:29 -0700632inline bool sameDirections(bool isPositiveCross, float a, float b) {
633 if (isPositiveCross) {
ztenghui39320632014-11-12 10:56:15 -0800634 return a >= -EPSILON && b >= -EPSILON;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700635 } else {
ztenghui39320632014-11-12 10:56:15 -0800636 return a <= EPSILON && b <= EPSILON;
ztenghui512e6432014-09-10 13:08:20 -0700637 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700638}
ztenghui512e6432014-09-10 13:08:20 -0700639
ztenghuid2dcd6f2014-10-29 16:04:29 -0700640// Find the right polygon edge to shoot the ray at.
641inline int findPolyIndex(bool isPositiveCross, int startPolyIndex, const Vector2& umbraDir,
John Reck1bcacfd2017-11-03 10:12:19 -0700642 const Vector2* polyToCentroid, int polyLength) {
ztenghuid2dcd6f2014-10-29 16:04:29 -0700643 // Make sure we loop with a bound.
644 for (int i = 0; i < polyLength; i++) {
645 int currentIndex = (i + startPolyIndex) % polyLength;
646 const Vector2& currentToCentroid = polyToCentroid[currentIndex];
647 const Vector2& nextToCentroid = polyToCentroid[(currentIndex + 1) % polyLength];
ztenghui512e6432014-09-10 13:08:20 -0700648
ztenghuid2dcd6f2014-10-29 16:04:29 -0700649 float currentCrossUmbra = currentToCentroid.cross(umbraDir);
650 float umbraCrossNext = umbraDir.cross(nextToCentroid);
651 if (sameDirections(isPositiveCross, currentCrossUmbra, umbraCrossNext)) {
ztenghui512e6432014-09-10 13:08:20 -0700652#if DEBUG_SHADOW
John Reck1bcacfd2017-11-03 10:12:19 -0700653 ALOGD("findPolyIndex loop %d times , index %d", i, currentIndex);
ztenghui512e6432014-09-10 13:08:20 -0700654#endif
ztenghuid2dcd6f2014-10-29 16:04:29 -0700655 return currentIndex;
ztenghui512e6432014-09-10 13:08:20 -0700656 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700657 }
658 LOG_ALWAYS_FATAL("Can't find the right polygon's edge from startPolyIndex %d", startPolyIndex);
659 return -1;
660}
ztenghui512e6432014-09-10 13:08:20 -0700661
ztenghuid2dcd6f2014-10-29 16:04:29 -0700662// Generate the index pair for penumbra / umbra vertices, and more penumbra vertices
663// if needed.
664inline void genNewPenumbraAndPairWithUmbra(const Vector2* penumbra, int penumbraLength,
John Reck1bcacfd2017-11-03 10:12:19 -0700665 const Vector2* umbra, int umbraLength,
666 Vector2* newPenumbra, int& newPenumbraIndex,
667 IndexPair* verticesPair, int& verticesPairIndex) {
ztenghuid2dcd6f2014-10-29 16:04:29 -0700668 // In order to keep everything in just one loop, we need to pre-compute the
669 // closest umbra vertex for the last penumbra vertex.
John Reck1bcacfd2017-11-03 10:12:19 -0700670 int previousClosestUmbraIndex =
671 getClosestUmbraIndex(penumbra[penumbraLength - 1], umbra, umbraLength);
ztenghuid2dcd6f2014-10-29 16:04:29 -0700672 for (int i = 0; i < penumbraLength; i++) {
673 const Vector2& currentPenumbraVertex = penumbra[i];
674 // For current penumbra vertex, starting from previousClosestUmbraIndex,
675 // then check the next one until the distance increase.
676 // The last one before the increase is the umbra vertex we need to pair with.
ztenghui39320632014-11-12 10:56:15 -0800677 float currentLengthSquared =
678 (currentPenumbraVertex - umbra[previousClosestUmbraIndex]).lengthSquared();
679 int currentClosestUmbraIndex = previousClosestUmbraIndex;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700680 int indexDelta = 0;
681 for (int j = 1; j < umbraLength; j++) {
682 int newUmbraIndex = (previousClosestUmbraIndex + j) % umbraLength;
683 float newLengthSquared = (currentPenumbraVertex - umbra[newUmbraIndex]).lengthSquared();
684 if (newLengthSquared > currentLengthSquared) {
ztenghui39320632014-11-12 10:56:15 -0800685 // currentClosestUmbraIndex is the umbra vertex's index which has
686 // currently found smallest distance, so we can simply break here.
ztenghuid2dcd6f2014-10-29 16:04:29 -0700687 break;
688 } else {
689 currentLengthSquared = newLengthSquared;
690 indexDelta++;
ztenghui39320632014-11-12 10:56:15 -0800691 currentClosestUmbraIndex = newUmbraIndex;
ztenghui512e6432014-09-10 13:08:20 -0700692 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700693 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700694
695 if (indexDelta > 1) {
John Reck1bcacfd2017-11-03 10:12:19 -0700696 // For those umbra don't have penumbra, generate new penumbra vertices by
697 // interpolation.
ztenghuid2dcd6f2014-10-29 16:04:29 -0700698 //
699 // Assuming Pi for penumbra vertices, and Ui for umbra vertices.
700 // In the case like below P1 paired with U1 and P2 paired with U5.
701 // U2 to U4 are unpaired umbra vertices.
702 //
703 // P1 P2
704 // | |
705 // U1 U2 U3 U4 U5
706 //
707 // We will need to generate 3 more penumbra vertices P1.1, P1.2, P1.3
708 // to pair with U2 to U4.
709 //
710 // P1 P1.1 P1.2 P1.3 P2
711 // | | | | |
712 // U1 U2 U3 U4 U5
713 //
714 // That distance ratio b/t Ui to U1 and Ui to U5 decides its paired penumbra
715 // vertex's location.
716 int newPenumbraNumber = indexDelta - 1;
717
Keith Moka1f56312015-11-10 16:52:05 -0800718 float accumulatedDeltaLength[indexDelta];
ztenghuid2dcd6f2014-10-29 16:04:29 -0700719 float totalDeltaLength = 0;
720
721 // To save time, cache the previous umbra vertex info outside the loop
722 // and update each loop.
723 Vector2 previousClosestUmbra = umbra[previousClosestUmbraIndex];
724 Vector2 skippedUmbra;
725 // Use umbra data to precompute the length b/t unpaired umbra vertices,
726 // and its ratio against the total length.
727 for (int k = 0; k < indexDelta; k++) {
728 int skippedUmbraIndex = (previousClosestUmbraIndex + k + 1) % umbraLength;
729 skippedUmbra = umbra[skippedUmbraIndex];
730 float currentDeltaLength = (skippedUmbra - previousClosestUmbra).length();
731
732 totalDeltaLength += currentDeltaLength;
733 accumulatedDeltaLength[k] = totalDeltaLength;
734
735 previousClosestUmbra = skippedUmbra;
736 }
737
738 const Vector2& previousPenumbra = penumbra[(i + penumbraLength - 1) % penumbraLength];
739 // Then for each unpaired umbra vertex, create a new penumbra by the ratio,
740 // and pair them togehter.
741 for (int k = 0; k < newPenumbraNumber; k++) {
742 float weightForCurrentPenumbra = 1.0f;
743 if (totalDeltaLength != 0.0f) {
744 weightForCurrentPenumbra = accumulatedDeltaLength[k] / totalDeltaLength;
745 }
746 float weightForPreviousPenumbra = 1.0f - weightForCurrentPenumbra;
747
748 Vector2 interpolatedPenumbra = currentPenumbraVertex * weightForCurrentPenumbra +
John Reck1bcacfd2017-11-03 10:12:19 -0700749 previousPenumbra * weightForPreviousPenumbra;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700750
751 int skippedUmbraIndex = (previousClosestUmbraIndex + k + 1) % umbraLength;
Andreas Gampeedaecc12014-11-10 20:54:07 -0800752 verticesPair[verticesPairIndex].outerIndex = newPenumbraIndex;
753 verticesPair[verticesPairIndex].innerIndex = skippedUmbraIndex;
754 verticesPairIndex++;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700755 newPenumbra[newPenumbraIndex++] = interpolatedPenumbra;
756 }
757 }
Andreas Gampeedaecc12014-11-10 20:54:07 -0800758 verticesPair[verticesPairIndex].outerIndex = newPenumbraIndex;
759 verticesPair[verticesPairIndex].innerIndex = currentClosestUmbraIndex;
760 verticesPairIndex++;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700761 newPenumbra[newPenumbraIndex++] = currentPenumbraVertex;
762
763 previousClosestUmbraIndex = currentClosestUmbraIndex;
764 }
765}
766
767// Precompute all the polygon's vector, return true if the reference cross product is positive.
John Reck1bcacfd2017-11-03 10:12:19 -0700768inline bool genPolyToCentroid(const Vector2* poly2d, int polyLength, const Vector2& centroid,
769 Vector2* polyToCentroid) {
ztenghuid2dcd6f2014-10-29 16:04:29 -0700770 for (int j = 0; j < polyLength; j++) {
771 polyToCentroid[j] = poly2d[j] - centroid;
ztenghui39320632014-11-12 10:56:15 -0800772 // Normalize these vectors such that we can use epsilon comparison after
773 // computing their cross products with another normalized vector.
774 polyToCentroid[j].normalize();
ztenghuid2dcd6f2014-10-29 16:04:29 -0700775 }
776 float refCrossProduct = 0;
777 for (int j = 0; j < polyLength; j++) {
778 refCrossProduct = polyToCentroid[j].cross(polyToCentroid[(j + 1) % polyLength]);
779 if (refCrossProduct != 0) {
780 break;
ztenghui512e6432014-09-10 13:08:20 -0700781 }
782 }
783
ztenghuid2dcd6f2014-10-29 16:04:29 -0700784 return refCrossProduct > 0;
785}
ztenghui512e6432014-09-10 13:08:20 -0700786
ztenghuid2dcd6f2014-10-29 16:04:29 -0700787// For one umbra vertex, shoot an ray from centroid to it.
788// If the ray hit the polygon first, then return the intersection point as the
789// closer vertex.
790inline Vector2 getCloserVertex(const Vector2& umbraVertex, const Vector2& centroid,
John Reck1bcacfd2017-11-03 10:12:19 -0700791 const Vector2* poly2d, int polyLength, const Vector2* polyToCentroid,
792 bool isPositiveCross, int& previousPolyIndex) {
ztenghuid2dcd6f2014-10-29 16:04:29 -0700793 Vector2 umbraToCentroid = umbraVertex - centroid;
794 float distanceToUmbra = umbraToCentroid.length();
795 umbraToCentroid = umbraToCentroid / distanceToUmbra;
796
797 // previousPolyIndex is updated for each item such that we can minimize the
798 // looping inside findPolyIndex();
John Reck1bcacfd2017-11-03 10:12:19 -0700799 previousPolyIndex = findPolyIndex(isPositiveCross, previousPolyIndex, umbraToCentroid,
800 polyToCentroid, polyLength);
ztenghuid2dcd6f2014-10-29 16:04:29 -0700801
802 float dx = umbraToCentroid.x;
803 float dy = umbraToCentroid.y;
John Reck1bcacfd2017-11-03 10:12:19 -0700804 float distanceToIntersectPoly =
805 rayIntersectPoints(centroid, dx, dy, poly2d[previousPolyIndex],
806 poly2d[(previousPolyIndex + 1) % polyLength]);
ztenghuid2dcd6f2014-10-29 16:04:29 -0700807 if (distanceToIntersectPoly < 0) {
808 distanceToIntersectPoly = 0;
809 }
810
811 // Pick the closer one as the occluded area vertex.
812 Vector2 closerVertex;
813 if (distanceToIntersectPoly < distanceToUmbra) {
814 closerVertex.x = centroid.x + dx * distanceToIntersectPoly;
815 closerVertex.y = centroid.y + dy * distanceToIntersectPoly;
816 } else {
817 closerVertex = umbraVertex;
818 }
819
820 return closerVertex;
ztenghui512e6432014-09-10 13:08:20 -0700821}
822
823/**
824 * Generate a triangle strip given two convex polygon
825**/
Andreas Gampe64bb4132014-11-22 00:35:09 +0000826void SpotShadow::generateTriangleStrip(bool isCasterOpaque, float shadowStrengthScale,
John Reck1bcacfd2017-11-03 10:12:19 -0700827 Vector2* penumbra, int penumbraLength, Vector2* umbra,
828 int umbraLength, const Vector3* poly, int polyLength,
829 VertexBuffer& shadowTriangleStrip, const Vector2& centroid) {
ztenghui512e6432014-09-10 13:08:20 -0700830 bool hasOccludedUmbraArea = false;
831 Vector2 poly2d[polyLength];
832
833 if (isCasterOpaque) {
834 for (int i = 0; i < polyLength; i++) {
835 poly2d[i].x = poly[i].x;
836 poly2d[i].y = poly[i].y;
837 }
838 // Make sure the centroid is inside the umbra, otherwise, fall back to the
839 // approach as if there is no occluded umbra area.
840 if (testPointInsidePolygon(centroid, poly2d, polyLength)) {
841 hasOccludedUmbraArea = true;
842 }
843 }
844
ztenghuid2dcd6f2014-10-29 16:04:29 -0700845 // For each penumbra vertex, find its corresponding closest umbra vertex index.
846 //
847 // Penumbra Vertices marked as Pi
848 // Umbra Vertices marked as Ui
849 // (P3)
850 // (P2) | ' (P4)
851 // (P1)' | | '
852 // ' | | '
853 // (P0) ------------------------------------------------(P5)
854 // | (U0) |(U1)
855 // | |
856 // | |(U2) (P5.1)
857 // | |
858 // | |
859 // | |
860 // | |
861 // | |
862 // | |
863 // (U4)-----------------------------------(U3) (P6)
864 //
865 // At least, like P0, P1, P2, they will find the matching umbra as U0.
866 // If we jump over some umbra vertex without matching penumbra vertex, then
867 // we will generate some new penumbra vertex by interpolation. Like P6 is
868 // matching U3, but U2 is not matched with any penumbra vertex.
869 // So interpolate P5.1 out and match U2.
870 // In this way, every umbra vertex will have a matching penumbra vertex.
871 //
872 // The total pair number can be as high as umbraLength + penumbraLength.
873 const int maxNewPenumbraLength = umbraLength + penumbraLength;
874 IndexPair verticesPair[maxNewPenumbraLength];
875 int verticesPairIndex = 0;
876
877 // Cache all the existing penumbra vertices and newly interpolated vertices into a
878 // a new array.
879 Vector2 newPenumbra[maxNewPenumbraLength];
880 int newPenumbraIndex = 0;
881
882 // For each penumbra vertex, find its closet umbra vertex by comparing the
883 // neighbor umbra vertices.
884 genNewPenumbraAndPairWithUmbra(penumbra, penumbraLength, umbra, umbraLength, newPenumbra,
John Reck1bcacfd2017-11-03 10:12:19 -0700885 newPenumbraIndex, verticesPair, verticesPairIndex);
ztenghuid2dcd6f2014-10-29 16:04:29 -0700886 ShadowTessellator::checkOverflow(verticesPairIndex, maxNewPenumbraLength, "Spot pair");
887 ShadowTessellator::checkOverflow(newPenumbraIndex, maxNewPenumbraLength, "Spot new penumbra");
888#if DEBUG_SHADOW
889 for (int i = 0; i < umbraLength; i++) {
890 ALOGD("umbra i %d, [%f, %f]", i, umbra[i].x, umbra[i].y);
ztenghui512e6432014-09-10 13:08:20 -0700891 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700892 for (int i = 0; i < newPenumbraIndex; i++) {
893 ALOGD("new penumbra i %d, [%f, %f]", i, newPenumbra[i].x, newPenumbra[i].y);
894 }
895 for (int i = 0; i < verticesPairIndex; i++) {
896 ALOGD("index i %d, [%d, %d]", i, verticesPair[i].outerIndex, verticesPair[i].innerIndex);
897 }
898#endif
ztenghui512e6432014-09-10 13:08:20 -0700899
ztenghuid2dcd6f2014-10-29 16:04:29 -0700900 // For the size of vertex buffer, we need 3 rings, one has newPenumbraSize,
901 // one has umbraLength, the last one has at most umbraLength.
902 //
903 // For the size of index buffer, the umbra area needs (2 * umbraLength + 2).
904 // The penumbra one can vary a bit, but it is bounded by (2 * verticesPairIndex + 2).
905 // And 2 more for jumping between penumbra to umbra.
906 const int newPenumbraLength = newPenumbraIndex;
907 const int totalVertexCount = newPenumbraLength + umbraLength * 2;
908 const int totalIndexCount = 2 * umbraLength + 2 * verticesPairIndex + 6;
John Reck1bcacfd2017-11-03 10:12:19 -0700909 AlphaVertex* shadowVertices = shadowTriangleStrip.alloc<AlphaVertex>(totalVertexCount);
910 uint16_t* indexBuffer = shadowTriangleStrip.allocIndices<uint16_t>(totalIndexCount);
ztenghui512e6432014-09-10 13:08:20 -0700911 int vertexBufferIndex = 0;
ztenghuid2dcd6f2014-10-29 16:04:29 -0700912 int indexBufferIndex = 0;
ztenghui512e6432014-09-10 13:08:20 -0700913
ztenghuid2dcd6f2014-10-29 16:04:29 -0700914 // Fill the IB and VB for the penumbra area.
915 for (int i = 0; i < newPenumbraLength; i++) {
John Reck1bcacfd2017-11-03 10:12:19 -0700916 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], newPenumbra[i].x, newPenumbra[i].y,
917 PENUMBRA_ALPHA);
ztenghuid2dcd6f2014-10-29 16:04:29 -0700918 }
Teng-Hui Zhu9c555562016-10-03 14:26:21 -0700919 // Since the umbra can be a faked one when the occluder is too high, the umbra should be lighter
920 // in this case.
921 float scaledUmbraAlpha = UMBRA_ALPHA * shadowStrengthScale;
922
ztenghuid2dcd6f2014-10-29 16:04:29 -0700923 for (int i = 0; i < umbraLength; i++) {
924 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], umbra[i].x, umbra[i].y,
John Reck1bcacfd2017-11-03 10:12:19 -0700925 scaledUmbraAlpha);
ztenghui512e6432014-09-10 13:08:20 -0700926 }
927
ztenghuid2dcd6f2014-10-29 16:04:29 -0700928 for (int i = 0; i < verticesPairIndex; i++) {
929 indexBuffer[indexBufferIndex++] = verticesPair[i].outerIndex;
930 // All umbra index need to be offseted by newPenumbraSize.
931 indexBuffer[indexBufferIndex++] = verticesPair[i].innerIndex + newPenumbraLength;
932 }
933 indexBuffer[indexBufferIndex++] = verticesPair[0].outerIndex;
934 indexBuffer[indexBufferIndex++] = verticesPair[0].innerIndex + newPenumbraLength;
ztenghui512e6432014-09-10 13:08:20 -0700935
ztenghuid2dcd6f2014-10-29 16:04:29 -0700936 // Now fill the IB and VB for the umbra area.
937 // First duplicated the index from previous strip and the first one for the
938 // degenerated triangles.
939 indexBuffer[indexBufferIndex] = indexBuffer[indexBufferIndex - 1];
940 indexBufferIndex++;
941 indexBuffer[indexBufferIndex++] = newPenumbraLength + 0;
942 // Save the first VB index for umbra area in order to close the loop.
943 int savedStartIndex = vertexBufferIndex;
944
ztenghui512e6432014-09-10 13:08:20 -0700945 if (hasOccludedUmbraArea) {
ztenghuid2dcd6f2014-10-29 16:04:29 -0700946 // Precompute all the polygon's vector, and the reference cross product,
947 // in order to find the right polygon edge for the ray to intersect.
948 Vector2 polyToCentroid[polyLength];
949 bool isPositiveCross = genPolyToCentroid(poly2d, polyLength, centroid, polyToCentroid);
ztenghui512e6432014-09-10 13:08:20 -0700950
ztenghuid2dcd6f2014-10-29 16:04:29 -0700951 // Because both the umbra and polygon are going in the same direction,
952 // we can save the previous polygon index to make sure we have less polygon
953 // vertex to compute for each ray.
954 int previousPolyIndex = 0;
955 for (int i = 0; i < umbraLength; i++) {
956 // Shoot a ray from centroid to each umbra vertices and pick the one with
957 // shorter distance to the centroid, b/t the umbra vertex or the intersection point.
John Reck1bcacfd2017-11-03 10:12:19 -0700958 Vector2 closerVertex =
959 getCloserVertex(umbra[i], centroid, poly2d, polyLength, polyToCentroid,
960 isPositiveCross, previousPolyIndex);
ztenghuid2dcd6f2014-10-29 16:04:29 -0700961
962 // We already stored the umbra vertices, just need to add the occlued umbra's ones.
963 indexBuffer[indexBufferIndex++] = newPenumbraLength + i;
964 indexBuffer[indexBufferIndex++] = vertexBufferIndex;
John Reck1bcacfd2017-11-03 10:12:19 -0700965 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], closerVertex.x, closerVertex.y,
966 scaledUmbraAlpha);
ztenghui512e6432014-09-10 13:08:20 -0700967 }
ztenghui512e6432014-09-10 13:08:20 -0700968 } else {
ztenghuid2dcd6f2014-10-29 16:04:29 -0700969 // If there is no occluded umbra at all, then draw the triangle fan
970 // starting from the centroid to all umbra vertices.
ztenghui512e6432014-09-10 13:08:20 -0700971 int lastCentroidIndex = vertexBufferIndex;
John Reck1bcacfd2017-11-03 10:12:19 -0700972 AlphaVertex::set(&shadowVertices[vertexBufferIndex++], centroid.x, centroid.y,
973 scaledUmbraAlpha);
ztenghuid2dcd6f2014-10-29 16:04:29 -0700974 for (int i = 0; i < umbraLength; i++) {
975 indexBuffer[indexBufferIndex++] = newPenumbraLength + i;
ztenghui512e6432014-09-10 13:08:20 -0700976 indexBuffer[indexBufferIndex++] = lastCentroidIndex;
977 }
ztenghui512e6432014-09-10 13:08:20 -0700978 }
ztenghuid2dcd6f2014-10-29 16:04:29 -0700979 // Closing the umbra area triangle's loop here.
980 indexBuffer[indexBufferIndex++] = newPenumbraLength;
981 indexBuffer[indexBufferIndex++] = savedStartIndex;
ztenghui512e6432014-09-10 13:08:20 -0700982
983 // At the end, update the real index and vertex buffer size.
984 shadowTriangleStrip.updateVertexCount(vertexBufferIndex);
985 shadowTriangleStrip.updateIndexCount(indexBufferIndex);
986 ShadowTessellator::checkOverflow(vertexBufferIndex, totalVertexCount, "Spot Vertex Buffer");
987 ShadowTessellator::checkOverflow(indexBufferIndex, totalIndexCount, "Spot Index Buffer");
988
Chris Craik117bdbc2015-02-05 10:12:38 -0800989 shadowTriangleStrip.setMeshFeatureFlags(VertexBuffer::kAlpha | VertexBuffer::kIndices);
ztenghui512e6432014-09-10 13:08:20 -0700990 shadowTriangleStrip.computeBounds<AlphaVertex>();
991}
992
ztenghuif5ca8b42014-01-27 15:53:28 -0800993#if DEBUG_SHADOW
994
995#define TEST_POINT_NUMBER 128
ztenghuif5ca8b42014-01-27 15:53:28 -0800996/**
997 * Calculate the bounds for generating random test points.
998 */
John Reck1bcacfd2017-11-03 10:12:19 -0700999void SpotShadow::updateBound(const Vector2 inVector, Vector2& lowerBound, Vector2& upperBound) {
ztenghuif5ca8b42014-01-27 15:53:28 -08001000 if (inVector.x < lowerBound.x) {
1001 lowerBound.x = inVector.x;
1002 }
1003
1004 if (inVector.y < lowerBound.y) {
1005 lowerBound.y = inVector.y;
1006 }
1007
1008 if (inVector.x > upperBound.x) {
1009 upperBound.x = inVector.x;
1010 }
1011
1012 if (inVector.y > upperBound.y) {
1013 upperBound.y = inVector.y;
1014 }
1015}
1016
1017/**
1018 * For debug purpose, when things go wrong, dump the whole polygon data.
1019 */
ztenghuic50a03d2014-08-21 13:47:54 -07001020void SpotShadow::dumpPolygon(const Vector2* poly, int polyLength, const char* polyName) {
1021 for (int i = 0; i < polyLength; i++) {
1022 ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
1023 }
1024}
1025
1026/**
1027 * For debug purpose, when things go wrong, dump the whole polygon data.
1028 */
1029void SpotShadow::dumpPolygon(const Vector3* poly, int polyLength, const char* polyName) {
ztenghuif5ca8b42014-01-27 15:53:28 -08001030 for (int i = 0; i < polyLength; i++) {
Teng-Hui Zhu8d0ec382015-10-01 16:49:16 -07001031 ALOGD("polygon %s i %d x %f y %f z %f", polyName, i, poly[i].x, poly[i].y, poly[i].z);
ztenghuif5ca8b42014-01-27 15:53:28 -08001032 }
1033}
1034
1035/**
1036 * Test whether the polygon is convex.
1037 */
John Reck1bcacfd2017-11-03 10:12:19 -07001038bool SpotShadow::testConvex(const Vector2* polygon, int polygonLength, const char* name) {
ztenghuif5ca8b42014-01-27 15:53:28 -08001039 bool isConvex = true;
1040 for (int i = 0; i < polygonLength; i++) {
1041 Vector2 start = polygon[i];
1042 Vector2 middle = polygon[(i + 1) % polygonLength];
1043 Vector2 end = polygon[(i + 2) % polygonLength];
1044
ztenghui9122b1b2014-10-03 11:21:11 -07001045 float delta = (float(middle.x) - start.x) * (float(end.y) - start.y) -
John Reck1bcacfd2017-11-03 10:12:19 -07001046 (float(middle.y) - start.y) * (float(end.x) - start.x);
ztenghuif5ca8b42014-01-27 15:53:28 -08001047 bool isCCWOrCoLinear = (delta >= EPSILON);
1048
1049 if (isCCWOrCoLinear) {
ztenghui50ecf842014-03-11 16:52:30 -07001050 ALOGW("(Error Type 2): polygon (%s) is not a convex b/c start (x %f, y %f),"
John Reck1bcacfd2017-11-03 10:12:19 -07001051 "middle (x %f, y %f) and end (x %f, y %f) , delta is %f !!!",
1052 name, start.x, start.y, middle.x, middle.y, end.x, end.y, delta);
ztenghuif5ca8b42014-01-27 15:53:28 -08001053 isConvex = false;
1054 break;
1055 }
1056 }
1057 return isConvex;
1058}
1059
1060/**
1061 * Test whether or not the polygon (intersection) is within the 2 input polygons.
1062 * Using Marte Carlo method, we generate a random point, and if it is inside the
1063 * intersection, then it must be inside both source polygons.
1064 */
John Reck1bcacfd2017-11-03 10:12:19 -07001065void SpotShadow::testIntersection(const Vector2* poly1, int poly1Length, const Vector2* poly2,
1066 int poly2Length, const Vector2* intersection,
1067 int intersectionLength) {
ztenghuif5ca8b42014-01-27 15:53:28 -08001068 // Find the min and max of x and y.
ztenghuic50a03d2014-08-21 13:47:54 -07001069 Vector2 lowerBound = {FLT_MAX, FLT_MAX};
1070 Vector2 upperBound = {-FLT_MAX, -FLT_MAX};
ztenghuif5ca8b42014-01-27 15:53:28 -08001071 for (int i = 0; i < poly1Length; i++) {
1072 updateBound(poly1[i], lowerBound, upperBound);
1073 }
1074 for (int i = 0; i < poly2Length; i++) {
1075 updateBound(poly2[i], lowerBound, upperBound);
1076 }
1077
1078 bool dumpPoly = false;
1079 for (int k = 0; k < TEST_POINT_NUMBER; k++) {
1080 // Generate a random point between minX, minY and maxX, maxY.
ztenghui9122b1b2014-10-03 11:21:11 -07001081 float randomX = rand() / float(RAND_MAX);
1082 float randomY = rand() / float(RAND_MAX);
ztenghuif5ca8b42014-01-27 15:53:28 -08001083
1084 Vector2 testPoint;
1085 testPoint.x = lowerBound.x + randomX * (upperBound.x - lowerBound.x);
1086 testPoint.y = lowerBound.y + randomY * (upperBound.y - lowerBound.y);
1087
1088 // If the random point is in both poly 1 and 2, then it must be intersection.
1089 if (testPointInsidePolygon(testPoint, intersection, intersectionLength)) {
1090 if (!testPointInsidePolygon(testPoint, poly1, poly1Length)) {
1091 dumpPoly = true;
ztenghui50ecf842014-03-11 16:52:30 -07001092 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
John Reck1bcacfd2017-11-03 10:12:19 -07001093 " not in the poly1",
1094 testPoint.x, testPoint.y);
ztenghuif5ca8b42014-01-27 15:53:28 -08001095 }
1096
1097 if (!testPointInsidePolygon(testPoint, poly2, poly2Length)) {
1098 dumpPoly = true;
ztenghui50ecf842014-03-11 16:52:30 -07001099 ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
John Reck1bcacfd2017-11-03 10:12:19 -07001100 " not in the poly2",
1101 testPoint.x, testPoint.y);
ztenghuif5ca8b42014-01-27 15:53:28 -08001102 }
1103 }
1104 }
1105
1106 if (dumpPoly) {
1107 dumpPolygon(intersection, intersectionLength, "intersection");
1108 for (int i = 1; i < intersectionLength; i++) {
1109 Vector2 delta = intersection[i] - intersection[i - 1];
1110 ALOGD("Intersetion i, %d Vs i-1 is delta %f", i, delta.lengthSquared());
1111 }
1112
1113 dumpPolygon(poly1, poly1Length, "poly 1");
1114 dumpPolygon(poly2, poly2Length, "poly 2");
1115 }
1116}
1117#endif
1118
John Reck1bcacfd2017-11-03 10:12:19 -07001119}; // namespace uirenderer
1120}; // namespace android