heightmap data

beta.r3js.org
polygonboutique 2016-10-13 12:49:14 +02:00
parent af3586db85
commit 1528637994
1 changed files with 102 additions and 0 deletions

View File

@ -3247,6 +3247,108 @@ GameLib.D3.Game.prototype.LinkPair = function (
});
};
/* * * * * * * * * *
* Heightmap Tools
* * * * * * * * * */
GameLib.D3.HeightmapData = function (
sizeX,
sizeY,
matrix
) {
this.sizeX = sizeX || 0;
this.sizeY = sizeY || 0;
// 2D Array with height data
// Column-major
this.matrix = matrix || [];
};
// Note: this currently only works for cannon!
GameLib.D3.GenerateThreeMeshFromHeightField = function (
heightFieldShape
// Physics type.....
) {
var geometry = new THREE.Geometry();
var v0 = new CANNON.Vec3();
var v1 = new CANNON.Vec3();
var v2 = new CANNON.Vec3();
var shape = heightFieldShape;
for (var xi = 0; xi < shape.data.length - 1; xi++) {
for (var yi = 0; yi < shape.data[xi].length - 1; yi++) {
for (var k = 0; k < 2; k++) {
shape.getConvexTrianglePillar(xi, yi, k===0);
v0.copy(shape.pillarConvex.vertices[0]);
v1.copy(shape.pillarConvex.vertices[1]);
v2.copy(shape.pillarConvex.vertices[2]);
v0.vadd(shape.pillarOffset, v0);
v1.vadd(shape.pillarOffset, v1);
v2.vadd(shape.pillarOffset, v2);
geometry.vertices.push(
new THREE.Vector3(v0.x, v0.y, v0.z),
new THREE.Vector3(v1.x, v1.y, v1.z),
new THREE.Vector3(v2.x, v2.y, v2.z)
);
var i = geometry.vertices.length - 3;
geometry.faces.push(new THREE.Face3(i, i+1, i+2));
}
}
}
geometry.computeBoundingSphere();
geometry.computeFaceNormals();
return new THREE.Mesh(geometry, new THREE.MeshNormalMaterial({ wireframe : false, shading : THREE.SmoothShading }));
};
GameLib.D3.GenerateHeightmapDataFromImage = function (
imagePath,
callback // receives HeightmapData instance as the first argument
) {
var img = new Image();
img.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
var imgd = context.getImageData(0, 0, img.width, img.height);
var pixels = imgd.data;
var heightList = [];
for (var i = 0, n = pixels.length; i < n; i += (4)) {
heightList.push(pixels[i]);
}
var matrix = [];
var sizeX = img.width,
sizeY = img.height;
for (var i = 0; i < sizeX; i++) {
matrix.push([]);
for (var j = 0; j < sizeY; j++) {
var height = (heightList[(sizeX - i) + j * sizeY] / 255) * 15;
matrix[i].push(height);
}
}
// todo: delete canvas here
callback(new GameLib.D3.HeightmapData(sizeX, sizeY, matrix));
};
img.src = imagePath;
};
if (typeof module != 'undefined') {
module.exports = GameLib.D3;
}