Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//from https://math.stackexchange.com/questions/296794/finding-the-transform-matrix-from-4-projected-points-with-javascript/339033#339033
// and http://jsfiddle.net/dFrHS/1/
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 = new Float32Array(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 general2DProjection(x1s, y1s, x2s, y2s, x3s, y3s, x1d, y1d, x2d, y2d, x3d, y3d) {
var s = [
x1s, x2s, x3s,
y1s, y2s, y3s,
1, 1, 1
];
var d = [
x1d, x2d, x3d,
y1d, y2d, y3d,
1, 1, 1
];
return multmm(d, adj(s));
}
function transform2d( x1, y1, x2, y2, x3, y3) {
var w = 100;
var h = 100;
var t = general2DProjection(0, 0, w, 0, 0, h, x1, y1, x2, y2, x3, y3 );
for(i = 0; i != 9; ++i) t[i] = t[i]/t[8];
return [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] ];
}
/*
//compacted
function transform2d( src, dest ) {
var t = multmm(
[ dest[0], dest[2], dest[4], dest[1], dest[3], dest[5], 1,1,1 ],
adj( [ src[0], src[2], src[4], src[1], src[3], src[5], 1,1,1 ] )
);
return [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] ];
}
//*/
for THREE
function adjugate(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 multiplyMatrices(a, b) {
var c = new Float32Array(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 affineTransform(src, dst) {
var t = multiplyMatrices(
[dst[0], dst[2], dst[4], dst[1], dst[3], dst[5], 1, 1, 1],
adjugate([src[0], src[2], src[4], src[1], src[3], src[5], 1, 1, 1])
);
return [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]];
}
function getTrMatrix( s0, s1, s2, d0, d1, d2 ) {
var src = [ s0.x, s0.y, s1.x, s1.y, s2.x, s2.y];
var dst = [ d0.x, d0.y, d1.x, d1.y, d2.x, d2.y];
var t = affineTransform( src, dst );
var mat = new THREE.Matrix4();
mat.elements = t;
return mat;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment