SpotShadow.cpp revision c50a03d78aaedd0003377e98710e7038bda330e9
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#define CASTER_Z_CAP_RATIO 0.95f
21#define FAKE_UMBRA_SIZE_RATIO 0.01f
22#define OCLLUDED_UMBRA_SHRINK_FACTOR 0.95f
23
24#include <math.h>
25#include <stdlib.h>
26#include <utils/Log.h>
27
28#include "ShadowTessellator.h"
29#include "SpotShadow.h"
30#include "Vertex.h"
31#include "utils/MathUtils.h"
32
33// TODO: After we settle down the new algorithm, we can remove the old one and
34// its utility functions.
35// Right now, we still need to keep it for comparison purpose and future expansion.
36namespace android {
37namespace uirenderer {
38
39static const double EPSILON = 1e-7;
40
41/**
42 * For each polygon's vertex, the light center will project it to the receiver
43 * as one of the outline vertex.
44 * For each outline vertex, we need to store the position and normal.
45 * Normal here is defined against the edge by the current vertex and the next vertex.
46 */
47struct OutlineData {
48    Vector2 position;
49    Vector2 normal;
50    float radius;
51};
52
53/**
54 * Calculate the angle between and x and a y coordinate.
55 * The atan2 range from -PI to PI.
56 */
57static float angle(const Vector2& point, const Vector2& center) {
58    return atan2(point.y - center.y, point.x - center.x);
59}
60
61/**
62 * Calculate the intersection of a ray with the line segment defined by two points.
63 *
64 * Returns a negative value in error conditions.
65
66 * @param rayOrigin The start of the ray
67 * @param dx The x vector of the ray
68 * @param dy The y vector of the ray
69 * @param p1 The first point defining the line segment
70 * @param p2 The second point defining the line segment
71 * @return The distance along the ray if it intersects with the line segment, negative if otherwise
72 */
73static float rayIntersectPoints(const Vector2& rayOrigin, float dx, float dy,
74        const Vector2& p1, const Vector2& p2) {
75    // The math below is derived from solving this formula, basically the
76    // intersection point should stay on both the ray and the edge of (p1, p2).
77    // solve([p1x+t*(p2x-p1x)=dx*t2+px,p1y+t*(p2y-p1y)=dy*t2+py],[t,t2]);
78
79    double divisor = (dx * (p1.y - p2.y) + dy * p2.x - dy * p1.x);
80    if (divisor == 0) return -1.0f; // error, invalid divisor
81
82#if DEBUG_SHADOW
83    double interpVal = (dx * (p1.y - rayOrigin.y) + dy * rayOrigin.x - dy * p1.x) / divisor;
84    if (interpVal < 0 || interpVal > 1) {
85        ALOGW("rayIntersectPoints is hitting outside the segment %f", interpVal);
86    }
87#endif
88
89    double distance = (p1.x * (rayOrigin.y - p2.y) + p2.x * (p1.y - rayOrigin.y) +
90            rayOrigin.x * (p2.y - p1.y)) / divisor;
91
92    return distance; // may be negative in error cases
93}
94
95/**
96 * Sort points by their X coordinates
97 *
98 * @param points the points as a Vector2 array.
99 * @param pointsLength the number of vertices of the polygon.
100 */
101void SpotShadow::xsort(Vector2* points, int pointsLength) {
102    quicksortX(points, 0, pointsLength - 1);
103}
104
105/**
106 * compute the convex hull of a collection of Points
107 *
108 * @param points the points as a Vector2 array.
109 * @param pointsLength the number of vertices of the polygon.
110 * @param retPoly pre allocated array of floats to put the vertices
111 * @return the number of points in the polygon 0 if no intersection
112 */
113int SpotShadow::hull(Vector2* points, int pointsLength, Vector2* retPoly) {
114    xsort(points, pointsLength);
115    int n = pointsLength;
116    Vector2 lUpper[n];
117    lUpper[0] = points[0];
118    lUpper[1] = points[1];
119
120    int lUpperSize = 2;
121
122    for (int i = 2; i < n; i++) {
123        lUpper[lUpperSize] = points[i];
124        lUpperSize++;
125
126        while (lUpperSize > 2 && !ccw(
127                lUpper[lUpperSize - 3].x, lUpper[lUpperSize - 3].y,
128                lUpper[lUpperSize - 2].x, lUpper[lUpperSize - 2].y,
129                lUpper[lUpperSize - 1].x, lUpper[lUpperSize - 1].y)) {
130            // Remove the middle point of the three last
131            lUpper[lUpperSize - 2].x = lUpper[lUpperSize - 1].x;
132            lUpper[lUpperSize - 2].y = lUpper[lUpperSize - 1].y;
133            lUpperSize--;
134        }
135    }
136
137    Vector2 lLower[n];
138    lLower[0] = points[n - 1];
139    lLower[1] = points[n - 2];
140
141    int lLowerSize = 2;
142
143    for (int i = n - 3; i >= 0; i--) {
144        lLower[lLowerSize] = points[i];
145        lLowerSize++;
146
147        while (lLowerSize > 2 && !ccw(
148                lLower[lLowerSize - 3].x, lLower[lLowerSize - 3].y,
149                lLower[lLowerSize - 2].x, lLower[lLowerSize - 2].y,
150                lLower[lLowerSize - 1].x, lLower[lLowerSize - 1].y)) {
151            // Remove the middle point of the three last
152            lLower[lLowerSize - 2] = lLower[lLowerSize - 1];
153            lLowerSize--;
154        }
155    }
156
157    // output points in CW ordering
158    const int total = lUpperSize + lLowerSize - 2;
159    int outIndex = total - 1;
160    for (int i = 0; i < lUpperSize; i++) {
161        retPoly[outIndex] = lUpper[i];
162        outIndex--;
163    }
164
165    for (int i = 1; i < lLowerSize - 1; i++) {
166        retPoly[outIndex] = lLower[i];
167        outIndex--;
168    }
169    // TODO: Add test harness which verify that all the points are inside the hull.
170    return total;
171}
172
173/**
174 * Test whether the 3 points form a counter clockwise turn.
175 *
176 * @return true if a right hand turn
177 */
178bool SpotShadow::ccw(double ax, double ay, double bx, double by,
179        double cx, double cy) {
180    return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > EPSILON;
181}
182
183/**
184 * Calculates the intersection of poly1 with poly2 and put in poly2.
185 * Note that both poly1 and poly2 must be in CW order already!
186 *
187 * @param poly1 The 1st polygon, as a Vector2 array.
188 * @param poly1Length The number of vertices of 1st polygon.
189 * @param poly2 The 2nd and output polygon, as a Vector2 array.
190 * @param poly2Length The number of vertices of 2nd polygon.
191 * @return number of vertices in output polygon as poly2.
192 */
193int SpotShadow::intersection(const Vector2* poly1, int poly1Length,
194        Vector2* poly2, int poly2Length) {
195#if DEBUG_SHADOW
196    if (!ShadowTessellator::isClockwise(poly1, poly1Length)) {
197        ALOGW("Poly1 is not clockwise! Intersection is wrong!");
198    }
199    if (!ShadowTessellator::isClockwise(poly2, poly2Length)) {
200        ALOGW("Poly2 is not clockwise! Intersection is wrong!");
201    }
202#endif
203    Vector2 poly[poly1Length * poly2Length + 2];
204    int count = 0;
205    int pcount = 0;
206
207    // If one vertex from one polygon sits inside another polygon, add it and
208    // count them.
209    for (int i = 0; i < poly1Length; i++) {
210        if (testPointInsidePolygon(poly1[i], poly2, poly2Length)) {
211            poly[count] = poly1[i];
212            count++;
213            pcount++;
214
215        }
216    }
217
218    int insidePoly2 = pcount;
219    for (int i = 0; i < poly2Length; i++) {
220        if (testPointInsidePolygon(poly2[i], poly1, poly1Length)) {
221            poly[count] = poly2[i];
222            count++;
223        }
224    }
225
226    int insidePoly1 = count - insidePoly2;
227    // If all vertices from poly1 are inside poly2, then just return poly1.
228    if (insidePoly2 == poly1Length) {
229        memcpy(poly2, poly1, poly1Length * sizeof(Vector2));
230        return poly1Length;
231    }
232
233    // If all vertices from poly2 are inside poly1, then just return poly2.
234    if (insidePoly1 == poly2Length) {
235        return poly2Length;
236    }
237
238    // Since neither polygon fully contain the other one, we need to add all the
239    // intersection points.
240    Vector2 intersection = {0, 0};
241    for (int i = 0; i < poly2Length; i++) {
242        for (int j = 0; j < poly1Length; j++) {
243            int poly2LineStart = i;
244            int poly2LineEnd = ((i + 1) % poly2Length);
245            int poly1LineStart = j;
246            int poly1LineEnd = ((j + 1) % poly1Length);
247            bool found = lineIntersection(
248                    poly2[poly2LineStart].x, poly2[poly2LineStart].y,
249                    poly2[poly2LineEnd].x, poly2[poly2LineEnd].y,
250                    poly1[poly1LineStart].x, poly1[poly1LineStart].y,
251                    poly1[poly1LineEnd].x, poly1[poly1LineEnd].y,
252                    intersection);
253            if (found) {
254                poly[count].x = intersection.x;
255                poly[count].y = intersection.y;
256                count++;
257            } else {
258                Vector2 delta = poly2[i] - poly1[j];
259                if (delta.lengthSquared() < EPSILON) {
260                    poly[count] = poly2[i];
261                    count++;
262                }
263            }
264        }
265    }
266
267    if (count == 0) {
268        return 0;
269    }
270
271    // Sort the result polygon around the center.
272    Vector2 center = {0.0f, 0.0f};
273    for (int i = 0; i < count; i++) {
274        center += poly[i];
275    }
276    center /= count;
277    sort(poly, count, center);
278
279#if DEBUG_SHADOW
280    // Since poly2 is overwritten as the result, we need to save a copy to do
281    // our verification.
282    Vector2 oldPoly2[poly2Length];
283    int oldPoly2Length = poly2Length;
284    memcpy(oldPoly2, poly2, sizeof(Vector2) * poly2Length);
285#endif
286
287    // Filter the result out from poly and put it into poly2.
288    poly2[0] = poly[0];
289    int lastOutputIndex = 0;
290    for (int i = 1; i < count; i++) {
291        Vector2 delta = poly[i] - poly2[lastOutputIndex];
292        if (delta.lengthSquared() >= EPSILON) {
293            poly2[++lastOutputIndex] = poly[i];
294        } else {
295            // If the vertices are too close, pick the inner one, because the
296            // inner one is more likely to be an intersection point.
297            Vector2 delta1 = poly[i] - center;
298            Vector2 delta2 = poly2[lastOutputIndex] - center;
299            if (delta1.lengthSquared() < delta2.lengthSquared()) {
300                poly2[lastOutputIndex] = poly[i];
301            }
302        }
303    }
304    int resultLength = lastOutputIndex + 1;
305
306#if DEBUG_SHADOW
307    testConvex(poly2, resultLength, "intersection");
308    testConvex(poly1, poly1Length, "input poly1");
309    testConvex(oldPoly2, oldPoly2Length, "input poly2");
310
311    testIntersection(poly1, poly1Length, oldPoly2, oldPoly2Length, poly2, resultLength);
312#endif
313
314    return resultLength;
315}
316
317/**
318 * Sort points about a center point
319 *
320 * @param poly The in and out polyogon as a Vector2 array.
321 * @param polyLength The number of vertices of the polygon.
322 * @param center the center ctr[0] = x , ctr[1] = y to sort around.
323 */
324void SpotShadow::sort(Vector2* poly, int polyLength, const Vector2& center) {
325    quicksortCirc(poly, 0, polyLength - 1, center);
326}
327
328/**
329 * Swap points pointed to by i and j
330 */
331void SpotShadow::swap(Vector2* points, int i, int j) {
332    Vector2 temp = points[i];
333    points[i] = points[j];
334    points[j] = temp;
335}
336
337/**
338 * quick sort implementation about the center.
339 */
340void SpotShadow::quicksortCirc(Vector2* points, int low, int high,
341        const Vector2& center) {
342    int i = low, j = high;
343    int p = low + (high - low) / 2;
344    float pivot = angle(points[p], center);
345    while (i <= j) {
346        while (angle(points[i], center) > pivot) {
347            i++;
348        }
349        while (angle(points[j], center) < pivot) {
350            j--;
351        }
352
353        if (i <= j) {
354            swap(points, i, j);
355            i++;
356            j--;
357        }
358    }
359    if (low < j) quicksortCirc(points, low, j, center);
360    if (i < high) quicksortCirc(points, i, high, center);
361}
362
363/**
364 * Sort points by x axis
365 *
366 * @param points points to sort
367 * @param low start index
368 * @param high end index
369 */
370void SpotShadow::quicksortX(Vector2* points, int low, int high) {
371    int i = low, j = high;
372    int p = low + (high - low) / 2;
373    float pivot = points[p].x;
374    while (i <= j) {
375        while (points[i].x < pivot) {
376            i++;
377        }
378        while (points[j].x > pivot) {
379            j--;
380        }
381
382        if (i <= j) {
383            swap(points, i, j);
384            i++;
385            j--;
386        }
387    }
388    if (low < j) quicksortX(points, low, j);
389    if (i < high) quicksortX(points, i, high);
390}
391
392/**
393 * Test whether a point is inside the polygon.
394 *
395 * @param testPoint the point to test
396 * @param poly the polygon
397 * @return true if the testPoint is inside the poly.
398 */
399bool SpotShadow::testPointInsidePolygon(const Vector2 testPoint,
400        const Vector2* poly, int len) {
401    bool c = false;
402    double testx = testPoint.x;
403    double testy = testPoint.y;
404    for (int i = 0, j = len - 1; i < len; j = i++) {
405        double startX = poly[j].x;
406        double startY = poly[j].y;
407        double endX = poly[i].x;
408        double endY = poly[i].y;
409
410        if (((endY > testy) != (startY > testy)) &&
411            (testx < (startX - endX) * (testy - endY)
412             / (startY - endY) + endX)) {
413            c = !c;
414        }
415    }
416    return c;
417}
418
419/**
420 * Make the polygon turn clockwise.
421 *
422 * @param polygon the polygon as a Vector2 array.
423 * @param len the number of points of the polygon
424 */
425void SpotShadow::makeClockwise(Vector2* polygon, int len) {
426    if (polygon == 0  || len == 0) {
427        return;
428    }
429    if (!ShadowTessellator::isClockwise(polygon, len)) {
430        reverse(polygon, len);
431    }
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*/
522
523void SpotShadow::createSpotShadow_old(bool isCasterOpaque, const Vector3* poly,
524        int polyLength, const Vector3& lightCenter, float lightSize,
525        int lightVertexCount, VertexBuffer& retStrips) {
526    Vector3 light[lightVertexCount * 3];
527    computeLightPolygon(lightVertexCount, lightCenter, lightSize, light);
528    computeSpotShadow_old(isCasterOpaque, light, lightVertexCount, lightCenter, poly,
529            polyLength, retStrips);
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_old(bool isCasterOpaque, const Vector3* lightPoly,
543        int lightPolyLength, const Vector3& lightCenter, const Vector3* poly, int polyLength,
544        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            // After validating the input, deltaZ is guaranteed to be positive.
575            float deltaZ = lightPoly[j].z - poly[i].z;
576            float ratioZ = lightPoly[j].z / deltaZ;
577            float x = lightPoly[j].x - ratioZ * (lightPoly[j].x - poly[i].x);
578            float y = lightPoly[j].y - ratioZ * (lightPoly[j].y - poly[i].y);
579
580            Vector2 newPoint = {x, y};
581            shadowRegion[k] = newPoint;
582            outline[m] = newPoint;
583
584            k++;
585            m++;
586        }
587
588        // For the first light polygon's vertex, use the outline as the umbra.
589        // Later on, use the intersection of the outline and existing umbra.
590        if (umbraLength == 0) {
591            for (int i = 0; i < polyLength; i++) {
592                umbra[i] = outline[i];
593            }
594            umbraLength = polyLength;
595        } else {
596            int col = ((j * 255) / lightPolyLength);
597            umbraLength = intersection(outline, polyLength, umbra, umbraLength);
598            if (umbraLength == 0) {
599                break;
600            }
601        }
602    }
603
604    // Generate the penumbra area using the hull of all shadow regions.
605    int shadowRegionLength = k;
606    Vector2 penumbra[k];
607    int penumbraLength = hull(shadowRegion, shadowRegionLength, penumbra);
608
609    Vector2 fakeUmbra[polyLength];
610    if (umbraLength < 3) {
611        // If there is no real umbra, make a fake one.
612        for (int i = 0; i < polyLength; i++) {
613            float deltaZ = lightCenter.z - poly[i].z;
614            float ratioZ = lightCenter.z / deltaZ;
615            float x = lightCenter.x - ratioZ * (lightCenter.x - poly[i].x);
616            float y = lightCenter.y - ratioZ * (lightCenter.y - poly[i].y);
617
618            fakeUmbra[i].x = x;
619            fakeUmbra[i].y = y;
620        }
621
622        // Shrink the centroid's shadow by 10%.
623        // TODO: Study the magic number of 10%.
624        Vector2 shadowCentroid =
625                ShadowTessellator::centroid2d(fakeUmbra, polyLength);
626        for (int i = 0; i < polyLength; i++) {
627            fakeUmbra[i] = shadowCentroid * (1.0f - SHADOW_SHRINK_SCALE) +
628                    fakeUmbra[i] * SHADOW_SHRINK_SCALE;
629        }
630#if DEBUG_SHADOW
631        ALOGD("No real umbra make a fake one, centroid2d =  %f , %f",
632                shadowCentroid.x, shadowCentroid.y);
633#endif
634        // Set the fake umbra, whose size is the same as the original polygon.
635        umbra = fakeUmbra;
636        umbraLength = polyLength;
637    }
638
639    generateTriangleStrip(isCasterOpaque, 1.0, penumbra, penumbraLength, umbra,
640            umbraLength, poly, polyLength, shadowTriangleStrip);
641}
642
643float SpotShadow::projectCasterToOutline(Vector2& outline,
644        const Vector3& lightCenter, const Vector3& polyVertex) {
645    float lightToPolyZ = lightCenter.z - polyVertex.z;
646    float ratioZ = CASTER_Z_CAP_RATIO;
647    if (lightToPolyZ != 0) {
648        // If any caster's vertex is almost above the light, we just keep it as 95%
649        // of the height of the light.
650        ratioZ = MathUtils::min(polyVertex.z / lightToPolyZ, CASTER_Z_CAP_RATIO);
651    }
652
653    outline.x = polyVertex.x - ratioZ * (lightCenter.x - polyVertex.x);
654    outline.y = polyVertex.y - ratioZ * (lightCenter.y - polyVertex.y);
655    return ratioZ;
656}
657
658/**
659 * Generate the shadow spot light of shape lightPoly and a object poly
660 *
661 * @param isCasterOpaque whether the caster is opaque
662 * @param lightCenter the center of the light
663 * @param lightSize the radius of the light
664 * @param poly x,y,z vertexes of a convex polygon that occludes the light source
665 * @param polyLength number of vertexes of the occluding polygon
666 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
667 *                            empty strip if error.
668 */
669void SpotShadow::createSpotShadow(bool isCasterOpaque, const Vector3& lightCenter,
670        float lightSize, const Vector3* poly, int polyLength, const Vector3& polyCentroid,
671        VertexBuffer& shadowTriangleStrip) {
672    OutlineData outlineData[polyLength];
673    Vector2 outlineCentroid;
674    // Calculate the projected outline for each polygon's vertices from the light center.
675    //
676    //                       O     Light
677    //                      /
678    //                    /
679    //                   .     Polygon vertex
680    //                 /
681    //               /
682    //              O     Outline vertices
683    //
684    // Ratio = (Poly - Outline) / (Light - Poly)
685    // Outline.x = Poly.x - Ratio * (Light.x - Poly.x)
686    // Outline's radius / Light's radius = Ratio
687
688    // Compute the last outline vertex to make sure we can get the normal and outline
689    // in one single loop.
690    projectCasterToOutline(outlineData[polyLength - 1].position, lightCenter,
691            poly[polyLength - 1]);
692
693    // Take the outline's polygon, calculate the normal for each outline edge.
694    int currentNormalIndex = polyLength - 1;
695    int nextNormalIndex = 0;
696
697    for (int i = 0; i < polyLength; i++) {
698        float ratioZ = projectCasterToOutline(outlineData[i].position,
699                lightCenter, poly[i]);
700        outlineData[i].radius = ratioZ * lightSize;
701
702        outlineData[currentNormalIndex].normal = ShadowTessellator::calculateNormal(
703                outlineData[currentNormalIndex].position,
704                outlineData[nextNormalIndex].position);
705        currentNormalIndex = (currentNormalIndex + 1) % polyLength;
706        nextNormalIndex++;
707    }
708
709    projectCasterToOutline(outlineCentroid, lightCenter, polyCentroid);
710
711    int penumbraIndex = 0;
712    int penumbraLength = polyLength * 3;
713    Vector2 penumbra[penumbraLength];
714
715    Vector2 umbra[polyLength];
716    float distOutline = 0;
717    float ratioVI = 0;
718
719    bool hasValidUmbra = true;
720    // We need the maxRatioVI to decrease the spot shadow strength accordingly.
721    float maxRaitoVI = 1.0;
722
723    for (int i = 0; i < polyLength; i++) {
724        // Generate all the penumbra's vertices only using the (outline vertex + normal * radius)
725        // There is no guarantee that the penumbra is still convex, but for
726        // each outline vertex, it will connect to all its corresponding penumbra vertices as
727        // triangle fans. And for neighber penumbra vertex, it will be a trapezoid.
728        //
729        // Penumbra Vertices marked as Pi
730        // Outline Vertices marked as Vi
731        //                                            (P3)
732        //          (P2)                               |     ' (P4)
733        //   (P1)'   |                                 |   '
734        //         ' |                                 | '
735        // (P0)  ------------------------------------------------(P5)
736        //           | (V0)                            |(V1)
737        //           |                                 |
738        //           |                                 |
739        //           |                                 |
740        //           |                                 |
741        //           |                                 |
742        //           |                                 |
743        //           |                                 |
744        //           |                                 |
745        //       (V3)-----------------------------------(V2)
746        int preNormalIndex = (i + polyLength - 1) % polyLength;
747        penumbra[penumbraIndex++] = outlineData[i].position +
748            outlineData[preNormalIndex].normal * outlineData[i].radius;
749
750        int currentNormalIndex = i;
751        // (TODO) Depending on how roundness we want for each corner, we can subdivide
752        // further here and/or introduce some heuristic to decide how much the
753        // subdivision should be.
754        Vector2 avgNormal =
755            (outlineData[preNormalIndex].normal + outlineData[currentNormalIndex].normal) / 2;
756
757        penumbra[penumbraIndex++] = outlineData[i].position +
758            avgNormal * outlineData[i].radius;
759
760        penumbra[penumbraIndex++] = outlineData[i].position +
761            outlineData[currentNormalIndex].normal * outlineData[i].radius;
762
763        // Compute the umbra by the intersection from the outline's centroid!
764        //
765        //       (V) ------------------------------------
766        //           |          '                       |
767        //           |         '                        |
768        //           |       ' (I)                      |
769        //           |    '                             |
770        //           | '             (C)                |
771        //           |                                  |
772        //           |                                  |
773        //           |                                  |
774        //           |                                  |
775        //           ------------------------------------
776        //
777        // Connect a line b/t the outline vertex (V) and the centroid (C), it will
778        // intersect with the outline vertex's circle at point (I).
779        // Now, ratioVI = VI / VC, ratioIC = IC / VC
780        // Then the intersetion point can be computed as Ixy = Vxy * ratioIC + Cxy * ratioVI;
781        //
782        // When one of the outline circle cover the the outline centroid, (like I is
783        // on the other side of C), there is no real umbra any more, so we just fake
784        // a small area around the centroid as the umbra, and tune down the spot
785        // shadow's umbra strength to simulate the effect the whole shadow will
786        // become lighter in this case.
787        // The ratio can be simulated by using the inverse of maximum of ratioVI for
788        // all (V).
789        distOutline = (outlineData[i].position - outlineCentroid).length();
790        if (distOutline == 0) {
791            // If the outline has 0 area, then there is no spot shadow anyway.
792            ALOGW("Outline has 0 area, no spot shadow!");
793            return;
794        }
795        ratioVI = outlineData[i].radius / distOutline;
796        if (ratioVI >= 1.0) {
797            maxRaitoVI = ratioVI;
798            hasValidUmbra = false;
799        }
800        // When we know we don't have valid umbra, don't bother to compute the
801        // values below. But we can't skip the loop yet since we want to know the
802        // maximum ratio.
803        if (hasValidUmbra) {
804            float ratioIC = (distOutline - outlineData[i].radius) / distOutline;
805            umbra[i] = outlineData[i].position * ratioIC + outlineCentroid * ratioVI;
806        }
807    }
808
809    float shadowStrengthScale = 1.0;
810    if (!hasValidUmbra) {
811        ALOGW("The object is too close to the light or too small, no real umbra!");
812        for (int i = 0; i < polyLength; i++) {
813            umbra[i] = outlineData[i].position * FAKE_UMBRA_SIZE_RATIO +
814                outlineCentroid * (1 - FAKE_UMBRA_SIZE_RATIO);
815        }
816        shadowStrengthScale = 1.0 / maxRaitoVI;
817    }
818
819#if DEBUG_SHADOW
820    dumpPolygon(poly, polyLength, "input poly");
821    dumpPolygon(outline, polyLength, "outline");
822    dumpPolygon(penumbra, penumbraLength, "penumbra");
823    dumpPolygon(umbra, polyLength, "umbra");
824    ALOGD("hasValidUmbra is %d and shadowStrengthScale is %f", hasValidUmbra, shadowStrengthScale);
825#endif
826
827    generateTriangleStrip(isCasterOpaque, shadowStrengthScale, penumbra,
828            penumbraLength, umbra, polyLength, poly, polyLength, shadowTriangleStrip);
829}
830
831/**
832 * Converts a polygon specified with CW vertices into an array of distance-from-centroid values.
833 *
834 * Returns false in error conditions
835 *
836 * @param poly Array of vertices. Note that these *must* be CW.
837 * @param polyLength The number of vertices in the polygon.
838 * @param polyCentroid The centroid of the polygon, from which rays will be cast
839 * @param rayDist The output array for the calculated distances, must be SHADOW_RAY_COUNT in size
840 */
841bool convertPolyToRayDist(const Vector2* poly, int polyLength, const Vector2& polyCentroid,
842        float* rayDist) {
843    const int rays = SHADOW_RAY_COUNT;
844    const float step = M_PI * 2 / rays;
845
846    const Vector2* lastVertex = &(poly[polyLength - 1]);
847    float startAngle = angle(*lastVertex, polyCentroid);
848
849    // Start with the ray that's closest to and less than startAngle
850    int rayIndex = floor((startAngle - EPSILON) / step);
851    rayIndex = (rayIndex + rays) % rays; // ensure positive
852
853    for (int polyIndex = 0; polyIndex < polyLength; polyIndex++) {
854        /*
855         * For a given pair of vertices on the polygon, poly[i-1] and poly[i], the rays that
856         * intersect these will be those that are between the two angles from the centroid that the
857         * vertices define.
858         *
859         * Because the polygon vertices are stored clockwise, the closest ray with an angle
860         * *smaller* than that defined by angle(poly[i], centroid) will be the first ray that does
861         * not intersect with poly[i-1], poly[i].
862         */
863        float currentAngle = angle(poly[polyIndex], polyCentroid);
864
865        // find first ray that will not intersect the line segment poly[i-1] & poly[i]
866        int firstRayIndexOnNextSegment = floor((currentAngle - EPSILON) / step);
867        firstRayIndexOnNextSegment = (firstRayIndexOnNextSegment + rays) % rays; // ensure positive
868
869        // Iterate through all rays that intersect with poly[i-1], poly[i] line segment.
870        // This may be 0 rays.
871        while (rayIndex != firstRayIndexOnNextSegment) {
872            float distanceToIntersect = rayIntersectPoints(polyCentroid,
873                    cos(rayIndex * step),
874                    sin(rayIndex * step),
875                    *lastVertex, poly[polyIndex]);
876            if (distanceToIntersect < 0) {
877#if DEBUG_SHADOW
878                ALOGW("ERROR: convertPolyToRayDist failed");
879#endif
880                return false; // error case, abort
881            }
882
883            rayDist[rayIndex] = distanceToIntersect;
884
885            rayIndex = (rayIndex - 1 + rays) % rays;
886        }
887        lastVertex = &poly[polyIndex];
888    }
889
890   return true;
891}
892
893int SpotShadow::calculateOccludedUmbra(const Vector2* umbra, int umbraLength,
894        const Vector3* poly, int polyLength, Vector2* occludedUmbra) {
895    // Occluded umbra area is computed as the intersection of the projected 2D
896    // poly and umbra.
897    for (int i = 0; i < polyLength; i++) {
898        occludedUmbra[i].x = poly[i].x;
899        occludedUmbra[i].y = poly[i].y;
900    }
901
902    // Both umbra and incoming polygon are guaranteed to be CW, so we can call
903    // intersection() directly.
904    return intersection(umbra, umbraLength,
905            occludedUmbra, polyLength);
906}
907
908/**
909 * Generate a triangle strip given two convex polygons
910 *
911 * @param penumbra The outer polygon x,y vertexes
912 * @param penumbraLength The number of vertexes in the outer polygon
913 * @param umbra The inner outer polygon x,y vertexes
914 * @param umbraLength The number of vertexes in the inner polygon
915 * @param shadowTriangleStrip return an (x,y,alpha) triangle strip representing the shadow. Return
916 *                            empty strip if error.
917**/
918void SpotShadow::generateTriangleStrip(bool isCasterOpaque, float shadowStrengthScale,
919        const Vector2* penumbra, int penumbraLength, const Vector2* umbra, int umbraLength,
920        const Vector3* poly, int polyLength, VertexBuffer& shadowTriangleStrip) {
921    const int rays = SHADOW_RAY_COUNT;
922    const int size = 2 * rays;
923    const float step = M_PI * 2 / rays;
924    // Centroid of the umbra.
925    Vector2 centroid = ShadowTessellator::centroid2d(umbra, umbraLength);
926#if DEBUG_SHADOW
927    ALOGD("centroid2d =  %f , %f", centroid.x, centroid.y);
928#endif
929    // Intersection to the penumbra.
930    float penumbraDistPerRay[rays];
931    // Intersection to the umbra.
932    float umbraDistPerRay[rays];
933    // Intersection to the occluded umbra area.
934    float occludedUmbraDistPerRay[rays];
935
936    // convert CW polygons to ray distance encoding, aborting on conversion failure
937    if (!convertPolyToRayDist(umbra, umbraLength, centroid, umbraDistPerRay)) return;
938    if (!convertPolyToRayDist(penumbra, penumbraLength, centroid, penumbraDistPerRay)) return;
939
940    bool hasOccludedUmbraArea = false;
941    if (isCasterOpaque) {
942        Vector2 occludedUmbra[polyLength + umbraLength];
943        int occludedUmbraLength = calculateOccludedUmbra(umbra, umbraLength, poly, polyLength,
944                occludedUmbra);
945        // Make sure the centroid is inside the umbra, otherwise, fall back to the
946        // approach as if there is no occluded umbra area.
947        if (testPointInsidePolygon(centroid, occludedUmbra, occludedUmbraLength)) {
948            hasOccludedUmbraArea = true;
949            // Shrink the occluded umbra area to avoid pixel level artifacts.
950            for (int i = 0; i < occludedUmbraLength; i ++) {
951                occludedUmbra[i] = centroid + (occludedUmbra[i] - centroid) *
952                        OCLLUDED_UMBRA_SHRINK_FACTOR;
953            }
954            if (!convertPolyToRayDist(occludedUmbra, occludedUmbraLength, centroid,
955                    occludedUmbraDistPerRay)) {
956                return;
957            }
958        }
959    }
960    AlphaVertex* shadowVertices =
961            shadowTriangleStrip.alloc<AlphaVertex>(SHADOW_VERTEX_COUNT);
962
963    // NOTE: Shadow alpha values are transformed when stored in alphavertices,
964    // so that they can be consumed directly by gFS_Main_ApplyVertexAlphaShadowInterp
965    float transformedMaxAlpha = M_PI * shadowStrengthScale;
966
967    // Calculate the vertices (x, y, alpha) in the shadow area.
968    AlphaVertex centroidXYA;
969    AlphaVertex::set(&centroidXYA, centroid.x, centroid.y, transformedMaxAlpha);
970    for (int rayIndex = 0; rayIndex < rays; rayIndex++) {
971        float dx = cosf(step * rayIndex);
972        float dy = sinf(step * rayIndex);
973
974        // penumbra ring
975        float penumbraDistance = penumbraDistPerRay[rayIndex];
976        AlphaVertex::set(&shadowVertices[rayIndex],
977                dx * penumbraDistance + centroid.x,
978                dy * penumbraDistance + centroid.y, 0.0f);
979
980        // umbra ring
981        float umbraDistance = umbraDistPerRay[rayIndex];
982        AlphaVertex::set(&shadowVertices[rays + rayIndex],
983                dx * umbraDistance + centroid.x,
984                dy * umbraDistance + centroid.y,
985                transformedMaxAlpha);
986
987        // occluded umbra ring
988        if (hasOccludedUmbraArea) {
989            float occludedUmbraDistance = occludedUmbraDistPerRay[rayIndex];
990            AlphaVertex::set(&shadowVertices[2 * rays + rayIndex],
991                    dx * occludedUmbraDistance + centroid.x,
992                    dy * occludedUmbraDistance + centroid.y, transformedMaxAlpha);
993        } else {
994            // Put all vertices of the occluded umbra ring at the centroid.
995            shadowVertices[2 * rays + rayIndex] = centroidXYA;
996        }
997    }
998    shadowTriangleStrip.setMode(VertexBuffer::kTwoPolyRingShadow);
999    shadowTriangleStrip.computeBounds<AlphaVertex>();
1000}
1001
1002/**
1003 * This is only for experimental purpose.
1004 * After intersections are calculated, we could smooth the polygon if needed.
1005 * So far, we don't think it is more appealing yet.
1006 *
1007 * @param level The level of smoothness.
1008 * @param rays The total number of rays.
1009 * @param rayDist (In and Out) The distance for each ray.
1010 *
1011 */
1012void SpotShadow::smoothPolygon(int level, int rays, float* rayDist) {
1013    for (int k = 0; k < level; k++) {
1014        for (int i = 0; i < rays; i++) {
1015            float p1 = rayDist[(rays - 1 + i) % rays];
1016            float p2 = rayDist[i];
1017            float p3 = rayDist[(i + 1) % rays];
1018            rayDist[i] = (p1 + p2 * 2 + p3) / 4;
1019        }
1020    }
1021}
1022
1023#if DEBUG_SHADOW
1024
1025#define TEST_POINT_NUMBER 128
1026
1027/**
1028 * Calculate the bounds for generating random test points.
1029 */
1030void SpotShadow::updateBound(const Vector2 inVector, Vector2& lowerBound,
1031        Vector2& upperBound ) {
1032    if (inVector.x < lowerBound.x) {
1033        lowerBound.x = inVector.x;
1034    }
1035
1036    if (inVector.y < lowerBound.y) {
1037        lowerBound.y = inVector.y;
1038    }
1039
1040    if (inVector.x > upperBound.x) {
1041        upperBound.x = inVector.x;
1042    }
1043
1044    if (inVector.y > upperBound.y) {
1045        upperBound.y = inVector.y;
1046    }
1047}
1048
1049/**
1050 * For debug purpose, when things go wrong, dump the whole polygon data.
1051 */
1052void SpotShadow::dumpPolygon(const Vector2* poly, int polyLength, const char* polyName) {
1053    for (int i = 0; i < polyLength; i++) {
1054        ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
1055    }
1056}
1057
1058/**
1059 * For debug purpose, when things go wrong, dump the whole polygon data.
1060 */
1061void SpotShadow::dumpPolygon(const Vector3* poly, int polyLength, const char* polyName) {
1062    for (int i = 0; i < polyLength; i++) {
1063        ALOGD("polygon %s i %d x %f y %f", polyName, i, poly[i].x, poly[i].y);
1064    }
1065}
1066
1067/**
1068 * Test whether the polygon is convex.
1069 */
1070bool SpotShadow::testConvex(const Vector2* polygon, int polygonLength,
1071        const char* name) {
1072    bool isConvex = true;
1073    for (int i = 0; i < polygonLength; i++) {
1074        Vector2 start = polygon[i];
1075        Vector2 middle = polygon[(i + 1) % polygonLength];
1076        Vector2 end = polygon[(i + 2) % polygonLength];
1077
1078        double delta = (double(middle.x) - start.x) * (double(end.y) - start.y) -
1079                (double(middle.y) - start.y) * (double(end.x) - start.x);
1080        bool isCCWOrCoLinear = (delta >= EPSILON);
1081
1082        if (isCCWOrCoLinear) {
1083            ALOGW("(Error Type 2): polygon (%s) is not a convex b/c start (x %f, y %f),"
1084                    "middle (x %f, y %f) and end (x %f, y %f) , delta is %f !!!",
1085                    name, start.x, start.y, middle.x, middle.y, end.x, end.y, delta);
1086            isConvex = false;
1087            break;
1088        }
1089    }
1090    return isConvex;
1091}
1092
1093/**
1094 * Test whether or not the polygon (intersection) is within the 2 input polygons.
1095 * Using Marte Carlo method, we generate a random point, and if it is inside the
1096 * intersection, then it must be inside both source polygons.
1097 */
1098void SpotShadow::testIntersection(const Vector2* poly1, int poly1Length,
1099        const Vector2* poly2, int poly2Length,
1100        const Vector2* intersection, int intersectionLength) {
1101    // Find the min and max of x and y.
1102    Vector2 lowerBound = {FLT_MAX, FLT_MAX};
1103    Vector2 upperBound = {-FLT_MAX, -FLT_MAX};
1104    for (int i = 0; i < poly1Length; i++) {
1105        updateBound(poly1[i], lowerBound, upperBound);
1106    }
1107    for (int i = 0; i < poly2Length; i++) {
1108        updateBound(poly2[i], lowerBound, upperBound);
1109    }
1110
1111    bool dumpPoly = false;
1112    for (int k = 0; k < TEST_POINT_NUMBER; k++) {
1113        // Generate a random point between minX, minY and maxX, maxY.
1114        double randomX = rand() / double(RAND_MAX);
1115        double randomY = rand() / double(RAND_MAX);
1116
1117        Vector2 testPoint;
1118        testPoint.x = lowerBound.x + randomX * (upperBound.x - lowerBound.x);
1119        testPoint.y = lowerBound.y + randomY * (upperBound.y - lowerBound.y);
1120
1121        // If the random point is in both poly 1 and 2, then it must be intersection.
1122        if (testPointInsidePolygon(testPoint, intersection, intersectionLength)) {
1123            if (!testPointInsidePolygon(testPoint, poly1, poly1Length)) {
1124                dumpPoly = true;
1125                ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
1126                      " not in the poly1",
1127                        testPoint.x, testPoint.y);
1128            }
1129
1130            if (!testPointInsidePolygon(testPoint, poly2, poly2Length)) {
1131                dumpPoly = true;
1132                ALOGW("(Error Type 1): one point (%f, %f) in the intersection is"
1133                      " not in the poly2",
1134                        testPoint.x, testPoint.y);
1135            }
1136        }
1137    }
1138
1139    if (dumpPoly) {
1140        dumpPolygon(intersection, intersectionLength, "intersection");
1141        for (int i = 1; i < intersectionLength; i++) {
1142            Vector2 delta = intersection[i] - intersection[i - 1];
1143            ALOGD("Intersetion i, %d Vs i-1 is delta %f", i, delta.lengthSquared());
1144        }
1145
1146        dumpPolygon(poly1, poly1Length, "poly 1");
1147        dumpPolygon(poly2, poly2Length, "poly 2");
1148    }
1149}
1150#endif
1151
1152}; // namespace uirenderer
1153}; // namespace android
1154