Skip to main content
rule CX Codex

object-pooling — Claude Code rule: object pools for Three.js

object-pooling — a rule that pushes the agent to reuse bullets, particles and NPCs from a pool instead of building and discarding meshes every frame.

MIT ★ 4,719 updated 2026-10-24

Install into Claude Code · Manually: put the files in place All methods and platforms ↓
.claude/rules/object-pooling.md
Open on GitHub

What object-pooling does

The rule hands the agent a pool pattern for Three.js scenes: an ObjectPool class that takes factory, reset and an initial size, with acquire and release, plus pre-warming while assets load. Projectiles, particles, spawned enemies and collectibles are the cases it names.

A working bullet-pool example ships in the same file. Pooled meshes share one geometry and material, hide through visible = false instead of leaving the scene, and go back to the pool once their position grows past 100. The anti-pattern section shows the other way: a fresh SphereGeometry and material per spawn inside setTimeout, never disposed, so memory keeps climbing.

Resetting on release is the part that bites. Leave userData.velocity untouched and the next bullet flies on the old vector. All examples are JavaScript for Three.js, so another engine needs its own version of the class.

What it helps with

  • reuse bullets instead of allocating a mesh per shot
  • keep the game loop free of garbage-collection hitches
  • cap scene memory with a bounded pool
  • pre-warm particle pools during loading
  • spot spawn code that leaks geometry and material

Example prompts for the agent

  • Build a bullet pool for the Three.js scene: pre-create 50 meshes sharing one geometry and material, hand them out with acquire, take them back with release.
  • Rework the particle spawner to follow the object-pooling rule: no new SphereGeometry or MeshBasicMaterial inside the game loop.
  • On release, clear userData.velocity and hide the mesh with visible = false.

How to install object-pooling

Manually: put the files in place

.claude/rules/object-pooling.md

The paths frontmatter field limits the files

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about object-pooling

How do I install object-pooling in Claude Code?

Add the rule file at .claude/rules/object-pooling.md in your project.

What does object-pooling do?

It gives the agent a concrete pool recipe: acquire and release, pre-warmed objects, shared geometry and material, so nothing is allocated per frame.

Why is creating meshes in setTimeout a problem?

Each call builds a new geometry and material, and removing the mesh from the scene leaves both in memory.

Source text

object-pooling.md · MIT
# Object Pooling

> Source: [100 Three.js Tips - Utsubo](https://www.utsubo.com/blog/threejs-best-practices-100-tips)

Object pooling prevents garbage collection pauses by reusing objects instead of creating/destroying them.

## When to Use

- Bullets, particles, projectiles
- Spawned enemies/NPCs
- Collectibles
- Any frequently created/destroyed objects

## Implementation

```javascript
class ObjectPool {
  constructor(factory, reset, initialSize = 20) {
    this.factory = factory;
    this.reset = reset;
    this.pool = [];

    // Pre-warm the pool
    for (let i = 0; i < initialSize; i++) {
      const obj = factory();
      obj.visible = false;
      this.pool.push(obj);
    }
  }

  acquire() {
    const obj = this.pool.pop() || this.factory();
    obj.visible = true;
    return obj;
  }

  release(obj) {
    this.reset(obj);
    obj.visible = false;
    this.pool.push(obj);
  }
}
```

## Example: Bullet Pool

```javascript
const bulletGeometry = new THREE.SphereGeometry(0.1);
const bulletMaterial = new THREE.MeshBasicMaterial({ color: 0xffff00 });

const bulletPool = new ObjectPool(
  // Factory: create new bullet
  () => {
    const bullet = new THREE.Mesh(bulletGeometry, bulletMaterial);
    scene.add(bullet);
    return bullet;
  },
  // Reset: return bullet to initial state
  (bullet) => {
    bullet.position.set(0, 0, 0);
    bullet.userData.velocity = null;
  },
  50 // Initial pool size
);

// Spawn bullet
function fireBullet(position, direction) {
  const bullet = bulletPool.acquire();
  bullet.position.copy(position);
  bullet.userData.velocity = direction.clone().multiplyScalar(10);
  activeBullets.add(bullet);
}

// Despawn bullet
function removeBullet(bullet) {
  activeBullets.delete(bullet);
  bulletPool.release(bullet);
}

// Update loop
function updateBullets(delta) {
  for (const bullet of activeBullets) {
    bullet.position.add(
      bullet.userData.velocity.clone().multiplyScalar(delta)
    );

    // Check bounds
    if (bullet.position.length() > 100) {
      removeBullet(bullet);
    }
  }
}
```

## Key Benefits

1. **No GC pauses** - Objects are reused, not collected
2. **Predictable memory** - Pool size is bounded
3. **Faster spawning** - No allocation overhead

## Best Practices

1. **Pre-warm pools** - Create objects during loading, not gameplay
2. **Share geometry/material** - All pooled objects use same resources
3. **Reset completely** - Clear all state when releasing
4. **Size appropriately** - Match pool size to max concurrent objects
5. **Use visibility** - Toggle `visible` instead of add/remove from scene

## Anti-Pattern

```javascript
// BAD: Creates garbage every frame
function spawnParticle() {
  const particle = new THREE.Mesh(
    new THREE.SphereGeometry(0.1), // New geometry!
    new THREE.MeshBasicMaterial() // New material!
  );
  scene.add(particle);

  setTimeout(() => {
    scene.remove(particle);
    // Memory leak: geometry/material not disposed
  }, 1000);
}
```

© zebbern · MIT · zebbern/claude-code-guide

Similar IDE rules

All IDE rules for Game dev and 3D: Unity, Unreal, Godot, Blender →

From the same set86

The whole set →
asset-compression Guides your AI coding agent through 3D asset compression for Three.js. Covers Draco, Meshopt, KTX2 textures, and LOD implementation. CX Codex +1 ★ 4,719repo stars perf-never-set-state-in-useframe perf-never-set-state-in-useframe — a react-three-fiber rule that bans setState inside useFrame and pushes you to mutate a ref instead, so animation stops triggering a React render every frame. CX Codex +1 ★ 4,719repo stars frame-delta-time frame-delta-time — a rule that makes every animated movement multiply by delta, so speed stops depending on the display's refresh rate. CX Codex +1 ★ 4,719repo stars draw-call-optimization The draw-call-optimization rule for Claude Code guides Three.js optimization, reducing draw calls to below 100 per frame through instancing, batching, and geometry merging. CX Codex +1 ★ 4,719repo stars shader-mobile The shader-mobile rule for Claude Code provides guidelines for optimizing GLSL and Three.js shaders for mobile GPUs to prevent framerate drops on mobile devices. CX Codex +1 ★ 4,719repo stars drei-use-gltf The drei-use-gltf rule guides GLTF loading through useGLTF, including caching and preloading. It fits React Three Fiber scenes that need model assets. CX Codex +1 ★ 4,719repo stars perf-zustand-selectors perf-zustand-selectors — a rule file that pushes the agent to subscribe components to individual Zustand slices instead of the whole store, so a component repaints only when the data it reads changes. CX Codex +1 ★ 4,719repo stars geometry-instanced-mesh geometry-instanced-mesh guides AI agents to use THREE.InstancedMesh instead of separate meshes for repeating 3D objects. CX Codex +1 ★ 4,719repo stars

Project sponsors

Companies that keep this analytics open