SpotShadow.cpp revision 9122b1b168d2a74d51517ed7282f4d6a8adea367
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "OpenGLRenderer"
18
19// The highest z value can't be higher than (CASTER_Z_CAP_RATIO * light.z)
20#define CASTER_Z_CAP_RATIO 0.95f
21
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
47
48#include <math.h>
49#include <stdlib.h>
50#include <utils/Log.h>
51
52#include "ShadowTessellator.h"
53#include "SpotShadow.h"
54#include "Vertex.h"
55#include "utils/MathUtils.h"
56
57// TODO: After we settle down the new algorithm, we can remove the old one and
58// its utility functions.
59// Right now, we still need to keep it for comparison purpose and future expansion.
60namespace android {
61namespace uirenderer {
62
63static const float EPSILON = 1e-7;
64
65/**
66 * For each polygon's vertex, the light center will project it to the receiver
67 * as one of the outline vertex.
68 * For each outline vertex, we need to store the position and normal.
69 * Normal here is defined against the edge by the current vertex and the next vertex.
70 */
71struct OutlineData {
72    Vector2 position;
73    Vector2 normal;
74    float radius;
75};
76
77/**
78 * For each vertex, we need to keep track of its angle, whether it is penumbra or
79 * umbra, and its corresponding vertex index.
80 */
81struct SpotShadow::VertexAngleData {
82    // The angle to the vertex from the centroid.
83    float mAngle;
84    // True is the vertex comes from penumbra, otherwise it comes from umbra.
85    bool mIsPenumbra;
86    // The index of the vertex described by this data.
87    int mVertexIndex;
88    void set(float angle, bool isPenumbra, int index) {
89        mAngle = angle;
90        mIsPenumbra = isPenumbra;
91        mVertexIndex = index;
92    }
93};
94
95/**
96 * Calculate the angle between and x and a y coordinate.
97 * The atan2 range from -PI to PI.
98 */
99static float angle(const Vector2& point, const Vector2& center) {
100    return atan2(point.y - center.y, point.x - center.x);
101}
102
103/**
104 * Calculate the intersection of a ray with the line segment defined by two points.
105 *
106 * Returns a negative value in error conditions.
107
108 * @param rayOrigin The start of the ray
109 * @param dx The x vector of the ray
110 * @param dy The y vector of the ray
111 * @param p1 The first point defining the line segment
112 * @param p2 The second point defining the line segment
113 * @return The distance along the ray if it intersects with the line segment, negative if otherwise
114 */
115static float rayIntersectPoints(const Vector2& rayOrigin, float dx, float dy,
116        const Vector2& p1, const Vector2& p2) {
117    // The math below is derived from solving this formula, basically the
118    // intersection point should stay on both the ray and the edge of (p1, p2).
119    // solve([p1x+t*(p2x-p1x)=dx*t2+px,p1y+t*(p2y-p1y)=dy*t2+py],[t,t2]);
120
121    float divisor = (dx * (p1.y - p2.y) + dy * p2.x - dy * p1.x);
122    if (divisor == 0) return -1.0f; // error, invalid divisor
123
124#if DEBUG_SHADOW
125    float interpVal = (dx * (p1.y - rayOrigin.y) + dy * rayOrigin.x - dy * p1.x) / divisor;
126    if (interpVal < 0 || interpVal > 1) {
127        ALOGW("rayIntersectPoints is hitting outside the segment %f", interpVal);
128    }
129#endif
130
131    float distance = (p1.x * (rayOrigin.y - p2.y) + p2.x * (p1.y - rayOrigin.y) +
132            rayOrigin.x * (p2.y - p1.y)) / divisor;
133
134    return distance; // may be negative in error cases
135}
136
137/**
138 * Sort points by their X coordinates
139 *
140 * @param points the points as a Vector2 array.
141 * @param pointsLength the number of vertices of the polygon.
142 */
143void SpotShadow::xsort(Vector2* points, int pointsLength) {
144    quicksortX(points, 0, pointsLength - 1);
145}
146
147/**
148 * compute the convex hull of a collection of Points
149 *
150 * @param points the points as a Vector2 array.
151 * @param pointsLength the number of vertices of the polygon.
152 * @param retPoly pre allocated array of floats to put the vertices
153 * @return the number of points in the polygon 0 if no intersection
154 */
155int SpotShadow::hull(Vector2* points, int pointsLength, Vector2* retPoly) {
156    xsort(points, pointsLength);
157    int n = pointsLength;
158    Vector2 lUpper[n];
159    lUpper[0] = points[0];
160    lUpper[1] = points[1];
161
162    int lUpperSize = 2;
163
164    for (int i = 2; i < n; i++) {
165        lUpper[lUpperSize] = points[i];
166        lUpperSize++;
167
168        while (lUpperSize > 2 && !ccw(
169                lUpper[lUpperSize - 3].x, lUpper[lUpperSize - 3].y,
170                lUpper[lUpperSize - 2].x, lUpper[lUpperSize - 2].y,
171                lUpper[lUpperSize - 1].x, lUpper[lUpperSize - 1].y)) {
172            // Remove the middle point of the three last
173            lUpper[lUpperSize - 2].x = lUpper[lUpperSize - 1].x;
174            lUpper[lUpperSize - 2].y = lUpper[lUpperSize - 1].y;
175            lUpperSize--;
176        }
177    }
178
179    Vector2 lLower[n];
180    lLower[0] = points[n - 1];
181    lLower[1] = points[n - 2];
182
183    int lLowerSize = 2;
184
185    for (int i = n - 3; i >= 0; i--) {
186        lLower[lLowerSize] = points[i];
187        lLowerSize++;
188
189        while (lLowerSize > 2 && !ccw(
190                lLower[lLowerSize - 3].x, lLower[lLowerSize - 3].y,
191                lLower[lLowerSize - 2].x, lLower[lLowerSize - 2].y,
192                lLower[lLowerSize - 1].x, lLower[lLowerSize - 1].y)) {
193            // Remove the middle point of the three last
194            lLower[lLowerSize - 2] = lLower[lLowerSize - 1];
195            lLowerSize--;
196        }
197    }
198
199    // output points in CW ordering
200    const int total = lUpperSize + lLowerSize - 2;
201    int outIndex = total - 1;
202    for (int i = 0; i < lUpperSize; i++) {
203        retPoly[outIndex] = lUpper[i];
204        outIndex--;
205    }
206
207    for (int i = 1; i < lLowerSize - 1; i++) {
208        retPoly[outIndex] = lLower[i];
209        outIndex--;
210    }
211    // TODO: Add test harness which verify that all the points are inside the hull.
212    return total;
213}
214
215/**
216 * Test whether the 3 points form a counter clockwise turn.
217 *
218 * @return true if a right hand turn
219 */
220bool SpotShadow::ccw(float ax, float ay, float bx, float by,
221        float cx, float cy) {
222    return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > EPSILON;
223}
224
225/**
226 * Sort points about a center point
227 *
228 * @param poly The in and out polyogon as a Vector2 array.
229 * @param polyLength The number of vertices of the polygon.
230 * @param center the center ctr[0] = x , ctr[1] = y to sort around.
231 */
232void SpotShadow::sort(Vector2* poly, int polyLength, const Vector2& center) {
233    quicksortCirc(poly, 0, polyLength - 1, center);
234}
235
236/**
237 * Swap points pointed to by i and j
238 */
239void SpotShadow::swap(Vector2* points, int i, int j) {
240    Vector2 temp = points[i];
241    points[i] = points[j];
242    points[j] = temp;
243}
244
245/**
246 * quick sort implementation about the center.
247 */
248void SpotShadow::quicksortCirc(Vector2* points, int low, int high,
249        const Vector2& center) {
250    int i = low, j = high;
251    int p = low + (high - low) / 2;
252    float pivot = angle(points[p], center);
253    while (i <= j) {
254        while (angle(points[i], center) > pivot) {
255            i++;
256        }
257        while (angle(points[j], center) < pivot) {
258            j--;
259        }
260
261        if (i <= j) {
262            swap(points, i, j);
263            i++;
264            j--;
265        }
266    }
267    if (low < j) quicksortCirc(points, low, j, center);
268    if (i < high) quicksortCirc(points, i, high, center);
269}
270
271/**
272 * Sort points by x axis
273 *
274 * @param points points to sort
275 * @param low start index
276 * @param high end index
277 */
278void SpotShadow::quicksortX(Vector2* points, int low, int high) {
279    int i = low, j = high;
280    int p = low + (high - low) / 2;
281    float pivot = points[p].x;
282    while (i <= j) {
283        while (points[i].x < pivot) {
284            i++;
285        }
286        while (points[j].x > pivot) {
287            j--;
288        }
289
290        if (i <= j) {
291            swap(points, i, j);
292            i++;
293            j--;
294        }
295    }
296    if (low < j) quicksortX(points, low, j);
297    if (i < high) quicksortX(points, i, high);
298}
299
300/**
301 * Test whether a point is inside the polygon.
302 *
303 * @param testPoint the point to test
304 * @param poly the polygon
305 * @return true if the testPoint is inside the poly.
306 */
307bool SpotShadow::testPointInsidePolygon(const Vector2 testPoint,
308        const Vector2* poly, int len) {
309    bool c = false;
310    float testx = testPoint.x;
311    float testy = testPoint.y;
312    for (int i = 0, j = len - 1; i < len; j = i++) {
313        float startX = poly[j].x;
314        float startY = poly[j].y;
315        float endX = poly[i].x;
316        float endY = poly[i].y;
317
318        if (((endY > testy) != (startY > testy))
319            && (testx < (startX - endX) * (testy - endY)
320             / (startY - endY) + endX)) {
321            c = !c;
322        }
323    }
324    return c;
325}
326
327/**
328 * Make the polygon turn clockwise.
329 *
330 * @param polygon the polygon as a Vector2 array.
331 * @param len the number of points of the polygon
332 */
333void SpotShadow::makeClockwise(Vector2* polygon, int len) {
334    if (polygon == 0  || len == 0) {
335        return;
336    }
337    if (!ShadowTessellator::isClockwise(polygon, len)) {
338        reverse(polygon, len);
339    }
340}
341
342/**
343 * Reverse the polygon
344 *
345 * @param polygon the polygon as a Vector2 array
346 * @param len the number of points of the polygon
347 */
348void SpotShadow::reverse(Vector2* polygon, int len) {
349    int n = len / 2;
350    for (int i = 0; i < n; i++) {
351        Vector2 tmp = polygon[i];
352        int k = len - 1 - i;
353        polygon[i] = polygon[k];
354        polygon[k] = tmp;
355    }
356}
357
358/**
359 * Compute a horizontal circular polygon about point (x , y , height) of radius
360 * (size)
361 *
362 * @param points number of the points of the output polygon.
363 * @param lightCenter the center of the light.
364 * @param size the light size.
365 * @param ret result polygon.
366 */
367void SpotShadow::computeLightPolygon(int points, const Vector3& lightCenter,
368        float size, Vector3* ret) {
369    // TODO: Caching all the sin / cos values and store them in a look up table.
370    for (int i = 0; i < points; i++) {
371        float angle = 2 * i * M_PI / points;
372        ret[i].x = cosf(angle) * size + lightCenter.x;
373        ret[i].y = sinf(angle) * size + lightCenter.y;
374        ret[i].z = lightCenter.z;
375    }
376}
377
378/**
379 * From light center, project one vertex to the z=0 surface and get the outline.
380 *
381 * @param outline The result which is the outline position.
382 * @param lightCenter The center of light.
383 * @param polyVertex The input polygon's vertex.
384 *
385 * @return float The ratio of (polygon.z / light.z - polygon.z)
386 */
387float SpotShadow::projectCasterToOutline(Vector2& outline,
388        const Vector3& lightCenter, const Vector3& polyVertex) {
389    float lightToPolyZ = lightCenter.z - polyVertex.z;
390    float ratioZ = CASTER_Z_CAP_RATIO;
391    if (lightToPolyZ != 0) {
392        // If any caster's vertex is almost above the light, we just keep it as 95%
393        // of the height of the light.
394        ratioZ = MathUtils::clamp(polyVertex.z / lightToPolyZ, 0.0f, CASTER_Z_CAP_RATIO);
395    }
396
397    outline.x = polyVertex.x - ratioZ * (lightCenter.x - polyVertex.x);
398    outline.y = polyVertex.y - ratioZ * (lightCenter.y - polyVertex.y);
399    return ratioZ;
400}
401
402/**
403 * Generate the shadow spot light of shape lightPoly and a object poly
404 *
405 * @param isCasterOpaque whether the caster is opaque
406 * @param lightCenter the center of the light
407 * @param lightSize the radius of the light
408 * @param poly x,y,z vertexes of a convex polygon that occludes the light source
409 * @param polyLength number of vertexes of the occluding polygon
410 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
411 *                            empty strip if error.
412 */
413void SpotShadow::createSpotShadow(bool isCasterOpaque, const Vector3& lightCenter,
414        float lightSize, const Vector3* poly, int polyLength, const Vector3& polyCentroid,
415        VertexBuffer& shadowTriangleStrip) {
416    if (CC_UNLIKELY(lightCenter.z <= 0)) {
417        ALOGW("Relative Light Z is not positive. No spot shadow!");
418        return;
419    }
420    if (CC_UNLIKELY(polyLength < 3)) {
421#if DEBUG_SHADOW
422        ALOGW("Invalid polygon length. No spot shadow!");
423#endif
424        return;
425    }
426    OutlineData outlineData[polyLength];
427    Vector2 outlineCentroid;
428    // Calculate the projected outline for each polygon's vertices from the light center.
429    //
430    //                       O     Light
431    //                      /
432    //                    /
433    //                   .     Polygon vertex
434    //                 /
435    //               /
436    //              O     Outline vertices
437    //
438    // Ratio = (Poly - Outline) / (Light - Poly)
439    // Outline.x = Poly.x - Ratio * (Light.x - Poly.x)
440    // Outline's radius / Light's radius = Ratio
441
442    // Compute the last outline vertex to make sure we can get the normal and outline
443    // in one single loop.
444    projectCasterToOutline(outlineData[polyLength - 1].position, lightCenter,
445            poly[polyLength - 1]);
446
447    // Take the outline's polygon, calculate the normal for each outline edge.
448    int currentNormalIndex = polyLength - 1;
449    int nextNormalIndex = 0;
450
451    for (int i = 0; i < polyLength; i++) {
452        float ratioZ = projectCasterToOutline(outlineData[i].position,
453                lightCenter, poly[i]);
454        outlineData[i].radius = ratioZ * lightSize;
455
456        outlineData[currentNormalIndex].normal = ShadowTessellator::calculateNormal(
457                outlineData[currentNormalIndex].position,
458                outlineData[nextNormalIndex].position);
459        currentNormalIndex = (currentNormalIndex + 1) % polyLength;
460        nextNormalIndex++;
461    }
462
463    projectCasterToOutline(outlineCentroid, lightCenter, polyCentroid);
464
465    int penumbraIndex = 0;
466    // Then each polygon's vertex produce at minmal 2 penumbra vertices.
467    // Since the size can be dynamic here, we keep track of the size and update
468    // the real size at the end.
469    int allocatedPenumbraLength = 2 * polyLength + SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER;
470    Vector2 penumbra[allocatedPenumbraLength];
471    int totalExtraCornerSliceNumber = 0;
472
473    Vector2 umbra[polyLength];
474
475    // When centroid is covered by all circles from outline, then we consider
476    // the umbra is invalid, and we will tune down the shadow strength.
477    bool hasValidUmbra = true;
478    // We need the minimal of RaitoVI to decrease the spot shadow strength accordingly.
479    float minRaitoVI = FLT_MAX;
480
481    for (int i = 0; i < polyLength; i++) {
482        // Generate all the penumbra's vertices only using the (outline vertex + normal * radius)
483        // There is no guarantee that the penumbra is still convex, but for
484        // each outline vertex, it will connect to all its corresponding penumbra vertices as
485        // triangle fans. And for neighber penumbra vertex, it will be a trapezoid.
486        //
487        // Penumbra Vertices marked as Pi
488        // Outline Vertices marked as Vi
489        //                                            (P3)
490        //          (P2)                               |     ' (P4)
491        //   (P1)'   |                                 |   '
492        //         ' |                                 | '
493        // (P0)  ------------------------------------------------(P5)
494        //           | (V0)                            |(V1)
495        //           |                                 |
496        //           |                                 |
497        //           |                                 |
498        //           |                                 |
499        //           |                                 |
500        //           |                                 |
501        //           |                                 |
502        //           |                                 |
503        //       (V3)-----------------------------------(V2)
504        int preNormalIndex = (i + polyLength - 1) % polyLength;
505
506        const Vector2& previousNormal = outlineData[preNormalIndex].normal;
507        const Vector2& currentNormal = outlineData[i].normal;
508
509        // Depending on how roundness we want for each corner, we can subdivide
510        // further here and/or introduce some heuristic to decide how much the
511        // subdivision should be.
512        int currentExtraSliceNumber = ShadowTessellator::getExtraVertexNumber(
513                previousNormal, currentNormal, SPOT_CORNER_RADIANS_DIVISOR);
514
515        int currentCornerSliceNumber = 1 + currentExtraSliceNumber;
516        totalExtraCornerSliceNumber += currentExtraSliceNumber;
517#if DEBUG_SHADOW
518        ALOGD("currentExtraSliceNumber should be %d", currentExtraSliceNumber);
519        ALOGD("currentCornerSliceNumber should be %d", currentCornerSliceNumber);
520        ALOGD("totalCornerSliceNumber is %d", totalExtraCornerSliceNumber);
521#endif
522        if (CC_UNLIKELY(totalExtraCornerSliceNumber > SPOT_MAX_EXTRA_CORNER_VERTEX_NUMBER)) {
523            currentCornerSliceNumber = 1;
524        }
525        for (int k = 0; k <= currentCornerSliceNumber; k++) {
526            Vector2 avgNormal =
527                    (previousNormal * (currentCornerSliceNumber - k) + currentNormal * k) /
528                    currentCornerSliceNumber;
529            avgNormal.normalize();
530            penumbra[penumbraIndex++] = outlineData[i].position +
531                    avgNormal * outlineData[i].radius;
532        }
533
534
535        // Compute the umbra by the intersection from the outline's centroid!
536        //
537        //       (V) ------------------------------------
538        //           |          '                       |
539        //           |         '                        |
540        //           |       ' (I)                      |
541        //           |    '                             |
542        //           | '             (C)                |
543        //           |                                  |
544        //           |                                  |
545        //           |                                  |
546        //           |                                  |
547        //           ------------------------------------
548        //
549        // Connect a line b/t the outline vertex (V) and the centroid (C), it will
550        // intersect with the outline vertex's circle at point (I).
551        // Now, ratioVI = VI / VC, ratioIC = IC / VC
552        // Then the intersetion point can be computed as Ixy = Vxy * ratioIC + Cxy * ratioVI;
553        //
554        // When all of the outline circles cover the the outline centroid, (like I is
555        // on the other side of C), there is no real umbra any more, so we just fake
556        // a small area around the centroid as the umbra, and tune down the spot
557        // shadow's umbra strength to simulate the effect the whole shadow will
558        // become lighter in this case.
559        // The ratio can be simulated by using the inverse of maximum of ratioVI for
560        // all (V).
561        float distOutline = (outlineData[i].position - outlineCentroid).length();
562        if (CC_UNLIKELY(distOutline == 0)) {
563            // If the outline has 0 area, then there is no spot shadow anyway.
564            ALOGW("Outline has 0 area, no spot shadow!");
565            return;
566        }
567
568        float ratioVI = outlineData[i].radius / distOutline;
569        minRaitoVI = MathUtils::min(minRaitoVI, ratioVI);
570        if (ratioVI >= (1 - FAKE_UMBRA_SIZE_RATIO)) {
571            ratioVI = (1 - FAKE_UMBRA_SIZE_RATIO);
572        }
573        // When we know we don't have valid umbra, don't bother to compute the
574        // values below. But we can't skip the loop yet since we want to know the
575        // maximum ratio.
576        float ratioIC = 1 - ratioVI;
577        umbra[i] = outlineData[i].position * ratioIC + outlineCentroid * ratioVI;
578    }
579
580    hasValidUmbra = (minRaitoVI <= 1.0);
581    float shadowStrengthScale = 1.0;
582    if (!hasValidUmbra) {
583#if DEBUG_SHADOW
584        ALOGW("The object is too close to the light or too small, no real umbra!");
585#endif
586        for (int i = 0; i < polyLength; i++) {
587            umbra[i] = outlineData[i].position * FAKE_UMBRA_SIZE_RATIO +
588                    outlineCentroid * (1 - FAKE_UMBRA_SIZE_RATIO);
589        }
590        shadowStrengthScale = 1.0 / minRaitoVI;
591    }
592
593    int penumbraLength = penumbraIndex;
594    int umbraLength = polyLength;
595
596#if DEBUG_SHADOW
597    ALOGD("penumbraLength is %d , allocatedPenumbraLength %d", penumbraLength, allocatedPenumbraLength);
598    dumpPolygon(poly, polyLength, "input poly");
599    dumpPolygon(penumbra, penumbraLength, "penumbra");
600    dumpPolygon(umbra, umbraLength, "umbra");
601    ALOGD("hasValidUmbra is %d and shadowStrengthScale is %f", hasValidUmbra, shadowStrengthScale);
602#endif
603
604    // The penumbra and umbra needs to be in convex shape to keep consistency
605    // and quality.
606    // Since we are still shooting rays to penumbra, it needs to be convex.
607    // Umbra can be represented as a fan from the centroid, but visually umbra
608    // looks nicer when it is convex.
609    Vector2 finalUmbra[umbraLength];
610    Vector2 finalPenumbra[penumbraLength];
611    int finalUmbraLength = hull(umbra, umbraLength, finalUmbra);
612    int finalPenumbraLength = hull(penumbra, penumbraLength, finalPenumbra);
613
614    generateTriangleStrip(isCasterOpaque, shadowStrengthScale, finalPenumbra,
615            finalPenumbraLength, finalUmbra, finalUmbraLength, poly, polyLength,
616            shadowTriangleStrip, outlineCentroid);
617
618}
619
620/**
621 * Converts a polygon specified with CW vertices into an array of distance-from-centroid values.
622 *
623 * Returns false in error conditions
624 *
625 * @param poly Array of vertices. Note that these *must* be CW.
626 * @param polyLength The number of vertices in the polygon.
627 * @param polyCentroid The centroid of the polygon, from which rays will be cast
628 * @param rayDist The output array for the calculated distances, must be SHADOW_RAY_COUNT in size
629 */
630bool convertPolyToRayDist(const Vector2* poly, int polyLength, const Vector2& polyCentroid,
631        float* rayDist) {
632    const int rays = SHADOW_RAY_COUNT;
633    const float step = M_PI * 2 / rays;
634
635    const Vector2* lastVertex = &(poly[polyLength - 1]);
636    float startAngle = angle(*lastVertex, polyCentroid);
637
638    // Start with the ray that's closest to and less than startAngle
639    int rayIndex = floor((startAngle - EPSILON) / step);
640    rayIndex = (rayIndex + rays) % rays; // ensure positive
641
642    for (int polyIndex = 0; polyIndex < polyLength; polyIndex++) {
643        /*
644         * For a given pair of vertices on the polygon, poly[i-1] and poly[i], the rays that
645         * intersect these will be those that are between the two angles from the centroid that the
646         * vertices define.
647         *
648         * Because the polygon vertices are stored clockwise, the closest ray with an angle
649         * *smaller* than that defined by angle(poly[i], centroid) will be the first ray that does
650         * not intersect with poly[i-1], poly[i].
651         */
652        float currentAngle = angle(poly[polyIndex], polyCentroid);
653
654        // find first ray that will not intersect the line segment poly[i-1] & poly[i]
655        int firstRayIndexOnNextSegment = floor((currentAngle - EPSILON) / step);
656        firstRayIndexOnNextSegment = (firstRayIndexOnNextSegment + rays) % rays; // ensure positive
657
658        // Iterate through all rays that intersect with poly[i-1], poly[i] line segment.
659        // This may be 0 rays.
660        while (rayIndex != firstRayIndexOnNextSegment) {
661            float distanceToIntersect = rayIntersectPoints(polyCentroid,
662                    cos(rayIndex * step),
663                    sin(rayIndex * step),
664                    *lastVertex, poly[polyIndex]);
665            if (distanceToIntersect < 0) {
666#if DEBUG_SHADOW
667                ALOGW("ERROR: convertPolyToRayDist failed");
668#endif
669                return false; // error case, abort
670            }
671
672            rayDist[rayIndex] = distanceToIntersect;
673
674            rayIndex = (rayIndex - 1 + rays) % rays;
675        }
676        lastVertex = &poly[polyIndex];
677    }
678
679    return true;
680}
681
682/**
683 * This is only for experimental purpose.
684 * After intersections are calculated, we could smooth the polygon if needed.
685 * So far, we don't think it is more appealing yet.
686 *
687 * @param level The level of smoothness.
688 * @param rays The total number of rays.
689 * @param rayDist (In and Out) The distance for each ray.
690 *
691 */
692void SpotShadow::smoothPolygon(int level, int rays, float* rayDist) {
693    for (int k = 0; k < level; k++) {
694        for (int i = 0; i < rays; i++) {
695            float p1 = rayDist[(rays - 1 + i) % rays];
696            float p2 = rayDist[i];
697            float p3 = rayDist[(i + 1) % rays];
698            rayDist[i] = (p1 + p2 * 2 + p3) / 4;
699        }
700    }
701}
702
703/**
704 * Generate a array of the angleData for either umbra or penumbra vertices.
705 *
706 * This array will be merged and used to guide where to shoot the rays, in clockwise order.
707 *
708 * @param angleDataList The result array of angle data.
709 *
710 * @return int The maximum angle's index in the array.
711 */
712int SpotShadow::setupAngleList(VertexAngleData* angleDataList,
713        int polyLength, const Vector2* polygon, const Vector2& centroid,
714        bool isPenumbra, const char* name) {
715    float maxAngle = FLT_MIN;
716    int maxAngleIndex = 0;
717    for (int i = 0; i < polyLength; i++) {
718        float currentAngle = angle(polygon[i], centroid);
719        if (currentAngle > maxAngle) {
720            maxAngle = currentAngle;
721            maxAngleIndex = i;
722        }
723        angleDataList[i].set(currentAngle, isPenumbra, i);
724#if DEBUG_SHADOW
725        ALOGD("%s AngleList i %d %f", name, i, currentAngle);
726#endif
727    }
728    return maxAngleIndex;
729}
730
731/**
732 * Make sure the polygons are indeed in clockwise order.
733 *
734 * Possible reasons to return false: 1. The input polygon is not setup properly. 2. The hull
735 * algorithm is not able to generate it properly.
736 *
737 * Anyway, since the algorithm depends on the clockwise, when these kind of unexpected error
738 * situation is found, we need to detect it and early return without corrupting the memory.
739 *
740 * @return bool True if the angle list is actually from big to small.
741 */
742bool SpotShadow::checkClockwise(int indexOfMaxAngle, int listLength, VertexAngleData* angleList,
743        const char* name) {
744    int currentIndex = indexOfMaxAngle;
745#if DEBUG_SHADOW
746    ALOGD("max index %d", currentIndex);
747#endif
748    for (int i = 0; i < listLength - 1; i++) {
749        // TODO: Cache the last angle.
750        float currentAngle = angleList[currentIndex].mAngle;
751        float nextAngle = angleList[(currentIndex + 1) % listLength].mAngle;
752        if (currentAngle < nextAngle) {
753#if DEBUG_SHADOW
754            ALOGE("%s, is not CW, at index %d", name, currentIndex);
755#endif
756            return false;
757        }
758        currentIndex = (currentIndex + 1) % listLength;
759    }
760    return true;
761}
762
763/**
764 * Check the polygon is clockwise.
765 *
766 * @return bool True is the polygon is clockwise.
767 */
768bool SpotShadow::checkPolyClockwise(int polyAngleLength, int maxPolyAngleIndex,
769        const float* polyAngleList) {
770    bool isPolyCW = true;
771    // Starting from maxPolyAngleIndex , check around to make sure angle decrease.
772    for (int i = 0; i < polyAngleLength - 1; i++) {
773        float currentAngle = polyAngleList[(i + maxPolyAngleIndex) % polyAngleLength];
774        float nextAngle = polyAngleList[(i + maxPolyAngleIndex + 1) % polyAngleLength];
775        if (currentAngle < nextAngle) {
776            isPolyCW = false;
777        }
778    }
779    return isPolyCW;
780}
781
782/**
783 * Given the sorted array of all the vertices angle data, calculate for each
784 * vertices, the offset value to array element which represent the start edge
785 * of the polygon we need to shoot the ray at.
786 *
787 * TODO: Calculate this for umbra and penumbra in one loop using one single array.
788 *
789 * @param distances The result of the array distance counter.
790 */
791void SpotShadow::calculateDistanceCounter(bool needsOffsetToUmbra, int angleLength,
792        const VertexAngleData* allVerticesAngleData, int* distances) {
793
794    bool firstVertexIsPenumbra = allVerticesAngleData[0].mIsPenumbra;
795    // If we want distance to inner, then we just set to 0 when we see inner.
796    bool needsSearch = needsOffsetToUmbra ? firstVertexIsPenumbra : !firstVertexIsPenumbra;
797    int distanceCounter = 0;
798    if (needsSearch) {
799        int foundIndex = -1;
800        for (int i = (angleLength - 1); i >= 0; i--) {
801            bool currentIsOuter = allVerticesAngleData[i].mIsPenumbra;
802            // If we need distance to inner, then we need to find a inner vertex.
803            if (currentIsOuter != firstVertexIsPenumbra) {
804                foundIndex = i;
805                break;
806            }
807        }
808        LOG_ALWAYS_FATAL_IF(foundIndex == -1, "Wrong index found, means either"
809                " umbra or penumbra's length is 0");
810        distanceCounter = angleLength - foundIndex;
811    }
812#if DEBUG_SHADOW
813    ALOGD("distances[0] is %d", distanceCounter);
814#endif
815
816    distances[0] = distanceCounter; // means never see a target poly
817
818    for (int i = 1; i < angleLength; i++) {
819        bool firstVertexIsPenumbra = allVerticesAngleData[i].mIsPenumbra;
820        // When we needs for distance for each outer vertex to inner, then we
821        // increase the distance when seeing outer vertices. Otherwise, we clear
822        // to 0.
823        bool needsIncrement = needsOffsetToUmbra ? firstVertexIsPenumbra : !firstVertexIsPenumbra;
824        // If counter is not -1, that means we have seen an other polygon's vertex.
825        if (needsIncrement && distanceCounter != -1) {
826            distanceCounter++;
827        } else {
828            distanceCounter = 0;
829        }
830        distances[i] = distanceCounter;
831    }
832}
833
834/**
835 * Given umbra and penumbra angle data list, merge them by sorting the angle
836 * from the biggest to smallest.
837 *
838 * @param allVerticesAngleData The result array of merged angle data.
839 */
840void SpotShadow::mergeAngleList(int maxUmbraAngleIndex, int maxPenumbraAngleIndex,
841        const VertexAngleData* umbraAngleList, int umbraLength,
842        const VertexAngleData* penumbraAngleList, int penumbraLength,
843        VertexAngleData* allVerticesAngleData) {
844
845    int totalRayNumber = umbraLength + penumbraLength;
846    int umbraIndex = maxUmbraAngleIndex;
847    int penumbraIndex = maxPenumbraAngleIndex;
848
849    float currentUmbraAngle = umbraAngleList[umbraIndex].mAngle;
850    float currentPenumbraAngle = penumbraAngleList[penumbraIndex].mAngle;
851
852    // TODO: Clean this up using a while loop with 2 iterators.
853    for (int i = 0; i < totalRayNumber; i++) {
854        if (currentUmbraAngle > currentPenumbraAngle) {
855            allVerticesAngleData[i] = umbraAngleList[umbraIndex];
856            umbraIndex = (umbraIndex + 1) % umbraLength;
857
858            // If umbraIndex round back, that means we are running out of
859            // umbra vertices to merge, so just copy all the penumbra leftover.
860            // Otherwise, we update the currentUmbraAngle.
861            if (umbraIndex != maxUmbraAngleIndex) {
862                currentUmbraAngle = umbraAngleList[umbraIndex].mAngle;
863            } else {
864                for (int j = i + 1; j < totalRayNumber; j++) {
865                    allVerticesAngleData[j] = penumbraAngleList[penumbraIndex];
866                    penumbraIndex = (penumbraIndex + 1) % penumbraLength;
867                }
868                break;
869            }
870        } else {
871            allVerticesAngleData[i] = penumbraAngleList[penumbraIndex];
872            penumbraIndex = (penumbraIndex + 1) % penumbraLength;
873            // If penumbraIndex round back, that means we are running out of
874            // penumbra vertices to merge, so just copy all the umbra leftover.
875            // Otherwise, we update the currentPenumbraAngle.
876            if (penumbraIndex != maxPenumbraAngleIndex) {
877                currentPenumbraAngle = penumbraAngleList[penumbraIndex].mAngle;
878            } else {
879                for (int j = i + 1; j < totalRayNumber; j++) {
880                    allVerticesAngleData[j] = umbraAngleList[umbraIndex];
881                    umbraIndex = (umbraIndex + 1) % umbraLength;
882                }
883                break;
884            }
885        }
886    }
887}
888
889#if DEBUG_SHADOW
890/**
891 * DEBUG ONLY: Verify all the offset compuation is correctly done by examining
892 * each vertex and its neighbor.
893 */
894static void verifyDistanceCounter(const VertexAngleData* allVerticesAngleData,
895        const int* distances, int angleLength, const char* name) {
896    int currentDistance = distances[0];
897    for (int i = 1; i < angleLength; i++) {
898        if (distances[i] != INT_MIN) {
899            if (!((currentDistance + 1) == distances[i]
900                || distances[i] == 0)) {
901                ALOGE("Wrong distance found at i %d name %s", i, name);
902            }
903            currentDistance = distances[i];
904            if (currentDistance != 0) {
905                bool currentOuter = allVerticesAngleData[i].mIsPenumbra;
906                for (int j = 1; j <= (currentDistance - 1); j++) {
907                    bool neigborOuter =
908                            allVerticesAngleData[(i + angleLength - j) % angleLength].mIsPenumbra;
909                    if (neigborOuter != currentOuter) {
910                        ALOGE("Wrong distance found at i %d name %s", i, name);
911                    }
912                }
913                bool oppositeOuter =
914                    allVerticesAngleData[(i + angleLength - currentDistance) % angleLength].mIsPenumbra;
915                if (oppositeOuter == currentOuter) {
916                    ALOGE("Wrong distance found at i %d name %s", i, name);
917                }
918            }
919        }
920    }
921}
922
923/**
924 * DEBUG ONLY: Verify all the angle data compuated are  is correctly done
925 */
926static void verifyAngleData(int totalRayNumber, const VertexAngleData* allVerticesAngleData,
927        const int* distancesToInner, const int* distancesToOuter,
928        const VertexAngleData* umbraAngleList, int maxUmbraAngleIndex, int umbraLength,
929        const VertexAngleData* penumbraAngleList, int maxPenumbraAngleIndex,
930        int penumbraLength) {
931    for (int i = 0; i < totalRayNumber; i++) {
932        ALOGD("currentAngleList i %d, angle %f, isInner %d, index %d distancesToInner"
933              " %d distancesToOuter %d", i, allVerticesAngleData[i].mAngle,
934                !allVerticesAngleData[i].mIsPenumbra,
935                allVerticesAngleData[i].mVertexIndex, distancesToInner[i], distancesToOuter[i]);
936    }
937
938    verifyDistanceCounter(allVerticesAngleData, distancesToInner, totalRayNumber, "distancesToInner");
939    verifyDistanceCounter(allVerticesAngleData, distancesToOuter, totalRayNumber, "distancesToOuter");
940
941    for (int i = 0; i < totalRayNumber; i++) {
942        if ((distancesToInner[i] * distancesToOuter[i]) != 0) {
943            ALOGE("distancesToInner wrong at index %d distancesToInner[i] %d,"
944                    " distancesToOuter[i] %d", i, distancesToInner[i], distancesToOuter[i]);
945        }
946    }
947    int currentUmbraVertexIndex =
948            umbraAngleList[maxUmbraAngleIndex].mVertexIndex;
949    int currentPenumbraVertexIndex =
950            penumbraAngleList[maxPenumbraAngleIndex].mVertexIndex;
951    for (int i = 0; i < totalRayNumber; i++) {
952        if (allVerticesAngleData[i].mIsPenumbra == true) {
953            if (allVerticesAngleData[i].mVertexIndex != currentPenumbraVertexIndex) {
954                ALOGW("wrong penumbra indexing i %d allVerticesAngleData[i].mVertexIndex %d "
955                        "currentpenumbraVertexIndex %d", i,
956                        allVerticesAngleData[i].mVertexIndex, currentPenumbraVertexIndex);
957            }
958            currentPenumbraVertexIndex = (currentPenumbraVertexIndex + 1) % penumbraLength;
959        } else {
960            if (allVerticesAngleData[i].mVertexIndex != currentUmbraVertexIndex) {
961                ALOGW("wrong umbra indexing i %d allVerticesAngleData[i].mVertexIndex %d "
962                        "currentUmbraVertexIndex %d", i,
963                        allVerticesAngleData[i].mVertexIndex, currentUmbraVertexIndex);
964            }
965            currentUmbraVertexIndex = (currentUmbraVertexIndex + 1) % umbraLength;
966        }
967    }
968    for (int i = 0; i < totalRayNumber - 1; i++) {
969        float currentAngle = allVerticesAngleData[i].mAngle;
970        float nextAngle = allVerticesAngleData[(i + 1) % totalRayNumber].mAngle;
971        if (currentAngle < nextAngle) {
972            ALOGE("Unexpected angle values!, currentAngle nextAngle %f %f", currentAngle, nextAngle);
973        }
974    }
975}
976#endif
977
978/**
979 * In order to compute the occluded umbra, we need to setup the angle data list
980 * for the polygon data. Since we only store one poly vertex per polygon vertex,
981 * this array only needs to be a float array which are the angles for each vertex.
982 *
983 * @param polyAngleList The result list
984 *
985 * @return int The index for the maximum angle in this array.
986 */
987int SpotShadow::setupPolyAngleList(float* polyAngleList, int polyAngleLength,
988        const Vector2* poly2d, const Vector2& centroid) {
989    int maxPolyAngleIndex = -1;
990    float maxPolyAngle = -FLT_MAX;
991    for (int i = 0; i < polyAngleLength; i++) {
992        polyAngleList[i] = angle(poly2d[i], centroid);
993        if (polyAngleList[i] > maxPolyAngle) {
994            maxPolyAngle = polyAngleList[i];
995            maxPolyAngleIndex = i;
996        }
997    }
998    return maxPolyAngleIndex;
999}
1000
1001/**
1002 * For umbra and penumbra, given the offset info and the current ray number,
1003 * find the right edge index (the (starting vertex) for the ray to shoot at.
1004 *
1005 * @return int The index of the starting vertex of the edge.
1006 */
1007inline int SpotShadow::getEdgeStartIndex(const int* offsets, int rayIndex, int totalRayNumber,
1008        const VertexAngleData* allVerticesAngleData) {
1009    int tempOffset = offsets[rayIndex];
1010    int targetRayIndex = (rayIndex - tempOffset + totalRayNumber) % totalRayNumber;
1011    return allVerticesAngleData[targetRayIndex].mVertexIndex;
1012}
1013
1014/**
1015 * For the occluded umbra, given the array of angles, find the index of the
1016 * starting vertex of the edge, for the ray to shoo at.
1017 *
1018 * TODO: Save the last result to shorten the search distance.
1019 *
1020 * @return int The index of the starting vertex of the edge.
1021 */
1022inline int SpotShadow::getPolyEdgeStartIndex(int maxPolyAngleIndex, int polyLength,
1023        const float* polyAngleList, float rayAngle) {
1024    int minPolyAngleIndex  = (maxPolyAngleIndex + polyLength - 1) % polyLength;
1025    int resultIndex = -1;
1026    if (rayAngle > polyAngleList[maxPolyAngleIndex]
1027        || rayAngle <= polyAngleList[minPolyAngleIndex]) {
1028        resultIndex = minPolyAngleIndex;
1029    } else {
1030        for (int i = 0; i < polyLength - 1; i++) {
1031            int currentIndex = (maxPolyAngleIndex + i) % polyLength;
1032            int nextIndex = (maxPolyAngleIndex + i + 1) % polyLength;
1033            if (rayAngle <= polyAngleList[currentIndex]
1034                && rayAngle > polyAngleList[nextIndex]) {
1035                resultIndex = currentIndex;
1036            }
1037        }
1038    }
1039    if (CC_UNLIKELY(resultIndex == -1)) {
1040        // TODO: Add more error handling here.
1041        ALOGE("Wrong index found, means no edge can't be found for rayAngle %f", rayAngle);
1042    }
1043    return resultIndex;
1044}
1045
1046/**
1047 * Convert the incoming polygons into arrays of vertices, for each ray.
1048 * Ray only shoots when there is one vertex either on penumbra on umbra.
1049 *
1050 * Finally, it will generate vertices per ray for umbra, penumbra and optionally
1051 * occludedUmbra.
1052 *
1053 * Return true (success) when all vertices are generated
1054 */
1055int SpotShadow::convertPolysToVerticesPerRay(
1056        bool hasOccludedUmbraArea, const Vector2* poly2d, int polyLength,
1057        const Vector2* umbra, int umbraLength, const Vector2* penumbra,
1058        int penumbraLength, const Vector2& centroid,
1059        Vector2* umbraVerticesPerRay, Vector2* penumbraVerticesPerRay,
1060        Vector2* occludedUmbraVerticesPerRay) {
1061    int totalRayNumber = umbraLength + penumbraLength;
1062
1063    // For incoming umbra / penumbra polygons, we will build an intermediate data
1064    // structure to help us sort all the vertices according to the vertices.
1065    // Using this data structure, we can tell where (the angle) to shoot the ray,
1066    // whether we shoot at penumbra edge or umbra edge, and which edge to shoot at.
1067    //
1068    // We first parse each vertices and generate a table of VertexAngleData.
1069    // Based on that, we create 2 arrays telling us which edge to shoot at.
1070    VertexAngleData allVerticesAngleData[totalRayNumber];
1071    VertexAngleData umbraAngleList[umbraLength];
1072    VertexAngleData penumbraAngleList[penumbraLength];
1073
1074    int polyAngleLength = hasOccludedUmbraArea ? polyLength : 0;
1075    float polyAngleList[polyAngleLength];
1076
1077    const int maxUmbraAngleIndex =
1078            setupAngleList(umbraAngleList, umbraLength, umbra, centroid, false, "umbra");
1079    const int maxPenumbraAngleIndex =
1080            setupAngleList(penumbraAngleList, penumbraLength, penumbra, centroid, true, "penumbra");
1081    const int maxPolyAngleIndex = setupPolyAngleList(polyAngleList, polyAngleLength, poly2d, centroid);
1082
1083    // Check all the polygons here are CW.
1084    bool isPolyCW = checkPolyClockwise(polyAngleLength, maxPolyAngleIndex, polyAngleList);
1085    bool isUmbraCW = checkClockwise(maxUmbraAngleIndex, umbraLength,
1086            umbraAngleList, "umbra");
1087    bool isPenumbraCW = checkClockwise(maxPenumbraAngleIndex, penumbraLength,
1088            penumbraAngleList, "penumbra");
1089
1090    if (!isUmbraCW || !isPenumbraCW || !isPolyCW) {
1091#if DEBUG_SHADOW
1092        ALOGE("One polygon is not CW isUmbraCW %d isPenumbraCW %d isPolyCW %d",
1093                isUmbraCW, isPenumbraCW, isPolyCW);
1094#endif
1095        return false;
1096    }
1097
1098    mergeAngleList(maxUmbraAngleIndex, maxPenumbraAngleIndex,
1099            umbraAngleList, umbraLength, penumbraAngleList, penumbraLength,
1100            allVerticesAngleData);
1101
1102    // Calculate the offset to the left most Inner vertex for each outerVertex.
1103    // Then the offset to the left most Outer vertex for each innerVertex.
1104    int offsetToInner[totalRayNumber];
1105    int offsetToOuter[totalRayNumber];
1106    calculateDistanceCounter(true, totalRayNumber, allVerticesAngleData, offsetToInner);
1107    calculateDistanceCounter(false, totalRayNumber, allVerticesAngleData, offsetToOuter);
1108
1109    // Generate both umbraVerticesPerRay and penumbraVerticesPerRay
1110    for (int i = 0; i < totalRayNumber; i++) {
1111        float rayAngle = allVerticesAngleData[i].mAngle;
1112        bool isUmbraVertex = !allVerticesAngleData[i].mIsPenumbra;
1113
1114        float dx = cosf(rayAngle);
1115        float dy = sinf(rayAngle);
1116        float distanceToIntersectUmbra = -1;
1117
1118        if (isUmbraVertex) {
1119            // We can just copy umbra easily, and calculate the distance for the
1120            // occluded umbra computation.
1121            int startUmbraIndex = allVerticesAngleData[i].mVertexIndex;
1122            umbraVerticesPerRay[i] = umbra[startUmbraIndex];
1123            if (hasOccludedUmbraArea) {
1124                distanceToIntersectUmbra = (umbraVerticesPerRay[i] - centroid).length();
1125            }
1126
1127            //shoot ray to penumbra only
1128            int startPenumbraIndex = getEdgeStartIndex(offsetToOuter, i, totalRayNumber,
1129                    allVerticesAngleData);
1130            float distanceToIntersectPenumbra = rayIntersectPoints(centroid, dx, dy,
1131                    penumbra[startPenumbraIndex],
1132                    penumbra[(startPenumbraIndex + 1) % penumbraLength]);
1133            if (distanceToIntersectPenumbra < 0) {
1134#if DEBUG_SHADOW
1135                ALOGW("convertPolyToRayDist for penumbra failed rayAngle %f dx %f dy %f",
1136                        rayAngle, dx, dy);
1137#endif
1138                distanceToIntersectPenumbra = 0;
1139            }
1140            penumbraVerticesPerRay[i].x = centroid.x + dx * distanceToIntersectPenumbra;
1141            penumbraVerticesPerRay[i].y = centroid.y + dy * distanceToIntersectPenumbra;
1142        } else {
1143            // We can just copy the penumbra
1144            int startPenumbraIndex = allVerticesAngleData[i].mVertexIndex;
1145            penumbraVerticesPerRay[i] = penumbra[startPenumbraIndex];
1146
1147            // And shoot ray to umbra only
1148            int startUmbraIndex = getEdgeStartIndex(offsetToInner, i, totalRayNumber,
1149                    allVerticesAngleData);
1150
1151            distanceToIntersectUmbra = rayIntersectPoints(centroid, dx, dy,
1152                    umbra[startUmbraIndex], umbra[(startUmbraIndex + 1) % umbraLength]);
1153            if (distanceToIntersectUmbra < 0) {
1154#if DEBUG_SHADOW
1155                ALOGW("convertPolyToRayDist for umbra failed rayAngle %f dx %f dy %f",
1156                        rayAngle, dx, dy);
1157#endif
1158                distanceToIntersectUmbra = 0;
1159            }
1160            umbraVerticesPerRay[i].x = centroid.x + dx * distanceToIntersectUmbra;
1161            umbraVerticesPerRay[i].y = centroid.y + dy * distanceToIntersectUmbra;
1162        }
1163
1164        if (hasOccludedUmbraArea) {
1165            // Shoot the same ray to the poly2d, and get the distance.
1166            int startPolyIndex = getPolyEdgeStartIndex(maxPolyAngleIndex, polyLength,
1167                    polyAngleList, rayAngle);
1168
1169            float distanceToIntersectPoly = rayIntersectPoints(centroid, dx, dy,
1170                    poly2d[startPolyIndex], poly2d[(startPolyIndex + 1) % polyLength]);
1171            if (distanceToIntersectPoly < 0) {
1172                distanceToIntersectPoly = 0;
1173            }
1174            distanceToIntersectPoly = MathUtils::min(distanceToIntersectUmbra, distanceToIntersectPoly);
1175            occludedUmbraVerticesPerRay[i].x = centroid.x + dx * distanceToIntersectPoly;
1176            occludedUmbraVerticesPerRay[i].y = centroid.y + dy * distanceToIntersectPoly;
1177        }
1178    }
1179
1180#if DEBUG_SHADOW
1181    verifyAngleData(totalRayNumber, allVerticesAngleData, offsetToInner,
1182            offsetToOuter,  umbraAngleList, maxUmbraAngleIndex,  umbraLength,
1183            penumbraAngleList,  maxPenumbraAngleIndex, penumbraLength);
1184#endif
1185    return true; // success
1186
1187}
1188
1189/**
1190 * Generate a triangle strip given two convex polygon
1191**/
1192void SpotShadow::generateTriangleStrip(bool isCasterOpaque, float shadowStrengthScale,
1193        Vector2* penumbra, int penumbraLength, Vector2* umbra, int umbraLength,
1194        const Vector3* poly, int polyLength, VertexBuffer& shadowTriangleStrip,
1195        const Vector2& centroid) {
1196
1197    bool hasOccludedUmbraArea = false;
1198    Vector2 poly2d[polyLength];
1199
1200    if (isCasterOpaque) {
1201        for (int i = 0; i < polyLength; i++) {
1202            poly2d[i].x = poly[i].x;
1203            poly2d[i].y = poly[i].y;
1204        }
1205        // Make sure the centroid is inside the umbra, otherwise, fall back to the
1206        // approach as if there is no occluded umbra area.
1207        if (testPointInsidePolygon(centroid, poly2d, polyLength)) {
1208            hasOccludedUmbraArea = true;
1209        }
1210    }
1211
1212    int totalRayNum = umbraLength + penumbraLength;
1213    Vector2 umbraVertices[totalRayNum];
1214    Vector2 penumbraVertices[totalRayNum];
1215    Vector2 occludedUmbraVertices[totalRayNum];
1216    bool convertSuccess = convertPolysToVerticesPerRay(hasOccludedUmbraArea, poly2d,
1217            polyLength, umbra, umbraLength, penumbra, penumbraLength,
1218            centroid, umbraVertices, penumbraVertices, occludedUmbraVertices);
1219    if (!convertSuccess) {
1220        return;
1221    }
1222
1223    // Minimal value is 1, for each vertex show up once.
1224    // The bigger this value is , the smoother the look is, but more memory
1225    // is consumed.
1226    // When the ray number is high, that means the polygon has been fine
1227    // tessellated, we don't need this extra slice, just keep it as 1.
1228    int sliceNumberPerEdge = (totalRayNum > FINE_TESSELLATED_POLYGON_RAY_NUMBER) ? 1 : 2;
1229
1230    // For each polygon, we at most add (totalRayNum * sliceNumberPerEdge) vertices.
1231    int slicedVertexCountPerPolygon = totalRayNum * sliceNumberPerEdge;
1232    int totalVertexCount = slicedVertexCountPerPolygon * 2 + totalRayNum;
1233    int totalIndexCount = 2 * (slicedVertexCountPerPolygon * 2 + 2);
1234    AlphaVertex* shadowVertices =
1235            shadowTriangleStrip.alloc<AlphaVertex>(totalVertexCount);
1236    uint16_t* indexBuffer =
1237            shadowTriangleStrip.allocIndices<uint16_t>(totalIndexCount);
1238
1239    int indexBufferIndex = 0;
1240    int vertexBufferIndex = 0;
1241
1242    uint16_t slicedUmbraVertexIndex[totalRayNum * sliceNumberPerEdge];
1243    // Should be something like 0 0 0  1 1 1 2 3 3 3...
1244    int rayNumberPerSlicedUmbra[totalRayNum * sliceNumberPerEdge];
1245    int realUmbraVertexCount = 0;
1246    for (int i = 0; i < totalRayNum; i++) {
1247        Vector2 currentPenumbra = penumbraVertices[i];
1248        Vector2 currentUmbra = umbraVertices[i];
1249
1250        Vector2 nextPenumbra = penumbraVertices[(i + 1) % totalRayNum];
1251        Vector2 nextUmbra = umbraVertices[(i + 1) % totalRayNum];
1252        // NextUmbra/Penumbra will be done in the next loop!!
1253        for (int weight = 0; weight < sliceNumberPerEdge; weight++) {
1254            const Vector2& slicedPenumbra = (currentPenumbra * (sliceNumberPerEdge - weight)
1255                + nextPenumbra * weight) / sliceNumberPerEdge;
1256
1257            const Vector2& slicedUmbra = (currentUmbra * (sliceNumberPerEdge - weight)
1258                + nextUmbra * weight) / sliceNumberPerEdge;
1259
1260            // In the vertex buffer, we fill the Penumbra first, then umbra.
1261            indexBuffer[indexBufferIndex++] = vertexBufferIndex;
1262            AlphaVertex::set(&shadowVertices[vertexBufferIndex++], slicedPenumbra.x,
1263                    slicedPenumbra.y, 0.0f);
1264
1265            // When we add umbra vertex, we need to remember its current ray number.
1266            // And its own vertexBufferIndex. This is for occluded umbra usage.
1267            indexBuffer[indexBufferIndex++] = vertexBufferIndex;
1268            rayNumberPerSlicedUmbra[realUmbraVertexCount] = i;
1269            slicedUmbraVertexIndex[realUmbraVertexCount] = vertexBufferIndex;
1270            realUmbraVertexCount++;
1271            AlphaVertex::set(&shadowVertices[vertexBufferIndex++], slicedUmbra.x,
1272                    slicedUmbra.y, M_PI);
1273        }
1274    }
1275
1276    indexBuffer[indexBufferIndex++] = 0;
1277    //RealUmbraVertexIndex[0] must be 1, so we connect back well at the
1278    //beginning of occluded area.
1279    indexBuffer[indexBufferIndex++] = 1;
1280
1281    float occludedUmbraAlpha = M_PI;
1282    if (hasOccludedUmbraArea) {
1283        // Now the occludedUmbra area;
1284        int currentRayNumber = -1;
1285        int firstOccludedUmbraIndex = -1;
1286        for (int i = 0; i < realUmbraVertexCount; i++) {
1287            indexBuffer[indexBufferIndex++] = slicedUmbraVertexIndex[i];
1288
1289            // If the occludedUmbra vertex has not been added yet, then add it.
1290            // Otherwise, just use the previously added occludedUmbra vertices.
1291            if (rayNumberPerSlicedUmbra[i] != currentRayNumber) {
1292                currentRayNumber++;
1293                indexBuffer[indexBufferIndex++] = vertexBufferIndex;
1294                // We need to remember the begining of the occludedUmbra vertices
1295                // to close this loop.
1296                if (currentRayNumber == 0) {
1297                    firstOccludedUmbraIndex = vertexBufferIndex;
1298                }
1299                AlphaVertex::set(&shadowVertices[vertexBufferIndex++],
1300                        occludedUmbraVertices[currentRayNumber].x,
1301                        occludedUmbraVertices[currentRayNumber].y,
1302                        occludedUmbraAlpha);
1303            } else {
1304                indexBuffer[indexBufferIndex++] = (vertexBufferIndex - 1);
1305            }
1306        }
1307        // Close the loop here!
1308        indexBuffer[indexBufferIndex++] = slicedUmbraVertexIndex[0];
1309        indexBuffer[indexBufferIndex++] = firstOccludedUmbraIndex;
1310    } else {
1311        int lastCentroidIndex = vertexBufferIndex;
1312        AlphaVertex::set(&shadowVertices[vertexBufferIndex++], centroid.x,
1313                centroid.y, occludedUmbraAlpha);
1314        for (int i = 0; i < realUmbraVertexCount; i++) {
1315            indexBuffer[indexBufferIndex++] = slicedUmbraVertexIndex[i];
1316            indexBuffer[indexBufferIndex++] = lastCentroidIndex;
1317        }
1318        // Close the loop here!
1319        indexBuffer[indexBufferIndex++] = slicedUmbraVertexIndex[0];
1320        indexBuffer[indexBufferIndex++] = lastCentroidIndex;
1321    }
1322
1323#if DEBUG_SHADOW
1324    ALOGD("allocated IB %d allocated VB is %d", totalIndexCount, totalVertexCount);
1325    ALOGD("IB index %d VB index is %d", indexBufferIndex, vertexBufferIndex);
1326    for (int i = 0; i < vertexBufferIndex; i++) {
1327        ALOGD("vertexBuffer i %d, (%f, %f %f)", i, shadowVertices[i].x, shadowVertices[i].y,
1328                shadowVertices[i].alpha);
1329    }
1330    for (int i = 0; i < indexBufferIndex; i++) {
1331        ALOGD("indexBuffer i %d, indexBuffer[i] %d", i, indexBuffer[i]);
1332    }
1333#endif
1334
1335    // At the end, update the real index and vertex buffer size.
1336    shadowTriangleStrip.updateVertexCount(vertexBufferIndex);
1337    shadowTriangleStrip.updateIndexCount(indexBufferIndex);
1338    ShadowTessellator::checkOverflow(vertexBufferIndex, totalVertexCount, "Spot Vertex Buffer");
1339    ShadowTessellator::checkOverflow(indexBufferIndex, totalIndexCount, "Spot Index Buffer");
1340
1341    shadowTriangleStrip.setMode(VertexBuffer::kIndices);
1342    shadowTriangleStrip.computeBounds<AlphaVertex>();
1343}
1344
1345#if DEBUG_SHADOW
1346
1347#define TEST_POINT_NUMBER 128
1348/**
1349 * Calculate the bounds for generating random test points.
1350 */
1351void SpotShadow::updateBound(const Vector2 inVector, Vector2& lowerBound,
1352        Vector2& upperBound) {
1353    if (inVector.x < lowerBound.x) {
1354        lowerBound.x = inVector.x;
1355    }
1356
1357    if (inVector.y < lowerBound.y) {
1358        lowerBound.y = inVector.y;
1359    }
1360
1361    if (inVector.x > upperBound.x) {
1362        upperBound.x = inVector.x;
1363    }
1364
1365    if (inVector.y > upperBound.y) {
1366        upperBound.y = inVector.y;
1367    }
1368}
1369
1370/**
1371 * For debug purpose, when things go wrong, dump the whole polygon data.
1372 */
1373void SpotShadow::dumpPolygon(const Vector2* poly, int polyLength, const char* polyName) {
1374    for (int i = 0; i < polyLength; i++) {
1375        ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
1376    }
1377}
1378
1379/**
1380 * For debug purpose, when things go wrong, dump the whole polygon data.
1381 */
1382void SpotShadow::dumpPolygon(const Vector3* poly, int polyLength, const char* polyName) {
1383    for (int i = 0; i < polyLength; i++) {
1384        ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
1385    }
1386}
1387
1388/**
1389 * Test whether the polygon is convex.
1390 */
1391bool SpotShadow::testConvex(const Vector2* polygon, int polygonLength,
1392        const char* name) {
1393    bool isConvex = true;
1394    for (int i = 0; i < polygonLength; i++) {
1395        Vector2 start = polygon[i];
1396        Vector2 middle = polygon[(i + 1) % polygonLength];
1397        Vector2 end = polygon[(i + 2) % polygonLength];
1398
1399        float delta = (float(middle.x) - start.x) * (float(end.y) - start.y) -
1400                (float(middle.y) - start.y) * (float(end.x) - start.x);
1401        bool isCCWOrCoLinear = (delta >= EPSILON);
1402
1403        if (isCCWOrCoLinear) {
1404            ALOGW("(Error Type 2): polygon (%s) is not a convex b/c start (x %f, y %f),"
1405                    "middle (x %f, y %f) and end (x %f, y %f) , delta is %f !!!",
1406                    name, start.x, start.y, middle.x, middle.y, end.x, end.y, delta);
1407            isConvex = false;
1408            break;
1409        }
1410    }
1411    return isConvex;
1412}
1413
1414/**
1415 * Test whether or not the polygon (intersection) is within the 2 input polygons.
1416 * Using Marte Carlo method, we generate a random point, and if it is inside the
1417 * intersection, then it must be inside both source polygons.
1418 */
1419void SpotShadow::testIntersection(const Vector2* poly1, int poly1Length,
1420        const Vector2* poly2, int poly2Length,
1421        const Vector2* intersection, int intersectionLength) {
1422    // Find the min and max of x and y.
1423    Vector2 lowerBound = {FLT_MAX, FLT_MAX};
1424    Vector2 upperBound = {-FLT_MAX, -FLT_MAX};
1425    for (int i = 0; i < poly1Length; i++) {
1426        updateBound(poly1[i], lowerBound, upperBound);
1427    }
1428    for (int i = 0; i < poly2Length; i++) {
1429        updateBound(poly2[i], lowerBound, upperBound);
1430    }
1431
1432    bool dumpPoly = false;
1433    for (int k = 0; k < TEST_POINT_NUMBER; k++) {
1434        // Generate a random point between minX, minY and maxX, maxY.
1435        float randomX = rand() / float(RAND_MAX);
1436        float randomY = rand() / float(RAND_MAX);
1437
1438        Vector2 testPoint;
1439        testPoint.x = lowerBound.x + randomX * (upperBound.x - lowerBound.x);
1440        testPoint.y = lowerBound.y + randomY * (upperBound.y - lowerBound.y);
1441
1442        // If the random point is in both poly 1 and 2, then it must be intersection.
1443        if (testPointInsidePolygon(testPoint, intersection, intersectionLength)) {
1444            if (!testPointInsidePolygon(testPoint, poly1, poly1Length)) {
1445                dumpPoly = true;
1446                ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
1447                        " not in the poly1",
1448                        testPoint.x, testPoint.y);
1449            }
1450
1451            if (!testPointInsidePolygon(testPoint, poly2, poly2Length)) {
1452                dumpPoly = true;
1453                ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
1454                        " not in the poly2",
1455                        testPoint.x, testPoint.y);
1456            }
1457        }
1458    }
1459
1460    if (dumpPoly) {
1461        dumpPolygon(intersection, intersectionLength, "intersection");
1462        for (int i = 1; i < intersectionLength; i++) {
1463            Vector2 delta = intersection[i] - intersection[i - 1];
1464            ALOGD("Intersetion i, %d Vs i-1 is delta %f", i, delta.lengthSquared());
1465        }
1466
1467        dumpPolygon(poly1, poly1Length, "poly 1");
1468        dumpPolygon(poly2, poly2Length, "poly 2");
1469    }
1470}
1471#endif
1472
1473}; // namespace uirenderer
1474}; // namespace android
1475