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