PolyDice

3D Physics Dice Roller
Loading physics engine…
Total 0
Rolling dice...
🎲
PolyDice Reference
API & ARCHITECTURE

🎲 System Overview

PolyDice is a high-performance, 100% self-contained JavaScript 3D polyhedral dice simulation library. It requires zero external image files or 3D asset downloads—all 9 polyhedral meshes, UV projections, and high-resolution normal maps with engraved numerals are synthesized mathematically at runtime.

Supported Polyhedral Dice

Die Geometry Faces Reading Rule
d4 Regular Tetrahedron 4 Equilateral Triangles Opposite apex (bottom face flat)
d6 Regular Hexahedron (Cube) 6 Squares Top face normal (+Y)
d8 Regular Octahedron 8 Equilateral Triangles Top face normal (+Y)
d10 Pentagonal Trapezohedron 10 Kites Top face normal (+Y)
d12 Regular Dodecahedron 12 Regular Pentagons Top face normal (+Y)
d14 Heptagonal Trapezohedron 14 Kites Top face normal (+Y)
d16 Octagonal Bipyramid 16 Isosceles Triangles Top face normal (+Y)
d20 Regular Icosahedron 20 Equilateral Triangles Top face normal (+Y)
d24 Deltoidal Icositetrahedron 24 Kites Top face normal (+Y)
d30 Rhombic Triacontahedron 30 Golden Rhombi (ratio φ) Top face normal (+Y)
d48 Disdyakis Dodecahedron 48 Scalene Triangles Top face normal (+Y)
d60 Pentakis Dodecahedron 60 Isosceles Triangles Top face normal (+Y)
d100 Zocchihedron (Dual Spherical Lattice) 100 Spherical Facets Top face normal (+Y)
d120 Disdyakis Triacontahedron 120 Scalene Triangles Top face normal (+Y)

Key Architectural Pillars

  • Procedural Engraving & Normal Mapping: A dynamic 2048² canvas renders centered numeral glyphs and runs a Sobel edge-detection height-to-normal gradient shader to produce tactile, engraved depth.
  • Optional Procedural Beveling / Chamfers: Procedural geometric chamfer engine generating edge quad strips and vertex corner cap polygons directly in 3D (Off: 0.0, Subtle: 0.05, Round: 0.10). Exported .glb models need no vertex-merging when imported into Blender or game engines!
  • Ammo.js Rigid Body Dynamics: Continuous Collision Detection (CCD), restitution bounce, rolling friction, and realistic relative polyhedral mass ratios.
  • Synthesized Positional Audio: Momentum-attenuated Web Audio sound synthesizer with distinct wood/felt low-end thuds and crisp micro-detuned die clacks.
  • Headless Predetermined Roll Replay: Pre-simulates rolls in ~4ms headless Ammo.js steps, applies local face transformation offset qOffset, and replays with 100% authentic tumbling physics without mid-air steering.
  • Multi-Row Showcase & GLTF Export: Lineup view with upright face camera alignment, luminous silhouette outlines, and binary .glb 3D model export.

⚡ JavaScript Module & API Specification

PolyDice is structured as a standalone, zero-asset ES6 module (polydice.js) taking THREE and Ammo dependencies in its constructor, with backward-compatible aliases on window.

1. ES6 Module Import & Constructor

import { PolyDice } from './polydice.js'; // Host creates Three.js Scene, Camera, Renderer, and Animation Loop const dice = new PolyDice({ THREE, // Three.js library instance Ammo: window.Ammo, // Ammo.js WebAssembly loader or instance ConvexHull, // Optional: Three.js ConvexHull addon GLTFExporter, // Optional: Three.js GLTFExporter addon scene, // Host Scene (dice.group mounts automatically) tray: { width: 12.0, depth: 12.0, wallHeight: 2.4 }, audio: true // Web Audio collision synthesizer toggle }); // Initialize Ammo physics world await dice.init(); // In host render loop: const timer = new THREE.Timer(); timer.connect(document); function animate() { requestAnimationFrame(animate); timer.update(); const deltaTime = Math.min(timer.getDelta(), 0.05); dice.update(deltaTime); // Steps physics, syncs meshes, updates audio renderer.render(scene, camera); }

2. Core Instance Methods

// Roll active pool with Promise resolution: const result = await dice.roll({ power: 1.2 }); console.log('Result:', result.total, result.summary); // Roll guaranteed predetermined outcome: await dice.rollPredeterminedDice(['d20'], [20], 1.0); // Generate standalone die mesh (usable anywhere in your scene or pedestal): const dieMesh = dice.createDieMesh('d20', { bevel: 0.20, material: 'ruby' }); // Listen to roll events: dice.on('rollComplete', (result) => console.log('Settled:', result)); // Set bevel and material presets: dice.setBevel(0.20, 4); // ratio, segments (immediately updates settled dice) dice.setDiceMaterial('gold'); // updates all active dice immediately in real-time dice.setDieMaterial(specificDie, 'obsidian'); // changes material of an individual die! dice.selectDie(specificDie); // highlights die with cyan aura outline // Clean teardown & memory management: dice.dispose(); // frees GPU VRAM & Ammo WASM C++ heap memory

3. Backward-Compatible Window Aliases & Events

// Global convenience bindings (for webhooks & quick console tests): window.rollDicePool(power = 1.0, targets = null); window.rollPredeterminedDice(diceTypes, targetValues, power = 1.0); window.parseTargetRollString('2d6: 6, 6'); window.diceEngine; // Access the active PolyDice instance // Trigger roll via DOM Event (e.g. from server WebSocket): window.dispatchEvent(new CustomEvent('serverDiceRoll', { detail: '2d6: 6, 6' })); // Listen for finished roll: window.addEventListener('diceRollComplete', (e) => console.log('Event Result:', e.detail));

4. Output JSON Schema

{ "timestamp": "2026-09-29T17:00:00.000Z", "total": 12, "diceCount": 2, "dice": [ { "id": 1, "type": "d6", "result": 6 }, { "id": 2, "type": "d6", "result": 6 } ], "breakdown": { "d6": [6, 6] }, "summary": "2d6: [6, 6] (12)" }

🤖 LLM / Agent Context Specification

This pre-formatted Markdown provides complete architectural, mathematical, and API context for ingestion into Large Language Model prompts, autonomous agents, and documentation generators.


        
⚙️
PolyDice Configurator & Integration Generator
DEVELOPER TOOL

Drop this snippet into your application, web game, or VTT to initialize PolyDice with your exact active pool, materials, and edge bevels:


        

Target roll strings allow webhooks, Discord bots, or server game backends to command predetermined roll outcomes:

Formats: "2d20: 20, 1" • "d20: 18; 2d6: 6, 5" • "d100: 99"
Engine method: diceEngine.rollPredeterminedDice(diceTypes, targetValues, power)

Inspect or edit your active configuration JSON below. Click Apply Config to Scene to instantly re-theme and reconfigure the live simulation:

Machine-Parsable Roll Data (JSON)
{}
Ready to roll
🎒 0
Dice Bag
Drag die here
📥
Drop JSON to Import Dice Bag
Release the file anywhere to append custom polyhedral dice to your local collection
Die Options
🎲 Spawn This Die
📦 Spawn Preset ▸
🗑️ Remove from Bag
👀 Viewing: Remote Player's Tray