Molten

Engine API: import { ... } from "molten"

Everything Cast can ask of the engine is imported from the built-in module "molten". This page lists all of it, with the exact parameter and result types the compiler uses (castc/src/compiler_check.cpp, Checker::molten). Each function is a thin wrapper over the C API in engine/include/molten.h.

Math functions (min, max, sin, dot, ...) and print are built into the language and need no import; see Basics.

Summary

Area Names
Behaviors behavior
Components Transform, Mesh, Camera, Light, PostProcess, AudioSource, RigidBody, Collider, CharacterController
Input Key, MouseButton, keyDown, keyPressed, mousePressed, mouseDown, mouseDelta, mouseWheel, setMouseLocked, mouseLocked, pointerPlane
Screens screenIs, switchScreen, pushScreen, popScreen, requestQuit
Objects spawnObject, placedObject, spawnPosition
Assets and rendering loadAsset, clearColor, shaderSetGlobal, shaderGlobal, graphicsTier, graphicsQuality, and the types MeshBlend, LightKind, ToneMapping, Antialiasing, SkyMode, ReflectionMode, ProbeUpdate, GraphicsTier, GraphicsQuality
UI uiSetNumber, uiSetBool, uiSetText
Save data saveRead, saveWrite
Audio AudioBus, audioPlay, audioPlayAt, audioPlayAttached, audioStop, audioBusVolume, audioSetBusVolume
Physics physicsRaycast, physicsShapeCast, physicsOverlap, characterMove, characterGrounded, physicsForce, physicsImpulse, physicsSetVelocity, physicsVelocity, physicsSleeping, physicsContactCount, physicsContact, and the types BodyMotion, ColliderShape, ContactPhase, PhysicsHit, PhysicsContact

Behaviors

export default behavior([ComponentA, ComponentB], (objects, dt: float): void => { ... });

See Components and behaviors.

Input

Function Result Notes
keyDown(key: Key) bool True while the key is held
keyPressed(key: Key) bool True during the first simulation tick after the key went down. A press between two ticks is kept until a tick runs
mousePressed(button: MouseButton) bool Latched through the next tick. Presses the UI used are excluded
mouseDown(button: MouseButton) bool True while the button is held. Presses the UI used are excluded
mouseDelta() vec2 Pointer motion in window points since the previous tick, +x right and +y down. Motion between two ticks is summed and reported once, to the next tick. Keeps reporting while the mouse is locked
mouseWheel() float Wheel notches since the previous tick, positive away from the user
setMouseLocked(locked: bool) void Locked hides the cursor and keeps it in the window (relative mouse mode) so mouseDelta can drive a first-person camera. Takes effect at the next frame. Unlock it when a menu or pause screen needs the cursor
mouseLocked() bool The lock gameplay last asked for
pointerPlane(y: float64) dvec3 | null Casts the mouse pointer through the active camera onto the horizontal plane at height y and returns the hit position or null

Mouse-look example (yaw and pitch kept in a component; see Gridline's fieldwork.cast for a full camera rig):

const d = mouseDelta();
obj.look.yaw -= d.x * 0.15;                                   // degrees per point
obj.look.pitch = clamp(obj.look.pitch - d.y * 0.15, -85.0, 85.0);

Key and MouseButton are case-sensitive string literal unions exported by "molten". The compiler emits their numeric input codes directly. Key names refer to physical positions (SDL scancodes), so "W" is the key where W sits on a US layout. "Left" and "Right" mean arrow keys in a Key argument and buttons in a MouseButton argument.

import { Key, keyDown, mousePressed } from "molten";

function moving(key: Key): bool { return keyDown(key); }
function clickedLeft(): bool { return mousePressed("Left"); }
function movingLeft(): bool { return moving("A"); }

MouseButton members are "Left", "Middle", "Right", "X1", and "X2".

Key names

Quote each name when you pass it to Cast.

Group Members
Letters A through Z
Top row 0 through 9
Keyboard controls and punctuation Enter, Escape, Backspace, Tab, Space, Minus, Equals, LeftBracket, RightBracket, Backslash, NonUSHash, Semicolon, Apostrophe, Grave, Comma, Period, Slash, CapsLock, PrintScreen, ScrollLock, Pause, Insert, Home, PageUp, Delete, End, PageDown, Right, Left, Down, Up, NumLock, NonUSBackslash, Application, Power, LeftControl, LeftShift, LeftAlt, LeftMeta, RightControl, RightShift, RightAlt, RightMeta, Mode
Function keys F1 through F24
Numeric keypad Numpad0 through Numpad9, NumpadA through NumpadF, NumpadDivide, NumpadMultiply, NumpadMinus, NumpadPlus, NumpadEnter, NumpadPeriod, NumpadEquals, NumpadComma, NumpadEqualsAS400, Numpad00, Numpad000, NumpadLeftParen, NumpadRightParen, NumpadLeftBrace, NumpadRightBrace, NumpadTab, NumpadBackspace, NumpadXor, NumpadPower, NumpadPercent, NumpadLess, NumpadGreater, NumpadAmpersand, NumpadDoubleAmpersand, NumpadVerticalBar, NumpadDoubleVerticalBar, NumpadColon, NumpadHash, NumpadSpace, NumpadAt, NumpadExclamation, NumpadMemoryStore, NumpadMemoryRecall, NumpadMemoryClear, NumpadMemoryAdd, NumpadMemorySubtract, NumpadMemoryMultiply, NumpadMemoryDivide, NumpadPlusMinus, NumpadClear, NumpadClearEntry, NumpadBinary, NumpadOctal, NumpadDecimal, NumpadHexadecimal
Editing, international and system keys International1 through International9, Lang1 through Lang9, Execute, Help, Menu, Select, Stop, Again, Undo, Cut, Copy, Paste, Find, Mute, VolumeUp, VolumeDown, AltErase, SysReq, Cancel, Clear, Prior, Enter2, Separator, Out, Oper, ClearAgain, CrSel, ExSel, Front, ThousandsSeparator, DecimalSeparator, CurrencyUnit, CurrencySubunit, Sleep, Wake, SoftLeft, SoftRight, Call, EndCall
Media and application controls ChannelIncrement, ChannelDecrement, MediaPlay, MediaPause, MediaRecord, MediaFastForward, MediaRewind, MediaNextTrack, MediaPreviousTrack, MediaStop, MediaEject, MediaPlayPause, MediaSelect, ACNew, ACOpen, ACClose, ACExit, ACSave, ACPrint, ACProperties, ACSearch, ACHome, ACBack, ACForward, ACStop, ACRefresh, ACBookmarks

Space reaches gameplay in every build and also toggles simulation pause in builds with dev link. Escape quits unless game.toml sets escape_quits = false.

Screens

Function Result Notes
screenIs(name: string) bool True if name is the top screen
switchScreen(name: string) bool Replace the stack with name and load its level. false if unknown. Takes effect at the end of the tick
pushScreen(name: string) bool Put name on top; the level is unchanged
popScreen() void Return to the screen below
requestQuit() void Quit after the current frame

Objects

Function Result Notes
spawnObject(type: string, position: dvec3) Handle<Object> Spawns an object type (with its parts) at position, no rotation. Null handle if the type is unknown. Usable at once; appears in behavior queries next tick. Belongs to the loaded level, if any
placedObject(id: string) Handle<Object> The object the current level placed with that id, or a null handle. placedObject("") is a handy null handle
spawnPosition(index: int) dvec3 Position of the loaded level's spawn point index (file order); dvec3(0) if out of range

On handles: h.get(), h.as<T>(), h == other. Inside behaviors: obj.handle, obj.destroy(). See Objects and handles.

Assets and rendering

Function Result Notes
loadAsset(path: string) asset Loads (importing first if needed) the asset at path under assets/; same handle for the same path. Assign to asset fields such as Mesh.mesh
clearColor(color: vec4) void The color the frame is cleared to before the scene (linear RGBA)
shaderSetGlobal(index: int, value: vec4) void Sets shader global index (0-15), which every mesh shader and post effect reads as shaderGlobal(index) / frame->globals[index]. Use it for weather, time of day, wind. Values survive Cast reloads and start at zero. See Shaders
shaderGlobal(index: int) vec4 The value last set (zero if out of range)
graphicsTier() GraphicsTier M17: "standard" or "cinematic", the tier this run renders at (the lowest of game.toml's graphics, the player's setting and what the GPU supports)
graphicsQuality() GraphicsQuality M17: the player's "low", "medium" or "high" preset (quality in settings.ini, or --quality). At "low" every M17 setting is ignored, so a game can tone down its own effects to match

UI

Function Result Notes
uiSetNumber(name: string, value: float) void Publish a number for {name} bindings (progress values, slider values, text)
uiSetBool(name: string, value: bool) void Publish a bool
uiSetText(name: string, value: string) void Publish text. The engine copies it

Values persist for the game session until set again. One name holds one value.

Save data

Function Result Notes
saveWrite(name: string, value: string) bool Writes the named slot atomically. false on failure
saveRead(name: string) string The slot's contents, or "" if it is missing or unreadable. Frame-lifetime: copy with new(game) string(...) to keep it

Slots are files under saves/ in the per-user data folder (<user data>/<organization>/<name>/saves/), with portable names and a 16 MiB limit. The dev runner uses the same folder when the project has a valid name.

Audio

AudioBus is "master", "music", "effects", or "ui".

Function Result Notes
audioPlay(path: string, bus: AudioBus, volume: float, loop: bool, fadeIn: float) uint64 Not positioned. fadeIn in seconds
audioPlayAt(path: string, bus: AudioBus, position: dvec3, volume: float) uint64 Spatial, at a fixed world position
audioPlayAttached(path: string, bus: AudioBus, object: Handle<Object>, volume: float) uint64 Spatial, follows the object; stops when it is destroyed. 0 for a null handle
audioStop(voice: uint64, fadeOut: float) void Fade out and stop
audioBusVolume(bus: AudioBus) float 0 to 1
audioSetBusVolume(bus: AudioBus, volume: float) bool Applies at once and saves to the player's settings.ini

The result is a voice handle; 0 means the sound didn't start. Voice handles survive code reloads. Up to 128 voices mix at once.

Physics

Queries see the physics state from the last completed tick. mask is a bit mask of collision layers (1 << layer); 0xffffffff tests all. ignore is an object to skip; pass a null handle (placedObject("")) to skip nothing.

Function Result Notes
physicsRaycast(origin: dvec3, displacement: vec3, mask: uint32, ignore: Handle<Object>) PhysicsHit Closest hit along the whole segment origin to origin + displacement
physicsShapeCast(shape: ColliderShape, size: vec3, origin: dvec3, rotation: quat, displacement: vec3, mask: uint32, ignore: Handle<Object>) PhysicsHit Closest hit of a swept primitive ("box", "sphere", "capsule", or "cylinder"; size unscaled full size)
physicsOverlap(shape: ColliderShape, size: vec3, origin: dvec3, rotation: quat, mask: uint32, ignore: Handle<Object>) PhysicsHit Deepest overlap; fraction is 0
characterMove(object: Handle<Object>, velocity: vec3, jump: bool) void Horizontal walking velocity for the next tick, capped at the controller's speed. Call every tick. jump is used once
characterGrounded(object: Handle<Object>) bool Standing on walkable ground after the last step
physicsForce(object, force: vec3) void Applied to a dynamic body during the next tick
physicsImpulse(object, impulse: vec3) void Instant change of momentum, next tick
physicsSetVelocity(object, velocity: vec3) void Sets a dynamic body's linear velocity, next tick
physicsVelocity(object) vec3 A rigid body's linear velocity
physicsSleeping(object) bool Whether a dynamic body is asleep
physicsContactCount() int Number of contact pairs from the previous tick
physicsContact(index: int) PhysicsContact One pair; null handles when out of range
struct PhysicsHit {      // a miss has a null object handle
    object: Handle<Object>;
    position: dvec3;
    normal: vec3;
    fraction: float;     // 0..1 along the displacement
    trigger: bool;
}
struct PhysicsContact {
    first: Handle<Object>;
    second: Handle<Object>;
    phase: ContactPhase; // "begin", "stay", or "end"
    trigger: bool;
}

Sleeping pairs keep reporting "stay". An "end" contact may name a destroyed object, so resolve handles with .get() / .as<T>()?.get() before using them. From samples/physics/behaviors/yard.cast:

for (let i = 0; i < physicsContactCount(); i++) {
    const contact = physicsContact(i);
    if (contact.phase != "begin") continue;
    const first = contact.first.as<Block>()?.get();
    if (first) first.impactState.flash = 1;
}

Not in Cast

These C API features have no Cast wrapper: sim_time, add_component and remove_component at runtime, object_count, part(object, name) by string (use the part field on the object type instead), current_level, and register_screen. Hand-written C in native/ can call them.

View this page's source on GitHub