blob: 810e6b21d011f3cbfff5afa1af03b08f48a06d71 [file] [log] [blame]
epoger@google.comec3ed6a2011-07-28 14:26:00 +00001
2/*
3 * Copyright 2011 Google Inc.
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
reed@android.com8a1c16f2008-12-17 15:59:43 +00008#include "SkMatrix.h"
9
10typedef int64_t SkDScalar;
11
12static SkScalar SkDScalar_toScalar(SkDScalar value) {
13 SkDScalar result = (value + (1 << 15)) >> 16;
bsalomon@google.com8e06dab2011-10-07 20:03:39 +000014 SkDEBUGCODE(int top = static_cast<int>(result >> 31);)
reed@android.com8a1c16f2008-12-17 15:59:43 +000015 SkASSERT(top == 0 || top == -1);
16 return (SkScalar)result;
17}
18
19static SkDScalar SkDScalar_setMul(SkScalar a, SkScalar b) {
20 return (SkDScalar)a * b;
21}
22
23static void computeOuterProduct(SkMatrix* matrix,
24 const SkPoint pts0[3], const SkPoint& ave0,
25 const SkPoint pts1[3], const SkPoint& ave1) {
26 SkDScalar tmp[4];
reed@android.com4516f472009-06-29 16:25:36 +000027 sk_bzero(tmp, sizeof(tmp));
reed@android.com8a1c16f2008-12-17 15:59:43 +000028
29 for (int i = 0; i < 3; i++) {
30 SkScalar x0 = pts0[i].fX - ave0.fX;
31 SkScalar y0 = pts0[i].fY - ave0.fY;
32 SkScalar x1 = pts1[i].fX - ave1.fX;
33 SkScalar y1 = pts1[i].fY - ave1.fY;
34 tmp[0] += SkDScalar_setMul(x0, x1);
35 tmp[1] += SkDScalar_setMul(x0, y1);
36 tmp[2] += SkDScalar_setMul(y0, x1);
37 tmp[3] += SkDScalar_setMul(y0, y1);
38 }
39 matrix->reset();
40 matrix->setScaleX(SkDScalar_toScalar(tmp[0]));
41 matrix->setSkewY( SkDScalar_toScalar(tmp[1]));
42 matrix->setSkewX( SkDScalar_toScalar(tmp[2]));
43 matrix->setScaleY(SkDScalar_toScalar(tmp[3]));
44}
45
46static SkScalar dot(SkScalar ax, SkScalar ay, SkScalar bx, SkScalar by) {
47 return SkDScalar_toScalar(SkDScalar_setMul(ax, bx) +
48 SkDScalar_setMul(ay, by));
49}
50
51bool SkSetPoly3To3(SkMatrix* matrix, const SkPoint src[3], const SkPoint dst[3]) {
52 const SkPoint& srcAve = src[0];
53 const SkPoint& dstAve = dst[0];
54
55 SkMatrix srcOP, dstOP;
56
57 computeOuterProduct(&srcOP, src, srcAve, src, srcAve);
58
59 if (!srcOP.invert(&srcOP)) {
60 return false;
61 }
62
63 computeOuterProduct(&dstOP, src, srcAve, dst, dstAve);
64
65 matrix->setConcat(dstOP, srcOP);
66 matrix->setTranslateX(dstAve.fX - dot(srcAve.fX, srcAve.fY,
67 matrix->getScaleX(), matrix->getSkewX()));
68 matrix->setTranslateY(dstAve.fY - dot(srcAve.fX, srcAve.fY,
69 matrix->getSkewY(), matrix->getScaleY()));
70 return true;
71}
72