Skip to content

Instantly share code, notes, and snippets.

@mrjackphil
Created October 20, 2023 11:13
Show Gist options
  • Save mrjackphil/49a435432458f7fcf7844a405dae0d59 to your computer and use it in GitHub Desktop.
Save mrjackphil/49a435432458f7fcf7844a405dae0d59 to your computer and use it in GitHub Desktop.
Drawings to walls for Foundry v10
let drawings = canvas.drawings.controlled;
function tuple(a) {
let arr = []
for (i in a) {
if (typeof a[i] !== 'number') {
continue
}
if (i % 2) {
arr[arr.length-1].push(a[i])
} else {
arr.push([a[i]])
}
}
return arr
}
drawings = drawings.map(drawing => {
console.log('==============Drawing=============\n', drawing)
switch (drawing.data.shape.type) {
case "f":
case "p": {
const rotation = drawing.shape.transform.rotation;
const {_id, x, y} = drawing.data;
const { points, width, height } = drawing.data.shape;
const tuple_points = tuple(points)
return { id: _id, valid: true, points: tuple_points, rotation, x, y, width, height };
}
case "r": {
const { width, height } = drawing.shape;
const rotation = drawing.shape.transform.rotation;
let { _id, x, y, strokeWidth } = drawing.data;
const points = [
[0 + (strokeWidth / 2), 0 + (strokeWidth / 2)],
[width - (strokeWidth / 2), 0 + (strokeWidth / 2)],
[width - (strokeWidth / 2), height - (strokeWidth / 2)],
[0 + (strokeWidth / 2), height - (strokeWidth / 2)],
[0 + (strokeWidth / 2), 0 + (strokeWidth / 2)]
];
return { id: _id, valid: true, points, rotation, x, y, width, height };
}
default:
return { id: drawing.data._id, valid: false };
}
}).filter(drawing => {
if (!drawing.valid) {
ui.notifications.warn(`Drawing "${drawing.id}" is not a valid drawing type!`);
return false;
}
return true;
});
if (drawings.length) {
const newWalls = drawings.flatMap((drawing) => {
const { x, y, width = 0, height = 0 } = drawing;
const xCenterOffset = width / 2;
const yCenterOffset = height / 2;
/*{
"id": "eevjaerrnHYZN6Qb",
"valid": true,
"points": [
[ 4, 4 ],
[ null, 4 ],
[ null, null ],
[ 4, null ],
[ 4, 4 ]
],
"rotation": 0,
"x": 1462.5,
"y": 1187.5
}
*/
console.log("=======Transofrmed========\n", drawing);
const θ = Math.toRadians(drawing.rotation);
const cosθ = Math.cos(θ);
const sinθ = Math.sin(θ);
const points = drawing.points.map((point) => {
const offsetX = (point[0] || 0) - xCenterOffset;
const offsetY = (point[1] || 1) - yCenterOffset;
const rotatedX = (offsetX * cosθ - offsetY * sinθ);
const rotatedY = (offsetY * cosθ + offsetX * sinθ);
return [rotatedX + x + xCenterOffset, rotatedY + y + yCenterOffset];
});
console.log("=========Points=========\n", points)
return points
.slice(0, points.length - 1)
.map((point, i) => ({ c: point.concat(points[i + 1]) }));
});
console.log('======newWalls==========\n', newWalls);
canvas.scene.createEmbeddedDocuments("Wall", newWalls);
canvas.walls.activate();
} else {
ui.notifications.error("No drawings selected!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment