-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.ts
More file actions
235 lines (207 loc) · 9.4 KB
/
helpers.ts
File metadata and controls
235 lines (207 loc) · 9.4 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import type { Point } from "./Math/LineIntersections";
import type { Vector } from "./Math/Vector";
import type { Camera } from "./Parts/Camera";
import { BoxCollider } from "./Parts/Children/BoxCollider";
import type { PolygonCollider } from "./Parts/Children/PolygonCollider";
import type { Renderer } from "./Parts/Children/Renderer";
import { Transform } from "./Parts/Children/Transform";
import type { Part } from "./Parts/Part";
import type { SpriteSheetData } from "./types";
export function generateUID(): string {
return Math.random().toString(36).substr(2, 9);
}
export function drawBox(ctx: CanvasRenderingContext2D, x: number, y: number, width: number, height: number, color: string = "black") {
ctx.strokeStyle = color;
ctx.strokeRect(x, y, width, height);
}
export function applyCamera(context: CanvasRenderingContext2D, camera: Camera) {
const view = camera.getViewMatrix();
context.save();
context.translate(context.canvas.width / 2, context.canvas.height / 2); // Move origin to center of canvas
context.translate(view.offset.x, view.offset.y); // Apply camera's inverse world position
context.scale(view.scale.x, view.scale.y); // Apply camera's zoom
}
export function resetCamera(context: CanvasRenderingContext2D) {
context.restore();
}
/**
* @param tpJson Texture Packer JSON data
* @description Converts Texture Packer JSON data to a format compatible with the SpriteSheetData interface. When exporting with TexturePacker, ensure to use the "JSON Array" format, and check the "prepend folder name" box to separate animations.
* @returns SpriteSheetData
*/
export function convertTexturePackerToSpriteSheetData(tpJson: any): SpriteSheetData {
const result: SpriteSheetData = {
frames: [],
meta: {
image: tpJson.meta.image,
size: {
w: tpJson.meta.size.w,
h: tpJson.meta.size.h,
},
animations: {},
},
};
for (const frameData of tpJson.frames) {
const { filename, frame } = frameData;
// Add to frames list
result.frames.push({
filename: filename.split("/").pop() || filename, // Use the last part of the filename
duration: frameData.duration || 100, // Optional duration for each frame
frame: {
x: frame.x,
y: frame.y,
w: frame.w,
h: frame.h,
},
rotated: frameData.rotated || false,
trimmed: frameData.trimmed || false,
spriteSourceSize: frameData.spriteSourceSize,
sourceSize: frameData.sourceSize,
});
// Extract animation name from folder (e.g., "walk")
const [animationName, frameName] = filename.split("/");
// Initialize animation entry if it doesn't exist
if (!result.meta.animations[animationName]) {
result.meta.animations[animationName] = { frames: [] };
}
// Add this frame to the animation group
result.meta.animations[animationName].frames.push(frameName);
}
// Optionally, pick the first animation as the default
const animationNames = Object.keys(result.meta.animations);
if (animationNames.length > 0) {
result.meta.startingAnimation = animationNames[0];
result.meta.startingFrame = result.meta.animations[animationNames[0]].frames[0];
}
return result;
}
export function getDebugInfo(part: any, depth: number): string {
if (!part || !part.childrenArray || part.childrenArray.length === 0) {
return "";
}
let info = depth == 0 ? `${part.name} (${part.id})<br>` : "";
const indent = "--".repeat(depth);
part.childrenArray.forEach((child: any) => {
info += `${indent}${child.name} (${child.id}): ${child.hoverbug || ""}<br>`;
if (child.childrenArray && child.childrenArray.length > 0) {
info += getDebugInfo(child, depth + 1);
}
});
return info;
}
export function isPointInPolygon(pointX: number, pointY: number, polygonVertices: Vector[]): boolean {
let inside = false;
for (let i = 0, j = polygonVertices.length - 1; i < polygonVertices.length; j = i++) {
const xi = polygonVertices[i].x, yi = polygonVertices[i].y;
const xj = polygonVertices[j].x, yj = polygonVertices[j].y;
const intersect = ((yi > pointY) !== (yj > pointY)) &&
(pointX < (xj - xi) * (pointY - yi) / (yj - yi) + xi);
if (intersect) inside = !inside;
}
return inside;
}
export function isPointInObject(mouseX: number, mouseY: number, child: Part): boolean {
const transform = child.child<Transform>("Transform");
if (!transform) {
console.warn(`Part <${child.name}> requires a Transform child.`);
return false;
}
const position = transform.worldPosition;
const boxCollider = child.child<BoxCollider>("BoxCollider");
const polygonCollider = child.child<PolygonCollider>("PolygonCollider");
let width, height, centerX, centerY;
if (boxCollider && boxCollider.start && boxCollider.end) {
// Use BoxCollider dimensions and offset
const scaledStart = boxCollider.start.multiply(transform.scale);
const scaledEnd = boxCollider.end.multiply(transform.scale);
width = scaledEnd.x - scaledStart.x;
height = scaledEnd.y - scaledStart.y;
// BoxCollider center relative to position
const offsetX = (scaledStart.x + scaledEnd.x) / 2;
const offsetY = (scaledStart.y + scaledEnd.y) / 2;
centerX = position.x + offsetX;
centerY = position.y + offsetY;
} else if (polygonCollider) {
// For polygon colliders, the position is already the center
// We use the AABB of the polygon for initial broad-phase check
width = polygonCollider.realWorldEnd.x - polygonCollider.realWorldStart.x;
height = polygonCollider.realWorldEnd.y - polygonCollider.realWorldStart.y;
centerX = (polygonCollider.realWorldStart.x + polygonCollider.realWorldEnd.x) / 2;
centerY = (polygonCollider.realWorldStart.y + polygonCollider.realWorldEnd.y) / 2;
// For rotated polygons, perform a point-in-polygon test
if (transform.rotation !== 0) {
return isPointInPolygon(mouseX, mouseY, polygonCollider.worldVertices);
}
} else if ((child as Renderer).width && (child as Renderer).height) {
// Check for width/height properties (e.g., AnimatedSprite, SpriteRender)
// These are rendered centered at position + width/2, height/2
width = (child as Renderer).width * transform.scale.x;
height = (child as Renderer).height * transform.scale.y;
centerX = position.x;
centerY = position.y;
} else {
// Fall back to superficial dimensions
width = (child?.superficialWidth || 50) * transform.scale.x;
height = (child?.superficialHeight || 50) * transform.scale.y;
centerX = position.x;
centerY = position.y;
}
if (child.type == "Button") {
console.log("BUTTON WH", width, height)
}
if (transform.rotation === 0) {
const left = centerX - width / 2;
const top = centerY - height / 2;
return mouseX >= left && mouseX <= left + width && mouseY >= top && mouseY <= top + height;
} else if (boxCollider) { // Only apply rotated box logic if it's a BoxCollider
const halfWidth = width / 2;
const halfHeight = height / 2;
const corners = [
{ x: -halfWidth, y: -halfHeight },
{ x: halfWidth, y: -halfHeight },
{ x: halfWidth, y: halfHeight },
{ x: -halfWidth, y: halfHeight },
];
const cos = Math.cos(transform.rotation);
const sin = Math.sin(transform.rotation);
const rotatedCorners = corners.map(corner => {
const rotatedX = corner.x * cos - corner.y * sin;
const rotatedY = corner.x * sin + corner.y * cos;
return {
x: centerX + rotatedX,
y: centerY + rotatedY
};
});
// Point-in-polygon test
let inside = false;
for (let i = 0, j = rotatedCorners.length - 1; i < rotatedCorners.length; j = i++) {
if (((rotatedCorners[i].y > mouseY) !== (rotatedCorners[j].y > mouseY)) &&
(mouseX < (rotatedCorners[j].x - rotatedCorners[i].x) * (mouseY - rotatedCorners[i].y) / (rotatedCorners[j].y - rotatedCorners[i].y) + rotatedCorners[i].x)) {
inside = !inside;
}
}
return inside;
}
return false;
}
export function vecEq(a: Vector, b: Vector): boolean {
return a.x === b.x && a.y === b.y;
}
export function pointInPoly(point: Point, poly: Point[]): boolean {
let inside = false;
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
const xi = poly[i].x, yi = poly[i].y;
const xj = poly[j].x, yj = poly[j].y;
// Check if the point is on the segment
const onSegment = (point.y - yi) * (xj - xi) === (point.x - xi) * (yj - yi) &&
(Math.min(xi, xj) <= point.x && point.x <= Math.max(xi, xj)) &&
(Math.min(yi, yj) <= point.y && point.y <= Math.max(yi, yj));
if (onSegment) {
return true; // Point is on the boundary
}
const intersect = ((yi > point.y) !== (yj > point.y))
&& (point.x < (xj - xi) * (point.y - yi) / (yj - yi) + xi);
if (intersect) inside = !inside;
}
return inside;
}