0.0.1 • Published 5 months ago

infernojs v0.0.1

Weekly downloads
-
License
MIT
Repository
-
Last release
5 months ago

pepperjs

A spicy, high-performance library for building 2D games in JavaScript.

Pepper - The Black Cat Mascot

Features

  • Efficient Collision Detection

    • Multiple collision detection strategies for different use cases
    • Support for circles, rectangles, polygons, and line segments
    • Spatial partitioning for optimal performance with large numbers of entities
    • Precise contact point and collision normal information
  • Future Additions (Coming Soon)

    • Efficient shape rendering
    • Input handling
    • Animation system
    • Simple physics
    • Game loop management
  • Developer-Friendly

    • Written in TypeScript with full type safety
    • Zero dependencies
    • Optimized for performance

Installation

npm install pepperjs

Usage: Collision Detection

Using Collision Detectors

import { BruteForceCollisionDetector, SpatialGridCollisionDetector } from "pepperjs";

// Create some entities
const entities = [
  {
    id: "circle1",
    type: "circle",
    shape: {
      center: { x: 100, y: 100 },
      radius: 50,
    },
  },
  {
    id: "rect1",
    type: "rectangle",
    shape: {
      position: { x: 300, y: 300 },
      width: 100,
      height: 100,
    },
  },
];

// Choose the appropriate detector for your use case
// BruteForce: Best for small number of entities or infrequent checks
const bruteForce = BruteForceCollisionDetector({ entities });

// SpatialGrid: Best for large number of entities and frequent checks
const spatialGrid = SpatialGridCollisionDetector({ 
  entities,
  cellSize: 64  // Optional: Size of grid cells (default: 64)
});

// Check collisions with a shape
const testCircle = {
  center: { x: 150, y: 150 },
  radius: 75,
};

// Get IDs of all entities that collide with the test shape
const collisions = spatialGrid.getCollisions(testCircle);
console.log(collisions); // ["circle1"]

Using the Legacy CollisionSystem

import { CollisionSystem, vec2 } from "pepperjs";

// Create a collision system
const physics = new CollisionSystem({
  cellSize: 64, // Size of spatial partitioning cells
  useBroadPhase: true, // Enable spatial partitioning for better performance
});

// Add a circle entity
const circleId = physics.addEntity({
  type: "circle",
  shape: {
    center: vec2(100, 100),
    radius: 50,
  },
});

// Add a rectangle entity
const rectId = physics.addEntity({
  type: "rectangle",
  shape: {
    position: vec2(120, 90),
    width: 80,
    height: 60,
  },
});

// Check for collisions
const collisions = physics.checkAllCollisions();

// Process collisions
for (const [pairKey, result] of collisions.entries()) {
  console.log(`Collision detected: ${pairKey}`);
  console.log(
    `Contact point: ${result.contacts[0].point.x}, ${result.contacts[0].point.y}`
  );
  console.log(
    `Normal: ${result.contacts[0].normal.x}, ${result.contacts[0].normal.y}`
  );
  console.log(`Penetration depth: ${result.contacts[0].depth}`);
}

Performance Optimization

The library uses several techniques to ensure high performance:

  1. Multiple collision detection strategies - Choose the right algorithm for your specific needs
  2. Spatial partitioning - Divides the world into grid cells to reduce the number of collision checks
  3. Broad-phase collision detection - Uses AABBs (Axis-Aligned Bounding Boxes) to quickly filter out non-colliding objects
  4. Optimized math operations - Uses squared distance calculations when possible to avoid costly square roots
  5. Efficient data structures - Uses Maps and Sets for fast lookups

Choosing the Right Collision Detector

PepperJS provides different collision detection strategies optimized for different scenarios:

  • BruteForceCollisionDetector: Checks every entity against the given shape

    • Best for small number of entities (< 100)
    • Best when you only need to check collisions occasionally
    • Simplest implementation with minimal overhead
  • SpatialGridCollisionDetector: Uses spatial partitioning to efficiently find potential collisions

    • Best for large number of entities (100+)
    • Best when entities are distributed across the space
    • Best when you need to check collisions frequently
    • Allows tuning the cell size for optimal performance

Roadmap

We're actively working on expanding pepperjs into a comprehensive 2D game development library. Here's what's coming:

Version 0.1.0 (Current)

  • ✅ High-performance collision detection
  • ✅ Spatial partitioning for efficient collision handling
  • ✅ Support for multiple shape types (circles, rectangles, polygons, line segments)

Version 0.2.0 (Planned)

  • 🔲 Canvas-based rendering system
  • 🔲 Shape drawing utilities
  • 🔲 Basic sprite support
  • 🔲 Performance optimizations for rendering

Version 0.3.0 (Planned)

  • 🔲 Input handling (keyboard, mouse, touch)
  • 🔲 Game loop management
  • 🔲 Time-based animation system

Version 0.4.0 (Planned)

  • 🔲 Simple physics engine (forces, gravity, etc.)
  • 🔲 Constraints and joints
  • 🔲 Integration with collision system

Version 0.5.0 (Planned)

  • 🔲 Entity-component system
  • 🔲 Particle systems
  • 🔲 Camera and viewport management

Future Additions

  • 🔲 WebGL renderer option
  • 🔲 Sound system
  • 🔲 Tile maps and level loading
  • 🔲 UI components

Examples

You can run the included examples to see the library in action:

# Basic collision detection example
npm run example

# Collision detectors comparison example
npm run example:detectors

Benchmarks

You can run performance benchmarks to test the library's collision detection performance:

npm run bench

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.

API Reference

CollisionSystem

The main class for handling collision detection.

// Create a new collision system
const system = new CollisionSystem({
  cellSize: 64, // Size of grid cells for spatial partitioning
  maxEntities: 1000, // Maximum number of entities (optional)
  useBroadPhase: true, // Whether to use spatial partitioning
});

// Add an entity and get its ID
const entityId = system.addEntity({
  type: "circle", // or 'rectangle', 'polygon', 'lineSegment'
  shape: {
    // Shape data here
  },
});

// Remove an entity
system.removeEntity(entityId);

// Update spatial partitioning (call after entities move)
system.updateSpatialPartitioning();

// Check for collisions and get results
const collisionResults = system.checkAllCollisions();

// Check collision between two specific entities
const result = system.checkCollision(entityA, entityB);

// Clear all entities
system.clear();

Shapes

The library supports several shape types:

Circle

const circle = {
  type: "circle",
  shape: {
    center: { x: 100, y: 100 },
    radius: 50,
  },
};

Rectangle

const rectangle = {
  type: "rectangle",
  shape: {
    position: { x: 100, y: 100 },
    width: 200,
    height: 150,
  },
};

Polygon

const polygon = {
  type: "polygon",
  shape: {
    points: [
      { x: 0, y: 0 },
      { x: 100, y: 0 },
      { x: 100, y: 100 },
      { x: 0, y: 100 },
    ],
  },
};

Line Segment

const lineSegment = {
  type: "lineSegment",
  shape: {
    start: { x: 0, y: 0 },
    end: { x: 100, y: 100 },
  },
};

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT