Macros & API

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.canvas3D and canvas3D are 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 browser

The 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

KeyUI option (Scene Setup)
auto3dMiscellaneous -> Enable 3D on Load
enablePlayersMiscellaneous -> Enable for Players
object3dSightMiscellaneous -> Use 3D Geometry for sight calculations
enableFogOfWarMiscellaneous -> Enable Fog of War
showSceneWalls / showSceneDoors / showSceneFloorsMiscellaneous -> Render Walls / Render Doors / Render Tiles
exrEssentials -> Skybox
sunPositionEssentials -> Time of Day (24h)
weather.preset, weather.intensityEssentials -> Weather, Intensity
weather.layer2Weather -> Additional Weather
pp.presetEssentials -> Visual Style (use sceneEssentials.update, above)
timeSyncSky & Light -> Automatic Lighting (off, time, darkness, both)
exposure, sunShadowsSky & Light -> Exposure, Sun Shadows
renderBackgroundSky & Light -> Display Background
bloom, pixelVisuals -> Bloom, Pixelize
mapEdgeVisuals -> Edge Style (none, fade, island, diorama, blueprint, legacy)
initialPositionInitial View Position (set by its capture button)

Tile

KeyUI option (Tiles & Map Building)
model3dEssentials -> 3D Model
dynaMeshEssentials -> Dynamic Mesh
collision / sight / cameraCollisionEssentials -> Block Movement / Block Sight / Block Camera
autoGroundEssentials -> Auto Ground
pausedEssentials -> Paused (model animation)
depth, tiltX, tiltZPosition -> Depth, Tilt X, Tilt Y
imageTexture, colorMaterial -> Texture, Tint
castShadowMaterial -> Cast Shadow
doorType, doorStateDoor -> Door Type, Door State
ParticleTypeEffects -> Particle Preset
scatter.setScatter -> Scatter Set

Token

KeyUI option (Tokens)
model3dEssentials -> 3D Model
scaleEssentials -> Scale
flatTokenStyleEssentials -> 2D Token Style
disableBaseEssentials -> Hide Base
rotationYPosition -> Facing
ParticleTypeEffects -> Particle Preset
auraRange, auraColorEffects -> Aura Range, Aura Color
shadersShaders set from the Token HUD (Effects)

Light

KeyUI option (Lights)
lightHaloEssentials -> Glow Halo
castShadowLight Effects -> Cast Shadow
tiltLight Effects -> Tilt
lightShaftLight Effects -> Light Shaft
enableParticle, ParticleTypeParticles -> Enable Particles, Particle Preset

Wall

KeyUI option (Walls)
wallTexture, wallSidesTextureTexture, Sides Texture
wallTint, wallSidesTintColor, Sides Tint
wallOpacity, wallDepthOpacity, Wall Depth
alwaysVisible, joinWallAlways Visible, Join Wall

Region

KeyUI option (Walls, Notes & Regions)
regionFx.theme3D tab -> Effect Theme
regionFx.color, regionFx.intensityEffect 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.

HookWhenArguments
3DCanvasPreInit, 3DCanvasPostInitBefore and after the 3D engine is created, at loadthe 3D Canvas object
3DCanvasConfigAt load, after CONFIG is builtgame.Levels3DPreview.CONFIG
3DCanvasInit, 3DCanvasReadyAt load, when game.Levels3DPreview existsthe 3D Canvas object
3DCanvasMapmakingPackRegisterAssetPacks / ...TokenPacksAt load, to add asset or miniature packs to the browsersthe Asset Browser / Token Browser class
3DCanvasTemplateEffectsInitAt load, to add spell-area themes for a game systemtheme tables, system handlers
3DCanvasToggleModeWhen 3D is switched with toggle() or the cube buttontrue (turning on) or false
3DCanvasSceneReadyEvery time a scene finishes building in 3D, also after a level switchthe 3D Canvas object, { levelSwitch: true } on level switch
3DCanvasScatterGeneratedEach time a scatter area is (re)generatedthe scatter field
3DCanvasDrawingsRenderedEach time the scene's drawings are painted onto the 3D surfaces (a drawing is created, changed or deleted)the 3D drawings system
3DCanvasBakeCompleteWhen a model bake finishesnone
3DCanvasThumbnailCaptureWhen a 3D scene thumbnail is capturedextra 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"));