infernojs 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,320 @@
1
+ # pepperjs
2
+
3
+ A spicy, high-performance library for building 2D games in JavaScript.
4
+
5
+ ![Pepper - The Black Cat Mascot](./assets/pepper-logo.svg)
6
+
7
+ ## Features
8
+
9
+ - **Efficient Collision Detection**
10
+
11
+ - Multiple collision detection strategies for different use cases
12
+ - Support for circles, rectangles, polygons, and line segments
13
+ - Spatial partitioning for optimal performance with large numbers of entities
14
+ - Precise contact point and collision normal information
15
+
16
+ - **Future Additions** (Coming Soon)
17
+
18
+ - Efficient shape rendering
19
+ - Input handling
20
+ - Animation system
21
+ - Simple physics
22
+ - Game loop management
23
+
24
+ - **Developer-Friendly**
25
+ - Written in TypeScript with full type safety
26
+ - Zero dependencies
27
+ - Optimized for performance
28
+
29
+ ## Installation
30
+
31
+ ```bash
32
+ npm install pepperjs
33
+ ```
34
+
35
+ ## Usage: Collision Detection
36
+
37
+ ### Using Collision Detectors
38
+
39
+ ```typescript
40
+ import { BruteForceCollisionDetector, SpatialGridCollisionDetector } from "pepperjs";
41
+
42
+ // Create some entities
43
+ const entities = [
44
+ {
45
+ id: "circle1",
46
+ type: "circle",
47
+ shape: {
48
+ center: { x: 100, y: 100 },
49
+ radius: 50,
50
+ },
51
+ },
52
+ {
53
+ id: "rect1",
54
+ type: "rectangle",
55
+ shape: {
56
+ position: { x: 300, y: 300 },
57
+ width: 100,
58
+ height: 100,
59
+ },
60
+ },
61
+ ];
62
+
63
+ // Choose the appropriate detector for your use case
64
+ // BruteForce: Best for small number of entities or infrequent checks
65
+ const bruteForce = BruteForceCollisionDetector({ entities });
66
+
67
+ // SpatialGrid: Best for large number of entities and frequent checks
68
+ const spatialGrid = SpatialGridCollisionDetector({
69
+ entities,
70
+ cellSize: 64 // Optional: Size of grid cells (default: 64)
71
+ });
72
+
73
+ // Check collisions with a shape
74
+ const testCircle = {
75
+ center: { x: 150, y: 150 },
76
+ radius: 75,
77
+ };
78
+
79
+ // Get IDs of all entities that collide with the test shape
80
+ const collisions = spatialGrid.getCollisions(testCircle);
81
+ console.log(collisions); // ["circle1"]
82
+ ```
83
+
84
+ ### Using the Legacy CollisionSystem
85
+
86
+ ```typescript
87
+ import { CollisionSystem, vec2 } from "pepperjs";
88
+
89
+ // Create a collision system
90
+ const physics = new CollisionSystem({
91
+ cellSize: 64, // Size of spatial partitioning cells
92
+ useBroadPhase: true, // Enable spatial partitioning for better performance
93
+ });
94
+
95
+ // Add a circle entity
96
+ const circleId = physics.addEntity({
97
+ type: "circle",
98
+ shape: {
99
+ center: vec2(100, 100),
100
+ radius: 50,
101
+ },
102
+ });
103
+
104
+ // Add a rectangle entity
105
+ const rectId = physics.addEntity({
106
+ type: "rectangle",
107
+ shape: {
108
+ position: vec2(120, 90),
109
+ width: 80,
110
+ height: 60,
111
+ },
112
+ });
113
+
114
+ // Check for collisions
115
+ const collisions = physics.checkAllCollisions();
116
+
117
+ // Process collisions
118
+ for (const [pairKey, result] of collisions.entries()) {
119
+ console.log(`Collision detected: ${pairKey}`);
120
+ console.log(
121
+ `Contact point: ${result.contacts[0].point.x}, ${result.contacts[0].point.y}`
122
+ );
123
+ console.log(
124
+ `Normal: ${result.contacts[0].normal.x}, ${result.contacts[0].normal.y}`
125
+ );
126
+ console.log(`Penetration depth: ${result.contacts[0].depth}`);
127
+ }
128
+ ```
129
+
130
+ ## Performance Optimization
131
+
132
+ The library uses several techniques to ensure high performance:
133
+
134
+ 1. **Multiple collision detection strategies** - Choose the right algorithm for your specific needs
135
+ 2. **Spatial partitioning** - Divides the world into grid cells to reduce the number of collision checks
136
+ 3. **Broad-phase collision detection** - Uses AABBs (Axis-Aligned Bounding Boxes) to quickly filter out non-colliding objects
137
+ 4. **Optimized math operations** - Uses squared distance calculations when possible to avoid costly square roots
138
+ 5. **Efficient data structures** - Uses Maps and Sets for fast lookups
139
+
140
+ ## Choosing the Right Collision Detector
141
+
142
+ PepperJS provides different collision detection strategies optimized for different scenarios:
143
+
144
+ - **BruteForceCollisionDetector**: Checks every entity against the given shape
145
+ - Best for small number of entities (< 100)
146
+ - Best when you only need to check collisions occasionally
147
+ - Simplest implementation with minimal overhead
148
+
149
+ - **SpatialGridCollisionDetector**: Uses spatial partitioning to efficiently find potential collisions
150
+ - Best for large number of entities (100+)
151
+ - Best when entities are distributed across the space
152
+ - Best when you need to check collisions frequently
153
+ - Allows tuning the cell size for optimal performance
154
+
155
+ ## Roadmap
156
+
157
+ We're actively working on expanding pepperjs into a comprehensive 2D game development library. Here's what's coming:
158
+
159
+ ### Version 0.1.0 (Current)
160
+
161
+ - ✅ High-performance collision detection
162
+ - ✅ Spatial partitioning for efficient collision handling
163
+ - ✅ Support for multiple shape types (circles, rectangles, polygons, line segments)
164
+
165
+ ### Version 0.2.0 (Planned)
166
+
167
+ - 🔲 Canvas-based rendering system
168
+ - 🔲 Shape drawing utilities
169
+ - 🔲 Basic sprite support
170
+ - 🔲 Performance optimizations for rendering
171
+
172
+ ### Version 0.3.0 (Planned)
173
+
174
+ - 🔲 Input handling (keyboard, mouse, touch)
175
+ - 🔲 Game loop management
176
+ - 🔲 Time-based animation system
177
+
178
+ ### Version 0.4.0 (Planned)
179
+
180
+ - 🔲 Simple physics engine (forces, gravity, etc.)
181
+ - 🔲 Constraints and joints
182
+ - 🔲 Integration with collision system
183
+
184
+ ### Version 0.5.0 (Planned)
185
+
186
+ - 🔲 Entity-component system
187
+ - 🔲 Particle systems
188
+ - 🔲 Camera and viewport management
189
+
190
+ ### Future Additions
191
+
192
+ - 🔲 WebGL renderer option
193
+ - 🔲 Sound system
194
+ - 🔲 Tile maps and level loading
195
+ - 🔲 UI components
196
+
197
+ ## Examples
198
+
199
+ You can run the included examples to see the library in action:
200
+
201
+ ```bash
202
+ # Basic collision detection example
203
+ npm run example
204
+
205
+ # Collision detectors comparison example
206
+ npm run example:detectors
207
+ ```
208
+
209
+ ## Benchmarks
210
+
211
+ You can run performance benchmarks to test the library's collision detection performance:
212
+
213
+ ```bash
214
+ npm run bench
215
+ ```
216
+
217
+ This will run a series of benchmarks with different configurations, allowing you to see how the library performs with different numbers of entities and different collision detection strategies.
218
+
219
+ ## API Reference
220
+
221
+ ### CollisionSystem
222
+
223
+ The main class for handling collision detection.
224
+
225
+ ```typescript
226
+ // Create a new collision system
227
+ const system = new CollisionSystem({
228
+ cellSize: 64, // Size of grid cells for spatial partitioning
229
+ maxEntities: 1000, // Maximum number of entities (optional)
230
+ useBroadPhase: true, // Whether to use spatial partitioning
231
+ });
232
+
233
+ // Add an entity and get its ID
234
+ const entityId = system.addEntity({
235
+ type: "circle", // or 'rectangle', 'polygon', 'lineSegment'
236
+ shape: {
237
+ // Shape data here
238
+ },
239
+ });
240
+
241
+ // Remove an entity
242
+ system.removeEntity(entityId);
243
+
244
+ // Update spatial partitioning (call after entities move)
245
+ system.updateSpatialPartitioning();
246
+
247
+ // Check for collisions and get results
248
+ const collisionResults = system.checkAllCollisions();
249
+
250
+ // Check collision between two specific entities
251
+ const result = system.checkCollision(entityA, entityB);
252
+
253
+ // Clear all entities
254
+ system.clear();
255
+ ```
256
+
257
+ ### Shapes
258
+
259
+ The library supports several shape types:
260
+
261
+ #### Circle
262
+
263
+ ```typescript
264
+ const circle = {
265
+ type: "circle",
266
+ shape: {
267
+ center: { x: 100, y: 100 },
268
+ radius: 50,
269
+ },
270
+ };
271
+ ```
272
+
273
+ #### Rectangle
274
+
275
+ ```typescript
276
+ const rectangle = {
277
+ type: "rectangle",
278
+ shape: {
279
+ position: { x: 100, y: 100 },
280
+ width: 200,
281
+ height: 150,
282
+ },
283
+ };
284
+ ```
285
+
286
+ #### Polygon
287
+
288
+ ```typescript
289
+ const polygon = {
290
+ type: "polygon",
291
+ shape: {
292
+ points: [
293
+ { x: 0, y: 0 },
294
+ { x: 100, y: 0 },
295
+ { x: 100, y: 100 },
296
+ { x: 0, y: 100 },
297
+ ],
298
+ },
299
+ };
300
+ ```
301
+
302
+ #### Line Segment
303
+
304
+ ```typescript
305
+ const lineSegment = {
306
+ type: "lineSegment",
307
+ shape: {
308
+ start: { x: 0, y: 0 },
309
+ end: { x: 100, y: 100 },
310
+ },
311
+ };
312
+ ```
313
+
314
+ ## Contributing
315
+
316
+ Contributions are welcome! Please feel free to submit a Pull Request.
317
+
318
+ ## License
319
+
320
+ MIT
@@ -0,0 +1,211 @@
1
+ import { Entity, Shape, Circle, Point, Rectangle } from './types.mjs';
2
+ export { AABB, CollisionConfig, CollisionResult, ContactPoint, ShapeType, Vector2D } from './types.mjs';
3
+ export { aabbIntersect, add, cellToId, circleToAABB, cross, distance, distanceSquared, dot, length, lengthSquared, normalize, positionToCell, rectToAABB, scale, subtract, vec2 } from './utils.mjs';
4
+
5
+ /**
6
+ * Base class for collision detectors that implements common functionality
7
+ */
8
+ declare abstract class BaseCollisionDetector {
9
+ /**
10
+ * The entities to check collisions against
11
+ */
12
+ protected entities: Entity[];
13
+ /**
14
+ * Create a new collision detector
15
+ * @param entities The entities to check collisions against
16
+ */
17
+ constructor(entities: Entity[]);
18
+ /**
19
+ * Get all entities that collide with the given shape
20
+ * @param shape The shape to check collisions against
21
+ * @returns Array of entity IDs that collide with the shape
22
+ */
23
+ abstract getCollisions(shape: Shape): (string | number)[];
24
+ }
25
+
26
+ /**
27
+ * Collision detector that uses a brute force approach
28
+ * Checks every entity against the given shape
29
+ *
30
+ * Best used when:
31
+ * - You have a small number of entities
32
+ * - You only need to check collisions occasionally
33
+ * - You want the simplest implementation
34
+ */
35
+ declare function BruteForceCollisionDetector({ entities, }: {
36
+ entities: Entity[];
37
+ }): BruteForceCollisionDetectorImpl;
38
+ declare class BruteForceCollisionDetectorImpl extends BaseCollisionDetector {
39
+ /**
40
+ * Get all entities that collide with the given shape
41
+ * @param shape The shape to check collisions against
42
+ * @returns Array of entity IDs that collide with the shape
43
+ */
44
+ getCollisions(shape: Shape): (string | number)[];
45
+ }
46
+
47
+ /**
48
+ * Configuration options for the spatial grid collision detector
49
+ */
50
+ interface SpatialGridConfig {
51
+ /** Size of each grid cell */
52
+ cellSize: number;
53
+ }
54
+ /**
55
+ * Collision detector that uses spatial partitioning for efficient collision detection
56
+ *
57
+ * Best used when:
58
+ * - You have a large number of entities
59
+ * - Entities are distributed across the space
60
+ * - You need to check collisions frequently
61
+ */
62
+ declare function SpatialGridCollisionDetector({ entities, cellSize, }: {
63
+ entities: Entity[];
64
+ cellSize?: number;
65
+ }): SpatialGridCollisionDetectorImpl;
66
+ declare class SpatialGridCollisionDetectorImpl extends BaseCollisionDetector {
67
+ /** The spatial hash grid for quick lookups */
68
+ private grid;
69
+ /** Configuration for the spatial grid */
70
+ private config;
71
+ /**
72
+ * Create a new spatial grid collision detector
73
+ */
74
+ constructor(entities: Entity[], config: SpatialGridConfig);
75
+ /**
76
+ * Get all entities that collide with the given shape
77
+ */
78
+ getCollisions(shape: Shape): (string | number)[];
79
+ /**
80
+ * Rebuild the spatial grid with the current entities
81
+ */
82
+ rebuildGrid(): void;
83
+ /**
84
+ * Insert an entity into the spatial grid
85
+ */
86
+ private insertEntityIntoGrid;
87
+ /**
88
+ * Get all cells that an AABB overlaps
89
+ */
90
+ private getCellsForAABB;
91
+ /**
92
+ * Get the AABB for an entity
93
+ */
94
+ private getAABB;
95
+ /**
96
+ * Get the AABB for a shape
97
+ */
98
+ private getAABBForShape;
99
+ }
100
+
101
+ /**
102
+ * Check if two entities are colliding
103
+ * @param shapeA First shape
104
+ * @param shapeB Second shape
105
+ * @returns True if the shapes are colliding
106
+ */
107
+ declare function checkShapeCollision(shapeA: Shape, shapeB: Shape): boolean;
108
+
109
+ /**
110
+ * Style options for rendering shapes
111
+ */
112
+ type ShapeStyle = {
113
+ /** Fill color (CSS color string) */
114
+ fillColor?: string;
115
+ /** Stroke color (CSS color string) */
116
+ strokeColor?: string;
117
+ /** Stroke width in pixels */
118
+ strokeWidth?: number;
119
+ /** Alpha/opacity (0-1) */
120
+ alpha?: number;
121
+ /** Shadow blur radius */
122
+ shadowBlur?: number;
123
+ /** Shadow color */
124
+ shadowColor?: string;
125
+ /** Shadow offset X */
126
+ shadowOffsetX?: number;
127
+ /** Shadow offset Y */
128
+ shadowOffsetY?: number;
129
+ };
130
+ /**
131
+ * A renderable entity with shape and style
132
+ */
133
+ type RenderableShape = {
134
+ shape: Shape;
135
+ style: ShapeStyle;
136
+ };
137
+ /**
138
+ * Configuration options for the renderer
139
+ */
140
+ type RendererOptions = {
141
+ /** Background color of the canvas */
142
+ backgroundColor?: string;
143
+ /** Default style to apply to shapes without specific styling */
144
+ defaultStyle?: ShapeStyle;
145
+ /** Whether to clear the canvas before each render */
146
+ clearBeforeRender?: boolean;
147
+ };
148
+
149
+ /**
150
+ * Apply style settings to the canvas context
151
+ */
152
+ declare function applyStyle(ctx: CanvasRenderingContext2D, style: ShapeStyle): void;
153
+ /**
154
+ * Restore the canvas context to its previous state
155
+ */
156
+ declare function restoreContext(ctx: CanvasRenderingContext2D): void;
157
+ /**
158
+ * Render a circle shape
159
+ */
160
+ declare function renderCircle(ctx: CanvasRenderingContext2D, circle: Circle, style: ShapeStyle): void;
161
+ /**
162
+ * Render a point shape
163
+ */
164
+ declare function renderPoint(ctx: CanvasRenderingContext2D, point: Point, style: ShapeStyle): void;
165
+ /**
166
+ * Render a rectangle shape
167
+ */
168
+ declare function renderRectangle(ctx: CanvasRenderingContext2D, rectangle: Rectangle, style: ShapeStyle): void;
169
+ /**
170
+ * Render any shape based on its type
171
+ */
172
+ declare function renderShape(ctx: CanvasRenderingContext2D, shape: Shape, style: ShapeStyle): void;
173
+ /**
174
+ * Main renderer function to render multiple shapes
175
+ */
176
+ declare function renderShapes(ctx: CanvasRenderingContext2D, shapes: RenderableShape[], options: RendererOptions): void;
177
+
178
+ /**
179
+ * pepperjs
180
+ * A spicy, high-performance library for building 2D games in JavaScript
181
+ *
182
+ * @packageDocumentation
183
+ */
184
+
185
+ declare const VERSION = "0.0.1";
186
+ /**
187
+ * @internal
188
+ * Rendering capabilities
189
+ */
190
+ declare const Renderer: {
191
+ notImplemented: boolean;
192
+ info: string;
193
+ };
194
+ /**
195
+ * @internal
196
+ * Future game loop management API
197
+ */
198
+ declare const GameLoop: {
199
+ notImplemented: boolean;
200
+ info: string;
201
+ };
202
+ /**
203
+ * @internal
204
+ * Future input handling API
205
+ */
206
+ declare const Input: {
207
+ notImplemented: boolean;
208
+ info: string;
209
+ };
210
+
211
+ export { BaseCollisionDetector, BruteForceCollisionDetector, Circle, Entity, GameLoop, Input, Point, Rectangle, Renderer, Shape, SpatialGridCollisionDetector, type SpatialGridConfig, VERSION, applyStyle, checkShapeCollision, renderCircle, renderPoint, renderRectangle, renderShape, renderShapes, restoreContext };