Macros & API
Ready-to-use macros for 3D Canvas: switch 3D on and off, move everyone's camera, ping, play animations, change the time of day or the weather, open the module's windows and play cutscenes. The second half lists the flags and hooks, for people who write their own scripts or modules.
To use a macro: open the Macro Directory (hotbar), Create Macro, set Type to Script, paste the code and click Execute Macro (or drag it to the hotbar). Most macros need the scene to be open in 3D.
Before You Start
- Everything lives in
game.Levels3DPreview.game.canvas3Dandcanvas3Dare the same object, use whichever you like. - Particle effects use their own global,
Particle3D: see Particles API. - A macro runs only on the computer of the user who clicks it. Some calls are sent to every user viewing the scene in 3D (pings, token animations, particles, shared camera moves, cutscenes): the description of each macro says so.
This shows whether the 3D view is open on your screen:
ui.notifications.info(game.Levels3DPreview._active ? "3D is on" : "3D is off");Turning 3D On and Off
This switches the 3D view on or off for you, like the cube button in the Token controls:
game.Levels3DPreview.toggle();toggle(true) always turns it on, toggle(false) always turns it off. game.Levels3DPreview.reload() rebuilds the 3D scene, useful after big changes made by a script.
Camera
This puts your camera back to the scene's starting view (Shift + R):
game.Levels3DPreview.resetCamera();resetCamera(true) gives a top-down view instead.
This glides your camera to the selected token, keeping the current angle (Shift + X):
game.Levels3DPreview.setCameraToControlled(canvas.tokens.controlled[0]);This flies your camera to a token from a fixed distance. distance is in pixels of the scene (3000 by default), rotation turns the point of view around the token (in radians), speed goes from 0.01 (slow) to 1 (instant):
const target = canvas.tokens.controlled[0];
game.Levels3DPreview.helpers.animateCamera(target, { distance: 1500, rotation: Math.PI / 2, speed: 0.04 });You can pass a point of the scene instead of a token, { x, y, z } with x and y in pixels and z the elevation. Add topdown: true to look straight down on it:
game.Levels3DPreview.helpers.animateCamera({ x: 2000, y: 1500, z: 0 }, { distance: 2000, topdown: true });Moving the Players' Cameras
This moves the camera of every user viewing the scene in 3D to your current view (the same as Shift + long press on the ground). Set up the view you want, then run it:
const L = game.Levels3DPreview;
L.helpers.focusCameraToPosition(L.camera.position, L.controls.target);This sends your current view to one player only (change the name):
const L = game.Levels3DPreview;
const user = game.users.getName("Gastone");
L.socket.socketCamera({ cameraPosition: L.camera.position, cameraLookat: L.controls.target }, { users: [user.id] });A player can run the first macro only when Players Can Send Camera Position is on (Camera & Controls). Shift + Q does the same without a macro.
Pings
This pings the selected token for everyone, with the ! marker. The other markers are "question", "location" and "target"; leave type out for a plain ping:
const L = game.Levels3DPreview;
const token = canvas.tokens.controlled[0];
L.socket.dispatchPing({ position: L.tokens[token.id].mesh.position, color: game.user.color.css, size: 1, type: "exclamation" });Token Animations
This plays the Shake animation twice on the selected tokens, for everyone:
game.Levels3DPreview.playTokenAnimation(canvas.tokens.controlled, "shake", { repeats: 2 });Animation ids: twirl, slash, swipe, charge, bow, buff, debuff, breath, shake, knockback. They are the same as in the Token HUD (Weather, Shaders & Effects).
Spells, arrows and other particle effects: Particles API.
Time of Day, Weather and Visual Style
These options are stored on the scene, so a change reaches every player at once and stays saved. sceneEssentials.update fills in the related values the same way the Scene Setup form does (wind and haze for a weather, all the colour values for a visual style).
This sets the time of day to 20:00 on the current scene:
const scene = canvas.scene;
await scene.update(game.Levels3DPreview.sceneEssentials.update(scene, "sunPosition", 20));This starts snow:
const scene = canvas.scene;
await scene.update(game.Levels3DPreview.sceneEssentials.update(scene, "weather.preset", "snow"));Weather ids: none, overcast, drizzle, rain, heavyrain, thunderstorm, snow, blizzard, hail, fog, mist, sand, sandstorm, ashfall, leaves, petals, embers, fireflies, mysteriouslights, stars, starfall, dust, smoke, toxic.
This switches the visual style to black and white:
const scene = canvas.scene;
await scene.update(game.Levels3DPreview.sceneEssentials.update(scene, "pp.preset", "noir"));Visual style ids: none, warm, cold, dramatic, noir, vintage, dreamy.
Setting only the pp.preset flag by hand changes the name in the form but not the look: use sceneEssentials.update as above. If the scene's Automatic Lighting follows the world time, change the world time instead of sunPosition.
Opening Windows
Each line opens one window (run one at a time):
new game.Levels3DPreview.CONFIG.UI.AssetBrowser().render(true); // Asset Browser
game.Levels3DPreview.helpers.setPerformancePreset(); // Graphics Settings
game.Levels3DPreview.helpers.showPerformanceDialog(); // Performance & Optimization report
game.Levels3DPreview.open3DFilePicker(); // File Browser showing only 3D models
new game.Levels3DPreview.sharing.apps.MapBrowser().render(true); // Community Maps browserThe Token Browser opens from a token's configuration; to search miniatures from a macro see the Token Browser API.
Tiles
This creates a 3D tile with a model from the Mapmaking Pack. x and y are the center of the tile in pixels:
const [tile] = await canvas.scene.createEmbeddedDocuments("Tile", [{
x: 3300, y: 2700, width: 100, height: 100,
flags: { "levels-3d-preview": { model3d: "modules/canvas3dcompendium/assets/Tiles/RPG Items/Chalice.glb" } }
}]);Merging every tile that shares a model, and undoing it: see Performance.
Cutscenes
Cutscenes are made with 3D Canvas - Advanced Tools, but a saved cutscene plays without it. This plays the cutscene named Intro of the current scene for every user viewing it in 3D (you can also give its number, starting from 0):
game.Levels3DPreview.cutsceneEngine.playCutscene("Intro");Add a list of user ids to play it only for them: playCutscene("Intro", [game.users.getName("Gastone").id]).
Advanced
Exporting the Scene as glTF
game.Levels3DPreview.exporter.export() should open an export dialog, but it opens without its checkboxes and its Export button does nothing. This macro exports all the tiles of the scene to a scene.gltf download instead; the 3D view reloads when it is done. Big scenes make big files (about 100 MB for the 74 tiles of a Map Maker village).
const L = game.Levels3DPreview;
const tiles = L.scene.children.filter(o => o.userData?.entity3D?.embeddedName === "Tile");
L.exporter.exportToGltf({ objects: tiles });Flags
Every 3D option is a flag of the document under levels-3d-preview. Read one with document.getFlag("levels-3d-preview", key) and change it with document.setFlag("levels-3d-preview", key, value); the 3D view updates by itself. This makes the selected tiles stop blocking sight:
for (const tile of canvas.tiles.controlled) {
await tile.document.setFlag("levels-3d-preview", "sight", false);
}The most useful keys, by document. Keys with a dot are inside an object (weather.preset is { weather: { preset } }).
Scene
| Key | UI option (Scene Setup) |
|---|---|
auto3d | Miscellaneous -> Enable 3D on Load |
enablePlayers | Miscellaneous -> Enable for Players |
object3dSight | Miscellaneous -> Use 3D Geometry for sight calculations |
enableFogOfWar | Miscellaneous -> Enable Fog of War |
showSceneWalls / showSceneDoors / showSceneFloors | Miscellaneous -> Render Walls / Render Doors / Render Tiles |
exr | Essentials -> Skybox |
sunPosition | Essentials -> Time of Day (24h) |
weather.preset, weather.intensity | Essentials -> Weather, Intensity |
weather.layer2 | Weather -> Additional Weather |
pp.preset | Essentials -> Visual Style (use sceneEssentials.update, above) |
timeSync | Sky & Light -> Automatic Lighting (off, time, darkness, both) |
exposure, sunShadows | Sky & Light -> Exposure, Sun Shadows |
renderBackground | Sky & Light -> Display Background |
bloom, pixel | Visuals -> Bloom, Pixelize |
mapEdge | Visuals -> Edge Style (none, fade, island, diorama, blueprint, legacy) |
initialPosition | Initial View Position (set by its capture button) |
Tile
| Key | UI option (Tiles & Map Building) |
|---|---|
model3d | Essentials -> 3D Model |
dynaMesh | Essentials -> Dynamic Mesh |
collision / sight / cameraCollision | Essentials -> Block Movement / Block Sight / Block Camera |
autoGround | Essentials -> Auto Ground |
paused | Essentials -> Paused (model animation) |
depth, tiltX, tiltZ | Position -> Depth, Tilt X, Tilt Y |
imageTexture, color | Material -> Texture, Tint |
castShadow | Material -> Cast Shadow |
doorType, doorState | Door -> Door Type, Door State |
ParticleType | Effects -> Particle Preset |
scatter.set | Scatter -> Scatter Set |
Token
| Key | UI option (Tokens) |
|---|---|
model3d | Essentials -> 3D Model |
scale | Essentials -> Scale |
flatTokenStyle | Essentials -> 2D Token Style |
disableBase | Essentials -> Hide Base |
rotationY | Position -> Facing |
ParticleType | Effects -> Particle Preset |
auraRange, auraColor | Effects -> Aura Range, Aura Color |
shaders | Shaders set from the Token HUD (Effects) |
Light
| Key | UI option (Lights) |
|---|---|
lightHalo | Essentials -> Glow Halo |
castShadow | Light Effects -> Cast Shadow |
tilt | Light Effects -> Tilt |
lightShaft | Light Effects -> Light Shaft |
enableParticle, ParticleType | Particles -> Enable Particles, Particle Preset |
Wall
| Key | UI option (Walls) |
|---|---|
wallTexture, wallSidesTexture | Texture, Sides Texture |
wallTint, wallSidesTint | Color, Sides Tint |
wallOpacity, wallDepth | Opacity, Wall Depth |
alwaysVisible, joinWall | Always Visible, Join Wall |
Region
| Key | UI option (Walls, Notes & Regions) |
|---|---|
regionFx.theme | 3D tab -> Effect Theme |
regionFx.color, regionFx.intensity | Effect Color, Intensity |
Hooks
3D Canvas calls these hooks. Use them in a world script or a module (Hooks.on(...)); the ones fired while Foundry loads cannot be caught from a macro.
| Hook | When | Arguments |
|---|---|---|
3DCanvasPreInit, 3DCanvasPostInit | Before and after the 3D engine is created, at load | the 3D Canvas object |
3DCanvasConfig | At load, after CONFIG is built | game.Levels3DPreview.CONFIG |
3DCanvasInit, 3DCanvasReady | At load, when game.Levels3DPreview exists | the 3D Canvas object |
3DCanvasMapmakingPackRegisterAssetPacks / ...TokenPacks | At load, to add asset or miniature packs to the browsers | the Asset Browser / Token Browser class |
3DCanvasTemplateEffectsInit | At load, to add spell-area themes for a game system | theme tables, system handlers |
3DCanvasToggleMode | When 3D is switched with toggle() or the cube button | true (turning on) or false |
3DCanvasSceneReady | Every time a scene finishes building in 3D, also after a level switch | the 3D Canvas object, { levelSwitch: true } on level switch |
3DCanvasScatterGenerated | Each time a scatter area is (re)generated | the scatter field |
3DCanvasDrawingsRendered | Each time the scene's drawings are painted onto the 3D surfaces (a drawing is created, changed or deleted) | the 3D drawings system |
3DCanvasBakeComplete | When a model bake finishes | none |
3DCanvasThumbnailCapture | When a 3D scene thumbnail is captured | extra data |
This posts a chat message each time a scene finishes loading in 3D on your screen (run it once; it lasts until the page is reloaded):
Hooks.on("3DCanvasSceneReady", () => {
ChatMessage.create({ content: `${canvas.scene.name} is ready in 3D`, whisper: [game.user.id] });
});This logs each switch between 2D and 3D in the browser console (F12):
Hooks.on("3DCanvasToggleMode", (on) => console.log(on ? "3D on" : "3D off"));