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