Manual

Manual

Calling JavaScript

A game built for the web plays on a page in a browser. Its C# can call the page's JavaScript, to show an ad, talk to a game portal or read the page's address, and the page can call the game back. This page covers calling the page with [JSImport], calling the game with [JSExport], standing in for the page with [JSStandIn] in the editor and on the desktop, what crosses between them, the game's web folder and its scripts, a package's scripts, the page a web game plays on, and code that differs in a browser with #if ABYSS_WEB. To build a game for the web, see Build for the web.

Call the page from C#

Mark a static partial method [JSImport] and leave out its body: the engine writes it. In a browser, it calls the function of the same name, camel-cased, that the script named after its class exports, in the game's web folder.

using Abyss.Core;
namespace DressUpMe;
public enum AdResult{    Completed,    Cancelled,}
public sealed record AdOffer(int Full, int Skipped);
public static partial class Ads{    [JSImport]    public static partial Task<AdResult> ShowRewarded(AdOffer offer);   // showRewarded in web/Ads.js}
// web/Ads.js
export async function showRewarded(offer) {
  // ...show the ad, offering offer.full coins, or offer.skipped for skipping it...
  return "completed";
}

A method's function is its name camel-cased: ShowRewarded calls showRewarded, and URLText calls urlText. Its script is the class's name: Ads calls web/Ads.js. No function is named in a string anywhere, so a rename that breaks the call shows up as the game compiles: a method whose script is not there, or does not export its function, is the build warning ABYSS035.

Call it as any method, from a flow or other async code:

AdResult watched = await Ads.ShowRewarded(new AdOffer(Full: 500, Skipped: 100));
  • A method that returns a Task or a Task<T> waits for the promise the function returns, and goes on at the start of a frame, on the engine thread, as the rest of a game's async code does.
  • A method that returns a value, or nothing, takes the function's result at once. A function that returns a promise to one of those fails the call.
  • What the page throws arrives as a JSException, with the page's message.

A [JSImport] method is static and partial with no body, in a partial class that is not generic, and takes no ref, out or in parameter; anything else is the build error ABYSS034.

Call the game from the page

Mark a static method [JSExport], and the page can call it. A web build writes game.js beside the page, which gives each class with such methods to the page's scripts as an object of the same name, each method camel-cased. It also writes game.d.ts, their TypeScript types, for your code editor.

using Abyss.Core;
[assembly: AbyssPlugin<DressUpMe.PagePlugin>]
namespace DressUpMe;
public sealed class PagePlugin : IPlugin{    public void Build(Schedule schedule) => Game.World = schedule.World;}
public static class Game{    internal static World? World { get; set; }
    internal static int Wallet { get; set; }
    [JSExport]    public static void Pause()    {        if (World is { } world)        {            world.Time.Scale = 0f;        }    }
    [JSExport]    public static void Resume()    {        if (World is { } world)        {            world.Time.Scale = 1f;        }    }
    [JSExport]    public static int Coins() => Wallet;}
// web/Ads.js
import { Game } from "./game.js";

export async function showRewarded(offer) {
  await Game.pause();
  const coins = await Game.coins();
  try {
    // ...show the ad...
    return "completed";
  } finally {
    await Game.resume();
  }
}

The page's call runs the method at the start of the game's next frame, on the engine thread, where the world is the game's to change. So every exported method gives the page a promise of its result, even one that returns at once. A method that returns a Task answers once it finishes. What the method throws rejects the promise with its message.

A [JSExport] method is a public or internal static method of a class that is not generic and not private, and takes no ref, out or in parameter; anything else is the build error ABYSS038. The page calls a method by its class's name and its own, so two methods the page would know by one name, overloads or two classes of the same name, are the build error ABYSS039.

In the editor and on the desktop

In the editor and in a desktop build there is no page. A class marked [JSStandIn] answers for another class's [JSImport] methods there, each with a static method of the same name, parameters and result:

[JSStandIn(typeof(Ads))]internal static class AdsInEditor{    public static Task<AdResult> ShowRewarded(AdOffer offer)    {        Log.Info($"An ad would show here: {offer.Full} coins watched to the end.");        return Task.FromResult(AdResult.Completed);    }}

A stand-in method is public or internal and static. One that takes or gives anything other than its [JSImport] method does is the build error ABYSS036. A [JSImport] method with no stand-in gives its result's default outside a browser, and says so once in the Logs panel.

A [JSExport] method is an ordinary method everywhere, so the game's own code can call it too.

What crosses

C#JavaScript
boola boolean
byte, int, long, float, double and the other numbersa number. A long past 2^53 loses its last digits, as every number in JavaScript does.
stringa string, or null
an enumits name, camel-cased: AdResult.Completed is "completed". Read back from the page, either spelling, or the number, is taken.
a class, a record or a structan object of its public fields and properties, their names camel-cased: { full: 500, skipped: 100 }
an array, a List<T> or an IReadOnlyList<T>an array
a nullable value, int?the value, or null
Task, Task<T>a promise

A member of a class or record holds what crosses too. A class the page's value is read into needs a public constructor whose parameters are its members, as a positional record has, or one with no parameters; a struct always has one. A member the page leaves out keeps the type's default. A parameter or result that does not cross is the build error ABYSS037, saying why.

The web folder

The game's scripts for its page go in a web folder at the top of the game's folder, beside assets and scripts. The Project panel shows it where the game has one. Its scripts are drawn in JavaScript's yellow, and a double-click opens one in your code editor; the editor never runs them.

To make one, choose Web Script in the Project panel's + menu, or New Web Script in the menu a right-click on a folder or on empty space opens. It makes the web folder where there is none, writes a script that says how it is called, and starts its name being typed: name it after the class whose [JSImport] methods call it, such as Ads.

A web build lays the web folder over what it writes:

  • web/Ads.js is Ads.js beside index.html, and web/art/ is art/. A script imports the build's game.js as ./game.js.
  • Each script at the top of the folder is loaded before the game starts.
  • A file with the same name as one the build writes, such as icon.png (the Player icon) or game.js, takes its place, and the build log says so. A script that takes the place of one of the build's is not loaded as the game's.
  • web/index.html is never copied. It is the page the game plays on when Player picks Own Page, and is left out, with a warning, when Player picks another. See The page a web game plays on.

A package's scripts

A package carries scripts for the page in its own web folder, as an ad network's or a game portal's package would. A new package has none: pick the package in the Project panel's switch, then choose Web Script in the + menu.

A web build copies a package's scripts to packages/<package id>/ beside the page, apart from the game's and from each other's, so two packages' Ads.js never meet. They import the build's game.js as ../../game.js.

A package's [JSImport] methods call its own scripts only, checked as the package compiles. Its [JSExport] methods are in the game's game.js with the game's own. A game's class and a package's, or two packages' classes, with the same name that both export methods stop the build, both named (ABYSS039), since the page calls a method by its class's name. See Making a package.

The page a web game plays on

Edit ▸ Project Settings... ▸ Player ▸ Web ▸ Web Page picks the page a web build writes: Minimal, Branded (the default), Framed, Click to Play, or Own Page. Build and run your game shows what each looks like. Own Page is grayed until the game has a web/index.html.

The engine's pages are templates, one file each, in the engine's SDK: dotnet/build/player-web/templates/<page>/index.html, for minimal, branded, framed and click. NuGet keeps the SDK in ~/.nuget/packages/abyssengine.sdk/<version> (%USERPROFILE%\.nuget\packages\abyssengine.sdk\<version> on Windows). Copy one into web/index.html to start a page of your own.

A page of your own

A page of your own is its look alone. It gives the game a canvas with the id abyss, and calls play from abyss-web.js, which the build writes beside it. play fetches the game and its packs, loads the scripts and starts the game, telling the page how far along it is:

<canvas id="abyss" tabindex="0"></canvas>
<div id="bar"></div>
<script type="module">
import { play } from "./abyss-web.js";

const bar = document.getElementById("bar");
const started = await play({
  progress: (done) => (bar.style.width = `${done * 100}%`),   // 0 to 1
  status: (doing) => console.log(doing),                      // "Loading", "Ready", then "Starting"
  failed: (why) => (bar.textContent = why),
});
</script>
OptionWhat it is told, or does
progressHow much of the game and its packs has arrived, from 0 to 1
statusWhat it is doing: "Loading", "Ready", then "Starting"
readyA function returning a promise, waited for once everything is loaded and before the game starts: a press of a Play button. A browser starts no sound before the player presses something, so waiting for one lets the game's sound start with its first frame.
failedWhy the game could not play: a browser that cannot draw it, a file that could not be fetched, a game that stopped as it started

play returns a promise of whether the game started. The canvas fills whatever holds it, so give its parent the size the game should have.

The build fills these places in the page, as it fills the engine's own:

PlaceWhat the build writes
@ABYSS_TITLE@The game's name
@ABYSS_ICON@An <img class="icon"> of the Player's Default Icon
@ABYSS_FAVICON@The <link rel="icon"> that gives the browser's tab that icon
@ABYSS_BACKGROUND@Player's Background Color, #rrggbb
@ABYSS_ACCENT@Player's Accent Color
@ABYSS_ON_ACCENT@A color for text on the accent: near black on a light accent, white on a dark one
@ABYSS_INK@A color for text on the background: dark on a light background, light on a dark one
@ABYSS_MUTED@The text color mixed toward the background, for quieter text
@ABYSS_BADGE@Nothing, or hidden where Engine Badge is unticked, for an element that says Made with Abyss Engine

Code that differs in a browser

A game for the web is compiled with ABYSS_WEB defined, and so are its packages. The editor and a desktop build do not define it. Use it for what the game does differently in a browser:

schedule.AddFlow("Regions", async flow =>{    for (int region = 0; region < 64; region++)    {#if ABYSS_WEB        Generate(region);                          // one thread in a browser: a region a frame        await flow.NextFrame();#else        await Task.Run(() => Generate(region));    // another core on the desktop#endif    }});

In a browser:

  • The game has one thread. Work handed to another thread, such as with Task.Run, does not run. Do it on the frame, a piece at a time, as above.
  • Sound starts with the first key press, click or touch, as browsers start none before one. Click to Play waits for that press before the game starts.
  • The browser keeps some keys. Ctrl+W, Ctrl+T and Ctrl+N are the browser's, whatever the game binds them to.
  • The mouse stays locked while the game wants it. When the browser lets go of it, as it does when the player presses Escape, the game is told Escape was pressed, and the next click on the game locks it again.

In the Scripting API