# melonjs-3d

Adopt this skill: https://proskills.md/skills/other/melonjs-melonjs-packages-melonjs-skills-melonjs-3d

Page: https://proskills.md/skills/other/melonjs-melonjs-packages-melonjs-skills-melonjs-3d
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: packages/melonjs/skills/melonjs-3d/SKILL.md
size: 81303
sha: 042b7bd5d3f4e30665a027745b565b5edb73a1c9
upstream: https://github.com/melonjs/melonjs/blob/master/packages/melonjs/skills/melonjs-3d/SKILL.md
truncated: true

````text
---
name: melonjs-3d
description: "Use this skill for anything 3D or 2.5D in melonJS — Camera3d, Mesh, InstancedMesh, Sprite3d billboards, Light3d, ground shadows, glTF/GLB scenes, and depth sorting. Covers the Y-down/+Z-forward convention (OpenGL's inverse), the cameraClass opt-in, orthographic (isometric) projection, clip planes, and the Canvas fallback's limits. Triggers on: Camera3d, toon, cel shading, toonBands, outlineWidth, outlineMode, rimLight, orthographic, isometric, orthoHeight, orthoWidth, projection, Mesh, InstancedMesh, Sprite3d, Trail3d, Light3d, billboard, glTF, glb, 3D, 2.5D, depth, cameraClass, fov, setClipPlanes, setFog, fog, heightFalloff, transparent, transparency, blendMode, castGroundShadow, shadowGroundPoint, lit, emissive, specular, shininess, normalMap, alphaCutoff, depthTest, vertexColors, worldToScreen, screenToRay, screenToWorld, pick, pickable, Ray3d, intersectRay, hit3d, followOffset, setBasis, getBasis, lookAt, orbit, up vector, gimbal, slerp, turn a direction, physics, rapier3d, Capsule3d, TriangleMesh3d."
license: MIT
---

# 3D and 2.5D in melonJS

> melonJS is a 2D engine that grew a real 3D tier: perspective cameras, meshes,
> instancing, glTF scenes and 3D lights. Most of what a model "knows" about 3D
> graphics comes from the OpenGL convention, and **melonJS's is the inverse**.
> Read the conventions section before writing any 3D code.

## Coordinate conventions — the inverse of OpenGL

This is the single most important thing on this page.

| | melonJS | OpenGL convention |
|---|---|---|
| vertical | **Y-down** — higher `y` is *lower* on screen | Y-up |
| depth | **+Z forward** — higher `z` is *farther* away | −Z forward |

`Camera3d` exposes three rotation angles: `camera.pitch`
(X, look up/down), `camera.yaw` (Y, look left/right) and `camera.roll` (Z, bank
the horizon). The view is `R(yaw) ∘ R(pitch) ∘ R(roll)` inverted, and the frustum
planes come off that same matrix — so culling follows a banked view.

The basis those angles produce is **readable and writable**: `getBasis(right,
up, forward)` reads it, `setBasis(right, up, forward)` poses the camera from
one.

`camera.rotate()` is NOT the way to bank a 3D camera. It writes the inherited
`currentTransform`, which a 3D view never reads, so the call is silently inert.
Set `roll`. (On a `Camera2d` it is the other way round: roll IS that transform's
rotation, which is why `worldToLocal` / `localToWorld` compensate for it.)

The payoff is that 2D code translates directly — anywhere you used `pos.x` /
`pos.y`, add `pos.z` and the maths still holds. The cost is that every
OpenGL-shaped instinct is backwards.

**Consequence that bites immediately:** "behind everything" is the *largest*
depth when the camera looks along +Z. Put a backdrop on the wrong side and it
either paints over the whole scene (it is nearer than everything else) or
disappears without trace (it falls in front of the near plane and the GPU clips
it). Which sign means "far" depends on which side the camera sits, so check the
camera before picking a backdrop depth.

glTF assets are authored Y-up right-handed. `level.load` converts them by
rotation (`rightHanded: true` is its default), so you do not apply a flip
yourself. The **`Mesh` constructor defaults `rightHanded` to `false`**, which
bridges by mirroring instead — geometry you hand to a `Mesh` directly comes in
flipped left/right unless you pass `rightHanded: true`. See
`melonjs-3d-assets`.

## Opting in

3D starts with the camera class, and nothing else has to change. Set it once on
the `Application`:

```js
import { Application, Camera3d } from "melonjs";

const app = new Application(1024, 768, {
    parent: "screen",
    cameraClass: Camera3d,      // ← the opt-in
});
await app.init();
```

That flips the world's sort to `"depth"`, switches the broadphase to a 3D index,
and renders sprites and meshes with perspective projection. `Camera3d` extends
`Camera2d`, so follow, fade, shake and post effects all still work (follow with
a difference, see the camera traps).

### Keep the camera, do not fish it back out

`app.viewport` is the **active stage's** default camera, so it is typed
`Camera2d`: a stage overrides the application's `cameraClass`, and the
built-in loading screen does exactly that. Reading your `Camera3d` back out of
it therefore needs a cast, and a cast that is wrong while the loader is up:

```js
const camera = app.viewport as Camera3d;   // works, until it does not
```

Own it instead. Pass the camera in and keep the typed reference, and nothing
downstream ever narrows:

```js
class GameStage extends Stage {
    readonly camera: Camera3d;

    constructor(app) {
        const camera = new Camera3d(0, 0, app.renderer.width, app.renderer.height);
        super({ cameras: [camera] });
        this.camera = camera;
    }
}
```

A freshly built camera is named `"default"`, and a stage registers its
`cameras` by name, so this IS the stage's default camera: `app.viewport`
returns the same instance.

### The two patterns differ in LIFETIME, and that decides which you want

This is the part that bites. `cameraClass` builds a **fresh camera for each
stage**, which the engine does deliberately so "Camera3d state shouldn't
bleed across stages". An owned camera passed through `super({ cameras })` is
built once and lives as long as the stage object, which for a stage you
register with `state.set()` means as long as the application.

So anything you attach to the camera now outlives the visit:

```js
// in onResetEvent — runs EVERY time the stage is entered
app.viewport.addPostEffect(bloom);
```

With `cameraClass` that lands on a fresh camera each time and is harmless.
With an owned camera it stacks: a second bloom on the second visit, a third
on the third. The symptom is text and edges appearing to double or smear,
because the scene is being post-processed once per accumulated effect.

Note that `removePostEffect` DESTROYS the effect rather than detaching it, so
"just remove it on the way out" is not a free undo.

**Choose on lifetime, not on typing:**

| your effects / camera state are | use |
|---|---|
| set up per stage visit, in `onResetEvent` | `cameraClass` — fresh camera per stage |
| set up once, in the stage constructor | an owned camera in `super({ cameras })` |

If you want the typed reference but your setup is per-visit, keep
`cameraClass` and narrow once on reset:

```js
override onResetEvent(app) {
    const viewport = app.viewport;
    if (!(viewport instanceof Camera3d)) {
        throw new Error("this stage needs a Camera3d");
    }
    this.camera = viewport;   // typed, checked, and still fresh per visit
}
```

That is what the Earth Defender example does, and why: it attaches post
effects on every reset and never removes them.

Narrowing beats asserting wherever you read the shared slot: the language
verifies `instanceof`, and fails loudly if the application was never given a
`cameraClass`, where a cast fails silently at the first 3D call.

Per-stage opt-in also works, which is useful when the loading screen is 2D:

```js
class GameStage extends Stage {
    constructor() {
        super({ cameras: [new Camera3d(0, 0, 1024, 768, { fov: Math.PI / 3 })] });
    }
}
```

## Camera traps

- **There is no sky.** The frame clears to `renderer.backgroundColor` (opaque
  black unless the renderer was created transparent), and `world.backgroundColor`
  clears over it when you set one — both are flat colours. Anything more is a
  backdrop renderable, screen-fixed or placed at a far depth.
- **Set the clip planes for your scene scale.** Defaults are near 0.1 / far 1000.
  Objects beyond the far plane clip or project with bad w-divides; a `near` that
  is too small wastes depth precision and distant props z-fight. Use
  `camera.setClipPlanes(near, far)`.
- **`camera.pos.set(x, y)` is 2-argument and zeroes z.** Use
  `camera.setPosition(x, y, z)`, which leaves the depth untouched when `z` is
  omitted; `camera.depth` is the z accessor i
````

## File: README.md
upstream: https://github.com/melonjs/melonjs/blob/master/README.md

```text
melonJS 2
=========
![melonJS: fast & light 2D & 3D games for the web, running on WebGPU, WebGL 2 or Canvas](https://github.com/melonjs/melonJS/raw/master/media/readme/hero.webp)

[![Build Status](https://github.com/melonjs/melonJS/actions/workflows/main.yml/badge.svg)](https://github.com/melonjs/melonJS/actions/workflows/main.yml)
[![NPM Package](https://img.shields.io/npm/v/melonjs)](https://www.npmjs.com/package/melonjs)
[![NPM Downloads](https://img.shields.io/npm/dm/melonjs)](https://www.npmjs.com/package/melonjs)
[![Build Size](https://img.shields.io/bundlejs/size/melonjs?label=minzip)](https://bundlejs.com/?q=melonjs)
[![jsDelivr](https://data.jsdelivr.com/v1/package/npm/melonjs/badge?style=rounded)](https://www.jsdelivr.com/package/npm/melonjs)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE.md)
[![Discord](https://img.shields.io/discord/608636676461428758?color=7289da&label=discord)](https://discord.gg/aur7JMk)
[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg)](CODE_OF_CONDUCT.md)

A modern & fully featured HTML5 game engine
-------------------------------------------------------------------------------
[melonJS](https://melonjs.org/) is an open-source 2D & 3D game engine designed for indie developers — perspective and orthogonal cameras, GPU-accelerated tilemap rendering, post-processing effects, custom shaders, 3D mesh support, polygon-accurate physics, modern Tiled workflows, and high performance. Runs on WebGPU, WebGL 2 or Canvas2D with automatic fallback. The whole engine is ~300 KB minzipped of vanilla JS/TS, with no dependencies and no toolchain lock-in. Built with modern class syntax and bundled with [esbuild](https://esbuild.github.io).

[melonJS](https://melonjs.org/) is licensed under the [MIT License](LICENSE.md) and actively maintained by the team at AltByte in Singapore.

Why melonJS
-------------------------------------------------------------------------------

melonJS is designed so you can **focus on making games, not on graphics plumbing**.

- **[Canvas2D-inspired rendering API](https://github.com/melonjs/melonJS/wiki/Rendering-API)** — If you've used the HTML5 Canvas, you already know melonJS. The rendering API (`save`, `restore`, `translate`, `rotate`, `setColor`, `fillRect`, ...) follows the same familiar patterns — no render graphs, no shader pipelines, no instruction sets to learn.

- **True renderer abstraction** — Write your game once, run it on WebGPU, WebGL 2 or Canvas2D with zero code changes. The engine handles all GPU complexity behind a unified API: the default `AUTO` mode tries WebGPU first at startup, falls back to WebGL 2 if that is unavailable, and ultimately to Canvas, and the entire feature set renders identically on both GPU backends.

- **Complete engine, minimal footprint** — Physics, tilemaps, audio, input, cameras, tweens, particles, UI — a full game stack in a single tree-shakeable ES module. No dependency sprawl, no library stitching.

- **Scenes, loaded in one call** — `level.load(name)` brings an authored scene straight into your world. [Tiled](https://www.mapeditor.org) is a first-class citizen for **2D** — orthogonal, isometric, hexagonal & staggered maps, all four rendered on the GPU (a whole tile layer in a single draw, on WebGPU and WebGL 2), animated tilesets, collision shapes, object properties, compressed formats — and **glTF / GLB** is the equivalent for **3D scenes**: author in Blender (or any DCC tool), export a `.glb`, and the whole scene — meshes, materials, cameras, lights, and node animation — loads under a `Camera3d`, no per-mesh wiring. Animated models play back through the same animation API as a 2D `Sprite`.

- **Batteries included, hackable by design** — Get started in minutes with minimal setup. When you need to go deeper: modern class-based architecture, a plugin system for engine extensions, and a clean architecture that's easy to extend without fighting the framework.

About melonJS
-------------------------------------------------------------------------------

[melonJS](https://melonjs.org/) is a fully featured game engine :

Compatibility
- Standalone library (does not rely on anything else, except a HTML5 capable browser)
- Compatible with all major browsers (Chrome, Safari, Firefox, Opera, Edge) and mobile devices

Graphics
- Fast GPU renderers (WebGPU and WebGL 2) for desktop and mobile devices, with fallback to Canvas rendering
- Since 20.0 the aging WebGL 1 path is retired and WebGL 2 is the baseline; devices offering only WebGL 1 fall back to the Canvas renderer under `AUTO`
- Extensible batcher system for custom rendering pipelines, with backend-neutral vertex formats and draw topologies (declare a layout once, describe it to either GPU backend)
- High DPI resolution & Canvas advanced auto scaling
- Sprite with 9-slice scaling option and frame animation (with per-frame callbacks)
- `Sprite3d` billboards, turning to face a `Camera3d` (cylindrical or spherical), for 2.5D characters and props
- Built-in effects such as tinting, masking, and the full set of CSS-style blend modes (normal, none, additive, multiply, screen, exclusion, darken, lighten, overlay, hard-light, color-dodge, color-burn, soft-light, difference) — supported identically on WebGPU, WebGL 2 and Canvas since 20.2, except `none`, which Canvas cannot do and draws as `normal`
- Standard spritesheet, single and multiple Packed Textures support
- Compressed texture support (DDS, KTX, KTX2, PVR, PKM) with automatic format detection and fallback
- Hardware antialiasing (`antiAlias: true`) on both GPU backends — and it survives post-processing, since the offscreen targets a post-effect chain renders into are multisampled to match
- Procedural noise textures: `Noise` (simplex/perlin/value/cellular, fBm / ridged / ping-pong fractal, domain warp; renderer-free and CPU-samplable for heightmaps, terrain, and spawn jitter) and `NoiseTexture2d` — bake a noise field into a sprite image, a `Gradient` color ramp, or a live-animated tangent-space normal map for lit water and surfaces; unified under a new `Texture2d` base alongside `TextureAtlas`
- 3D mesh rendering with OBJ/MTL model loading, multi-material support, hardware depth testing, and perspective projection via `Camera3d` — retained-mode geometry, uploaded to the GPU once and re-drawn from there, so moving, rotating, scaling or re-tinting a mesh costs no vertex upload and no per-vertex CPU work at all. 3D is built for the GPU backends; the Canvas fallback still draws a mesh under a 2D camera, as a last resort
- Mipmapped and anisotropically-filtered mesh textures on both GPU backends, so distant and grazing-angle geometry stops shimmering (opt out per mesh with `textureFilter: "nearest"` for crisp pixel-art models)
- Crisp or smooth, application-wide: `textureFilter` (`"nearest"`, `"linear"`, or `"linear-mipmap"`, which mipmaps sprites, text and tile layers too), and integer scaling with letterboxing (`scaleRounding: "integer"`) for pixel art
- 3D mesh materials: tangent-space normal maps, specular, emissive, alpha cutout, per-vertex colors, toon (cel) shading and inked outlines, and a back-to-front transparent pass for glass and additive glows; GPU instancing draws one mesh many times in one call (`InstancedMesh`, and glTF `EXT_mesh_gpu_instancing`)
- Lighting, in 2D and 3D:
    - **2D** — `Light2d` as a first-class `Renderable` (multiple dynamic lights, radial-gradient falloff, adjustable edge `softness`, illumination-only mode, procedural rendering via `drawLight`), plus optional per-pixel normal-map shading and specular highlights (`shininess`) on sprites for 3D-looking dynamic lights
    - **3D** — `Light3d` directional, point, spot and ambient lights, added to the world like `Light2d` (half-Lambert diffuse + ambient fill, quadratic falloff and cone angles on the punctual types, runtime-manipulable for day/night), auto-loaded from a glTF scene's authored suns and lamps
    - up
```
