Golix for developers

Host Golix rooms from Node with golix.js, script what happens in them, join rooms as a bot and write your own stadiums.

Getting started

golix.js needs Node 22 or later.

npm install golix.js

A room registers with the public lobby, and players connect straight to your process over WebRTC, or through the lobby when a direct connection fails.

const golix = require('golix.js');

golix().then((HBInit) => {
  const room = HBInit({
    roomName: 'My room',
    maxPlayers: 12,
    noPlayer: true,
    lobby: 'wss://golix.cosmosfutsal.com',
    // 22 characters of A-Z, a-z, 0-9, - and _: keeps the room link across restarts.
    roomSecret: process.env.ROOM_SECRET,
    // Only the first time this roomSecret opens a room: from https://golix.cosmosfutsal.com/headlesstoken
    token: process.env.ROOM_TOKEN,
  });
  room.onRoomLink = (link) => console.log(link);
  room.onPlayerJoin = (player) => room.sendAnnouncement(`Welcome ${player.name}`, player.id);
});

With ES modules: import golix from 'golix.js'; const HBInit = await golix();

Callbacks run inside the room's tick, 60 times a second. Methods called from them take effect on the next tick, and an exception thrown by a callback is logged without stopping the room.

Room config

FieldMeaning
roomNameUp to 40 characters.
playerNameName of the host player; leave out with noPlayer: true.
passwordUp to 30 characters.
maxPlayers2 to 30, default 12.
publicWhether the room is listed. Default true.
geo{ code, lat, lon } shown in the room list.
noPlayerRun the room without a host player.
lobbyws:// or wss:// lobby to register with.
roomSecretWith lobby: the secret the room id is derived from, so the link survives restarts.
tokenWith lobby: a room token from /headlesstoken, needed the first time a roomSecret opens a room. It works once, for ten minutes; the same roomSecret reopens the room later without one.
serverWithout lobby: serve the room from your own lobby, given as a running server or its options (default port 8787).
clientUrlOrigin used in the room link.
webrtc{ bindAddress, portRange: [first, last], iceServers } for the WebRTC connections players open to your process.

Room methods

Players and chat

MethodNotes
sendChat(message, targetId?)As the host player; up to 140 characters.
sendAnnouncement(msg, targetId?, color?, style?, sound?)Style normal, bold, italic, small, small-bold or small-italic; sound 0, 1 or 2; up to 1000 characters.
setPlayerAdmin(id, admin)
setPlayerTeam(id, team)0 spectators, 1 red, 2 blue.
kickPlayer(id, reason, ban)A ban matches the player's auth and conn.
clearBan(id), clearBans()
getPlayer(id), getPlayerList()
reorderPlayers(ids, moveToTop)
setPlayerAvatar(id, avatar)Null gives back the avatar the player chose.

Game

MethodNotes
startGame(), stopGame(), pauseGame(paused)
setScoreLimit(n), setTimeLimit(minutes)0 to 99; only between games.
setTeamsLock(locked)
setTeamColors(team, angle, textColor, colors)Up to five stripes.
setKickRateLimit(min, rate, burst)
getScores(), getBallPosition()scores.timeLimit is in seconds.
setCustomStadium(text)Takes a stadium file; throws when the text is not a valid one.
setDefaultStadium(name)Built-ins: Standard, Wide Goals, Compact, Stadium, Oval, Rink, Big Rink, Stadium Wide Goals, Big Oval, Colossal. Classic, Easy, Small, Big, Rounded, Hockey, Big Hockey, Big Easy, Big Rounded and Huge name the same ones in that order.
startRecording(), stopRecording()Returns a .glx replay as a Uint8Array.
setPassword(pass)Null or empty removes it.

Discs

MethodNotes
getDiscCount()Stadium discs, with the ball at 0, then player discs.
getDiscProperties(index), setDiscProperties(index, props)Fields x y xspeed yspeed xgravity ygravity radius bCoeff invMass damping color cMask cGroup; floats are stored as 32-bit.
getPlayerDiscProperties(id), setPlayerDiscProperties(id, props)Players get fresh discs at every kickoff, so changes last until then. For lasting changes use setPlayerPhysics.
A call with a value players could not receive, such as a color above 32 bits, a fractional flag or team 3, is dropped with a warning in the console instead of breaking the room.

Protection

MethodNotes
setRequireRecaptcha(on)Asks every joiner for a captcha. See room protection.
setRaidProtection({ joins, seconds, minutes })Tunes the automatic raid guard; null turns it off.
setMaxPlayersPerConn(n)How many players one network address may have in the room; null for no limit (the default).

Room events

Assign a function to the property.

EventNotes
onPlayerJoin(player), onPlayerLeave(player)
onPlayerChat(player, message)Return false to keep the message from the others.
onPlayerKicked(player, reason, ban, byPlayer)
onPlayerAdminChange(player, byPlayer), onPlayerTeamChange(player, byPlayer)
onPlayerActivity(player)The player sent input, which happens when their keys change.
onPlayerInput(player, prevInput)The player's keys changed; player.input holds the new ones.
onPlayerAction(player, actionId, isPressed)An action key 1 to 6 went down or up, in rooms with setActionKeys(true).
onPlayerBallKick(player)
onTeamGoal(team), onTeamVictory(scores)
onGameStart(byPlayer), onGameStop(byPlayer)
onGamePause(byPlayer), onGameUnpause(byPlayer)
onGameTick()Every tick of a running, unpaused game.
onPositionsReset()After a goal, before the next kickoff.
onStadiumChange(name, byPlayer)
onKickRateLimitSet(min, rate, burst, byPlayer), onTeamsLockChange(locked, byPlayer)
onCollisionDiscVsDisc(disc1, disc2)Two discs bounced off each other; disc indexes as in getDiscProperties.
onCollisionDiscVsPlane(disc, planeIndex), onCollisionDiscVsSegment(disc, segmentIndex), onCollisionDiscVsVertex(disc, vertexIndex)A disc bounced off the stadium's plane, segment or vertex at that index.
onRoomLink(url)The room's link, once it is registered.
onLobbyDisconnect(retryInMs)The lobby is out of reach. Players on WebRTC keep playing; new ones cannot join until it is back.
onLobbyReconnect()Registered again under the same room link.

A post hit is the ball, disc 0, against a post's disc index; a touch is the ball against a player's disc.

Player objects

FieldMeaning
id, name, team, admin
position{ x, y }, or null without a disc.
inputThe keys held, as input flags.
authThe player's identity: an 87-character base64url P-256 public key that stays with their browser. Only set in onPlayerJoin.
connThe hex of the player's network address. Only set in onPlayerJoin.

Customizing the game

Physics for one player

room.setPlayerPhysics(player.id, { kickStrength: 7, acceleration: 0.12, radius: 17 });
room.getPlayerPhysics(player.id); // { kickStrength: 7, acceleration: 0.12, radius: 17 }
room.setPlayerPhysics(player.id, null); // back to the stadium's

Any of radius bCoef invMass damping acceleration kickingAcceleration kickingDamping kickStrength kickback; the fields you leave out keep the stadium's playerPhysics. The change lasts across kickoffs until you clear it.

Text on the game screen

room.setHudItem('score', { text: 'Round 2 of 3', x: 0.5, y: 0.12, align: 'center', color: 0xffd34d, size: 22 });
room.clearHudItem('score');

x and y place the item as a fraction of the screen from the top left. Calling setHudItem with the same id replaces the item. Up to 16 items of 100 characters, sizes 8 to 64. Players who join later see them too.

Camera

room.setCamera({ playerId: scorer.id }, 1.6); // follow a player, zoomed in
room.setCamera({ discIndex: 0 });              // the ball
room.setCamera({ x: 0, y: 0 }, 0.8);           // a fixed point
room.setCamera(null);                          // back to normal

The zoom, 0.25 to 4, multiplies each player's own view setting.

Kits

setPlayerColors(id, angle, textColor, colors) dresses one player in their own kit instead of the team's, with up to five stripes; clearPlayerColors(id) takes it off.

Action keys

setActionKeys(true) lets players send six extra keys, Q, E, R, F, C and V by default. Each press and release arrives as onPlayerAction(player, actionId, isPressed); the keys do nothing by themselves.

Room hosts who play in the browser get most of this without code, from the Mods button in their room.

Flags

room.InputFlags      // up 1, down 2, left 4, right 8, kick 16
room.CollisionFlags  // ball 1, red 2, blue 4, redKO 8, blueKO 16, wall 32, all 63,
                     // kick 64, score 128, c0 1<<28, c1 1<<29, c2 1<<30, c3 1<<31

With action keys on, player.input also carries them as bits 32, 64, 128, 256, 512 and 1024 for actions 1 to 6.

Joining as a player

const { session, auth, key } = await golix.joinRoom({
  room: 'https://golix.cosmosfutsal.com/play?c=<id>',
  name: 'bot',
});
session.send({ type: 'chat', text: 'hi' });
session.onEvent((event) => console.log(event));

Store key and pass it back as key to join again with the same auth. A refused join rejects with a golix.JoinError whose reason is password, full, banned, invalid, rateLimited, captcha, connLimit, version (the room runs another Golix version) or closed. Joining again with a key that is already in the room replaces the older connection.

Replays

golix.decodeReplay(bytes), golix.encodeReplay(replay) and golix.trimReplay(replay, fromFrame, toFrame) read, write and cut .glx replays. The game runs at 60 frames per second, so a 10 second clip ending at frame f is trimReplay(replay, f - 600, f). Replays open in the game from the room list.

Stadium files

A stadium is a JSON5 text file (.hbs) holding one object. Every field but name, width and height has a default; null counts as leaving a field out.

FieldMeaning
nameShown in the room.
width, heightHalf-size of the area the camera stays in.
maxViewWidthZooms in when a screen would show more than this width; 0 (default) for no limit.
cameraFollow"ball" (default) follows the ball and the player, "player" only the player.
spawnDistanceHow far from the centre teams line up at kickoff when there are no spawn points. Default 200.
redSpawnPoints, blueSpawnPoints[[x, y], ...] kickoff positions, taken in player order; a player who joins a team mid-game takes the last one.
kickOffReset"partial" (default) resets the ball and the players at kickoff, "full" every disc.
canBeStoredWhether players may keep the stadium. Default true.
bg{ type, width, height, kickOffRadius, cornerRadius, goalLine, color }; type is "grass", "hockey" or "none" (default), color default "718C5A".
traitsNamed sets of default fields; an object with "trait": "name" takes the fields it leaves out from that set.
vertexes{ x, y, bCoef, cMask, cGroup }: points that discs bounce off.
segments{ v0, v1, curve, curveF, bias, bCoef, cMask, cGroup, vis, color }: lines between two vertexes. curve bends it by that many degrees; bias makes it one-sided and that thick.
planes{ normal: [x, y], dist, bCoef, cMask, cGroup }: endless walls, usually the outer bounds.
goals{ p0: [x, y], p1: [x, y], team }: a line that scores for the other team when a score disc crosses it.
discs{ pos, speed, gravity, radius, invMass, damping, bCoef, color, cMask, cGroup }: posts, extra balls and anything else round. invMass: 0 does not move.
joints{ d0, d1, length, strength, color }: links two discs. length null keeps their starting distance, a number fixes it, [min, max] allows a range; strength "rigid" (default) or a number for a spring.
playerPhysics{ radius, bCoef, invMass, damping, acceleration, kickingAcceleration, kickingDamping, kickStrength, kickback, gravity, cGroup }.
ballPhysicsA disc for the ball, which always scores and can be kicked, or "disc0" to use the first disc as the ball.

Room protection

Every room gets these without any code:

The captcha is Cloudflare Turnstile. setRequireRecaptcha(true) turns it on for good; on a lobby without Turnstile keys it and the raid guard allow one join attempt per address every 30 seconds instead.