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