-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransform.js
89 lines (77 loc) · 2.02 KB
/
transform.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
function adj(m) { // Compute the adjugate of m
return [
m[4] * m[8] - m[5] * m[7], m[2] * m[7] - m[1] * m[8], m[1] * m[5] - m[2] * m[4],
m[5] * m[6] - m[3] * m[8], m[0] * m[8] - m[2] * m[6], m[2] * m[3] - m[0] * m[5],
m[3] * m[7] - m[4] * m[6], m[1] * m[6] - m[0] * m[7], m[0] * m[4] - m[1] * m[3]
];
}
function multmm(a, b) { // multiply two matrices
var c = Array(9);
for (var i = 0; i != 3; ++i) {
for (var j = 0; j != 3; ++j) {
var cij = 0;
for (var k = 0; k != 3; ++k) {
cij += a[3 * i + k] * b[3 * k + j];
}
c[3 * i + j] = cij;
}
}
return c;
}
function multmv(m, v) { // multiply matrix and vector
return [
m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
];
}
function pdbg(m, v) {
var r = multmv(m, v);
return r + " (" + r[0] / r[2] + ", " + r[1] / r[2] + ")";
}
function basisToPoints(x1, y1, x2, y2, x3, y3, x4, y4) {
var m = [
x1, x2, x3,
y1, y2, y3,
1, 1, 1
];
var v = multmv(adj(m), [x4, y4, 1]);
return multmm(m, [
v[0], 0, 0,
0, v[1], 0,
0, 0, v[2]
]);
}
function general2DProjection(
x1s, y1s, x1d, y1d,
x2s, y2s, x2d, y2d,
x3s, y3s, x3d, y3d,
x4s, y4s, x4d, y4d
) {
var s = basisToPoints(x1s, y1s, x2s, y2s, x3s, y3s, x4s, y4s);
var d = basisToPoints(x1d, y1d, x2d, y2d, x3d, y3d, x4d, y4d);
return multmm(d, adj(s));
}
function project(m, x, y) {
var v = multmv(m, [x, y, 1]);
return [v[0] / v[2], v[1] / v[2]];
}
function transform2d(w, h, x1, y1, x2, y2, x3, y3, x4, y4) {
var t = general2DProjection(0, 0, x1, y1, w, 0, x2, y2, 0, h, x3, y3, w, h, x4, y4);
for (i = 0; i != 9; ++i) t[i] = t[i] / t[8];
t = [t[0], t[3], 0, t[6],
t[1], t[4], 0, t[7],
0, 0, 1, 0,
t[2], t[5], 0, t[8]
];
t = "matrix3d(" + t.join(", ") + ")";
return t;
}
var width = 640;
var height = 1136;
var tl = [1723, 1358];
var tr = [1990, 1464];
var bl = [1486, 1828];
var br = [1755, 1945];
var transform = transform2d(width, height, tl[0], tl[1], tr[0], tr[1], bl[0], bl[1], br[0], br[1]);
console.log(transform);