1/*
2 * Copyright 2014 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "SkPatchUtils.h"
9
10#include "SkColorPriv.h"
11#include "SkGeometry.h"
12
13/**
14 * Evaluator to sample the values of a cubic bezier using forward differences.
15 * Forward differences is a method for evaluating a nth degree polynomial at a uniform step by only
16 * adding precalculated values.
17 * For a linear example we have the function f(t) = m*t+b, then the value of that function at t+h
18 * would be f(t+h) = m*(t+h)+b. If we want to know the uniform step that we must add to the first
19 * evaluation f(t) then we need to substract f(t+h) - f(t) = m*t + m*h + b - m*t + b = mh. After
20 * obtaining this value (mh) we could just add this constant step to our first sampled point
21 * to compute the next one.
22 *
23 * For the cubic case the first difference gives as a result a quadratic polynomial to which we can
24 * apply again forward differences and get linear function to which we can apply again forward
25 * differences to get a constant difference. This is why we keep an array of size 4, the 0th
26 * position keeps the sampled value while the next ones keep the quadratic, linear and constant
27 * difference values.
28 */
29
30class FwDCubicEvaluator {
31
32public:
33    FwDCubicEvaluator()
34    : fMax(0)
35    , fCurrent(0)
36    , fDivisions(0) {
37        memset(fPoints, 0, 4 * sizeof(SkPoint));
38        memset(fPoints, 0, 4 * sizeof(SkPoint));
39        memset(fPoints, 0, 4 * sizeof(SkPoint));
40    }
41
42    /**
43     * Receives the 4 control points of the cubic bezier.
44     */
45    FwDCubicEvaluator(SkPoint a, SkPoint b, SkPoint c, SkPoint d) {
46        fPoints[0] = a;
47        fPoints[1] = b;
48        fPoints[2] = c;
49        fPoints[3] = d;
50
51        SkCubicToCoeff(fPoints, fCoefs);
52
53        this->restart(1);
54    }
55
56    explicit FwDCubicEvaluator(const SkPoint points[4])  {
57        memcpy(fPoints, points, 4 * sizeof(SkPoint));
58
59        SkCubicToCoeff(fPoints, fCoefs);
60
61        this->restart(1);
62    }
63
64    /**
65     * Restarts the forward differences evaluator to the first value of t = 0.
66     */
67    void restart(int divisions)  {
68        fDivisions = divisions;
69        SkScalar h  = 1.f / fDivisions;
70        fCurrent    = 0;
71        fMax        = fDivisions + 1;
72        fFwDiff[0]  = fCoefs[3];
73        SkScalar h2 = h * h;
74        SkScalar h3 = h2 * h;
75
76        fFwDiff[3].set(6.f * fCoefs[0].x() * h3, 6.f * fCoefs[0].y() * h3); //6ah^3
77        fFwDiff[2].set(fFwDiff[3].x() + 2.f * fCoefs[1].x() * h2, //6ah^3 + 2bh^2
78                       fFwDiff[3].y() + 2.f * fCoefs[1].y() * h2);
79        fFwDiff[1].set(fCoefs[0].x() * h3 + fCoefs[1].x() * h2 + fCoefs[2].x() * h,//ah^3 + bh^2 +ch
80                       fCoefs[0].y() * h3 + fCoefs[1].y() * h2 + fCoefs[2].y() * h);
81    }
82
83    /**
84     * Check if the evaluator is still within the range of 0<=t<=1
85     */
86    bool done() const {
87        return fCurrent > fMax;
88    }
89
90    /**
91     * Call next to obtain the SkPoint sampled and move to the next one.
92     */
93    SkPoint next() {
94        SkPoint point = fFwDiff[0];
95        fFwDiff[0]    += fFwDiff[1];
96        fFwDiff[1]    += fFwDiff[2];
97        fFwDiff[2]    += fFwDiff[3];
98        fCurrent++;
99        return point;
100    }
101
102    const SkPoint* getCtrlPoints() const {
103        return fPoints;
104    }
105
106private:
107    int fMax, fCurrent, fDivisions;
108    SkPoint fFwDiff[4], fCoefs[4], fPoints[4];
109};
110
111////////////////////////////////////////////////////////////////////////////////
112
113// size in pixels of each partition per axis, adjust this knob
114static const int kPartitionSize = 10;
115
116/**
117 * Calculate the approximate arc length given a bezier curve's control points.
118 */
119static SkScalar approx_arc_length(SkPoint* points, int count) {
120    if (count < 2) {
121        return 0;
122    }
123    SkScalar arcLength = 0;
124    for (int i = 0; i < count - 1; i++) {
125        arcLength += SkPoint::Distance(points[i], points[i + 1]);
126    }
127    return arcLength;
128}
129
130static SkScalar bilerp(SkScalar tx, SkScalar ty, SkScalar c00, SkScalar c10, SkScalar c01,
131                      SkScalar c11) {
132    SkScalar a = c00 * (1.f - tx) + c10 * tx;
133    SkScalar b = c01 * (1.f - tx) + c11 * tx;
134    return a * (1.f - ty) + b * ty;
135}
136
137SkISize SkPatchUtils::GetLevelOfDetail(const SkPoint cubics[12], const SkMatrix* matrix) {
138
139    // Approximate length of each cubic.
140    SkPoint pts[kNumPtsCubic];
141    SkPatchUtils::getTopCubic(cubics, pts);
142    matrix->mapPoints(pts, kNumPtsCubic);
143    SkScalar topLength = approx_arc_length(pts, kNumPtsCubic);
144
145    SkPatchUtils::getBottomCubic(cubics, pts);
146    matrix->mapPoints(pts, kNumPtsCubic);
147    SkScalar bottomLength = approx_arc_length(pts, kNumPtsCubic);
148
149    SkPatchUtils::getLeftCubic(cubics, pts);
150    matrix->mapPoints(pts, kNumPtsCubic);
151    SkScalar leftLength = approx_arc_length(pts, kNumPtsCubic);
152
153    SkPatchUtils::getRightCubic(cubics, pts);
154    matrix->mapPoints(pts, kNumPtsCubic);
155    SkScalar rightLength = approx_arc_length(pts, kNumPtsCubic);
156
157    // Level of detail per axis, based on the larger side between top and bottom or left and right
158    int lodX = static_cast<int>(SkMaxScalar(topLength, bottomLength) / kPartitionSize);
159    int lodY = static_cast<int>(SkMaxScalar(leftLength, rightLength) / kPartitionSize);
160
161    return SkISize::Make(SkMax32(8, lodX), SkMax32(8, lodY));
162}
163
164void SkPatchUtils::getTopCubic(const SkPoint cubics[12], SkPoint points[4]) {
165    points[0] = cubics[kTopP0_CubicCtrlPts];
166    points[1] = cubics[kTopP1_CubicCtrlPts];
167    points[2] = cubics[kTopP2_CubicCtrlPts];
168    points[3] = cubics[kTopP3_CubicCtrlPts];
169}
170
171void SkPatchUtils::getBottomCubic(const SkPoint cubics[12], SkPoint points[4]) {
172    points[0] = cubics[kBottomP0_CubicCtrlPts];
173    points[1] = cubics[kBottomP1_CubicCtrlPts];
174    points[2] = cubics[kBottomP2_CubicCtrlPts];
175    points[3] = cubics[kBottomP3_CubicCtrlPts];
176}
177
178void SkPatchUtils::getLeftCubic(const SkPoint cubics[12], SkPoint points[4]) {
179    points[0] = cubics[kLeftP0_CubicCtrlPts];
180    points[1] = cubics[kLeftP1_CubicCtrlPts];
181    points[2] = cubics[kLeftP2_CubicCtrlPts];
182    points[3] = cubics[kLeftP3_CubicCtrlPts];
183}
184
185void SkPatchUtils::getRightCubic(const SkPoint cubics[12], SkPoint points[4]) {
186    points[0] = cubics[kRightP0_CubicCtrlPts];
187    points[1] = cubics[kRightP1_CubicCtrlPts];
188    points[2] = cubics[kRightP2_CubicCtrlPts];
189    points[3] = cubics[kRightP3_CubicCtrlPts];
190}
191
192bool SkPatchUtils::getVertexData(SkPatchUtils::VertexData* data, const SkPoint cubics[12],
193                   const SkColor colors[4], const SkPoint texCoords[4], int lodX, int lodY) {
194    if (lodX < 1 || lodY < 1 || NULL == cubics || NULL == data) {
195        return false;
196    }
197
198    // check for overflow in multiplication
199    const int64_t lodX64 = (lodX + 1),
200                   lodY64 = (lodY + 1),
201                   mult64 = lodX64 * lodY64;
202    if (mult64 > SK_MaxS32) {
203        return false;
204    }
205    data->fVertexCount = SkToS32(mult64);
206
207    // it is recommended to generate draw calls of no more than 65536 indices, so we never generate
208    // more than 60000 indices. To accomplish that we resize the LOD and vertex count
209    if (data->fVertexCount > 10000 || lodX > 200 || lodY > 200) {
210        SkScalar weightX = static_cast<SkScalar>(lodX) / (lodX + lodY);
211        SkScalar weightY = static_cast<SkScalar>(lodY) / (lodX + lodY);
212
213        // 200 comes from the 100 * 2 which is the max value of vertices because of the limit of
214        // 60000 indices ( sqrt(60000 / 6) that comes from data->fIndexCount = lodX * lodY * 6)
215        lodX = static_cast<int>(weightX * 200);
216        lodY = static_cast<int>(weightY * 200);
217        data->fVertexCount = (lodX + 1) * (lodY + 1);
218    }
219    data->fIndexCount = lodX * lodY * 6;
220
221    data->fPoints = SkNEW_ARRAY(SkPoint, data->fVertexCount);
222    data->fIndices = SkNEW_ARRAY(uint16_t, data->fIndexCount);
223
224    // if colors is not null then create array for colors
225    SkPMColor colorsPM[kNumCorners];
226    if (colors) {
227        // premultiply colors to avoid color bleeding.
228        for (int i = 0; i < kNumCorners; i++) {
229            colorsPM[i] = SkPreMultiplyColor(colors[i]);
230        }
231        data->fColors = SkNEW_ARRAY(uint32_t, data->fVertexCount);
232    }
233
234    // if texture coordinates are not null then create array for them
235    if (texCoords) {
236        data->fTexCoords = SkNEW_ARRAY(SkPoint, data->fVertexCount);
237    }
238
239    SkPoint pts[kNumPtsCubic];
240    SkPatchUtils::getBottomCubic(cubics, pts);
241    FwDCubicEvaluator fBottom(pts);
242    SkPatchUtils::getTopCubic(cubics, pts);
243    FwDCubicEvaluator fTop(pts);
244    SkPatchUtils::getLeftCubic(cubics, pts);
245    FwDCubicEvaluator fLeft(pts);
246    SkPatchUtils::getRightCubic(cubics, pts);
247    FwDCubicEvaluator fRight(pts);
248
249    fBottom.restart(lodX);
250    fTop.restart(lodX);
251
252    SkScalar u = 0.0f;
253    int stride = lodY + 1;
254    for (int x = 0; x <= lodX; x++) {
255        SkPoint bottom = fBottom.next(), top = fTop.next();
256        fLeft.restart(lodY);
257        fRight.restart(lodY);
258        SkScalar v = 0.f;
259        for (int y = 0; y <= lodY; y++) {
260            int dataIndex = x * (lodY + 1) + y;
261
262            SkPoint left = fLeft.next(), right = fRight.next();
263
264            SkPoint s0 = SkPoint::Make((1.0f - v) * top.x() + v * bottom.x(),
265                                       (1.0f - v) * top.y() + v * bottom.y());
266            SkPoint s1 = SkPoint::Make((1.0f - u) * left.x() + u * right.x(),
267                                       (1.0f - u) * left.y() + u * right.y());
268            SkPoint s2 = SkPoint::Make(
269                                       (1.0f - v) * ((1.0f - u) * fTop.getCtrlPoints()[0].x()
270                                                     + u * fTop.getCtrlPoints()[3].x())
271                                       + v * ((1.0f - u) * fBottom.getCtrlPoints()[0].x()
272                                              + u * fBottom.getCtrlPoints()[3].x()),
273                                       (1.0f - v) * ((1.0f - u) * fTop.getCtrlPoints()[0].y()
274                                                     + u * fTop.getCtrlPoints()[3].y())
275                                       + v * ((1.0f - u) * fBottom.getCtrlPoints()[0].y()
276                                              + u * fBottom.getCtrlPoints()[3].y()));
277            data->fPoints[dataIndex] = s0 + s1 - s2;
278
279            if (colors) {
280                uint8_t a = uint8_t(bilerp(u, v,
281                                   SkScalar(SkColorGetA(colorsPM[kTopLeft_Corner])),
282                                   SkScalar(SkColorGetA(colorsPM[kTopRight_Corner])),
283                                   SkScalar(SkColorGetA(colorsPM[kBottomLeft_Corner])),
284                                   SkScalar(SkColorGetA(colorsPM[kBottomRight_Corner]))));
285                uint8_t r = uint8_t(bilerp(u, v,
286                                   SkScalar(SkColorGetR(colorsPM[kTopLeft_Corner])),
287                                   SkScalar(SkColorGetR(colorsPM[kTopRight_Corner])),
288                                   SkScalar(SkColorGetR(colorsPM[kBottomLeft_Corner])),
289                                   SkScalar(SkColorGetR(colorsPM[kBottomRight_Corner]))));
290                uint8_t g = uint8_t(bilerp(u, v,
291                                   SkScalar(SkColorGetG(colorsPM[kTopLeft_Corner])),
292                                   SkScalar(SkColorGetG(colorsPM[kTopRight_Corner])),
293                                   SkScalar(SkColorGetG(colorsPM[kBottomLeft_Corner])),
294                                   SkScalar(SkColorGetG(colorsPM[kBottomRight_Corner]))));
295                uint8_t b = uint8_t(bilerp(u, v,
296                                   SkScalar(SkColorGetB(colorsPM[kTopLeft_Corner])),
297                                   SkScalar(SkColorGetB(colorsPM[kTopRight_Corner])),
298                                   SkScalar(SkColorGetB(colorsPM[kBottomLeft_Corner])),
299                                   SkScalar(SkColorGetB(colorsPM[kBottomRight_Corner]))));
300                data->fColors[dataIndex] = SkPackARGB32(a,r,g,b);
301            }
302
303            if (texCoords) {
304                data->fTexCoords[dataIndex] = SkPoint::Make(
305                                            bilerp(u, v, texCoords[kTopLeft_Corner].x(),
306                                                   texCoords[kTopRight_Corner].x(),
307                                                   texCoords[kBottomLeft_Corner].x(),
308                                                   texCoords[kBottomRight_Corner].x()),
309                                            bilerp(u, v, texCoords[kTopLeft_Corner].y(),
310                                                   texCoords[kTopRight_Corner].y(),
311                                                   texCoords[kBottomLeft_Corner].y(),
312                                                   texCoords[kBottomRight_Corner].y()));
313
314            }
315
316            if(x < lodX && y < lodY) {
317                int i = 6 * (x * lodY + y);
318                data->fIndices[i] = x * stride + y;
319                data->fIndices[i + 1] = x * stride + 1 + y;
320                data->fIndices[i + 2] = (x + 1) * stride + 1 + y;
321                data->fIndices[i + 3] = data->fIndices[i];
322                data->fIndices[i + 4] = data->fIndices[i + 2];
323                data->fIndices[i + 5] = (x + 1) * stride + y;
324            }
325            v = SkScalarClampMax(v + 1.f / lodY, 1);
326        }
327        u = SkScalarClampMax(u + 1.f / lodX, 1);
328    }
329    return true;
330
331}
332