publish remote client (#58)
Some checks are pending
Server - Release / release (push) Waiting to run

* add panic hook

* settler movement restriction

* remote server

* publish client

* publish client

* publish client

* publish client

* add dependabot.yml

* fmt

* publish client

* publish client

* fix end turn

* publish client

* publish client

* publish client

* publish client
This commit is contained in:
Gregor Zeitlinger 2024-10-02 17:29:24 +02:00 • committed by GitHub
commit bba2d10a5b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
28 changed files with 209 additions and 271 deletions

12
.github/dependabot.yml vendored Normal file
View file

@ -0,0 +1,12 @@
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: weekly
- package-ecosystem: cargo
directory: "/"
schedule:
interval: daily

View file

@ -22,7 +22,18 @@ jobs:
- uses: jetli/wasm-pack-action@v0.4.0
with:
version: 'latest'
# see https://stackoverflow.com/questions/58177786/get-the-current-pushed-tag-in-github-actions
- run: ./scripts/publish-server.sh ${{ github.event.release.tag_name }}
- uses: jetli/wasm-bindgen-action@v0.2.0
with:
version: 'latest'
- name: Publish Server
# see https://stackoverflow.com/questions/58177786/get-the-current-pushed-tag-in-github-actions
run: |
./scripts/publish-server.sh ${{ github.event.release.tag_name }}
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Publish Client
# rustup target add wasm32-unknown-unknown # automatically done by wasm-pack
run: |
./scripts/publish-client.sh ${{ github.event.release.tag_name }}
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

View file

@ -9,20 +9,10 @@
- `cd client`
- `cargo run`.
### Run local web client
### Run remote with boardgamers-mono web client locally
- `cd client`
- `./build-local.sh local_client`
- `cd dist`
- `basic-http-server .`
- open `http://localhost:4000` in a browser.
### Run remote web client locally
- `cd client`
- `./build-remote.sh`
- `cd remote_client/dist`
- `basic-http-server .`
- `./scripts/build-remote-client.sh`
- `cd client/js/dist && basic-http-server .`
- `google-chrome --disable-web-security --user-data-dir=/tmp http://localhost:8612`
### Server wrapper
@ -45,8 +35,8 @@
- `docker run -d -p 27017:27017 mongo:4.4`
- `cd apps/api && pnpm seed && echo cron=1 > .env`
- `pnpm dev --filter @bgs/api --filter @bgs/game-server --filter @bgs/web --filter @bgs/admin`
- admin: http://localhost:3000 (admin@test.com/password)
- user: http://localhost:8612/ (user@test.com/password)
- admin: http://localhost:3000 (admin@test.com / password)
- user: http://localhost:8612/ (user@test.com / password)
old
@ -102,7 +92,7 @@ diff --git a/apps/api/app/resources.ts b/apps/api/app/resources.ts
const viewer: ViewerInfo =
gameInfo?.viewer?.alternate?.url && ctx.query.alternate === "1" ? gameInfo?.viewer.alternate : gameInfo.viewer;
- const viewerUrl = ctx.query.customViewerUrl || viewer.url;
+ const viewerUrl = "/home/gregor/source/clash/client/remote_client/index.js";
+ const viewerUrl = "http://127.0.0.1:4000/client.js";
ctx.body = `
<html>
@ -148,7 +138,7 @@ GameInfo.json (for now)
"preferences": [],
"rules": "",
"viewer": {
"url": "http://localhost:4000/client.js",
"url": "//cdn.jsdelivr.net/npm/@boardgamers/clash-client@0.0.5/client.js",
"topLevelVariable": "clash",
"dependencies": {
"scripts": [],

12
client/Cargo.lock generated
View file

@ -205,6 +205,7 @@ name = "client"
version = "0.1.0"
dependencies = [
"async-std",
"console_error_panic_hook",
"hex2d",
"itertools",
"lazy_static",
@ -232,6 +233,16 @@ dependencies = [
"crossbeam-utils",
]
[[package]]
name = "console_error_panic_hook"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc"
dependencies = [
"cfg-if",
"wasm-bindgen",
]
[[package]]
name = "crc32fast"
version = "1.4.2"
@ -785,6 +796,7 @@ name = "server"
version = "0.1.0"
dependencies = [
"async-std",
"console_error_panic_hook",
"hex2d",
"itertools",
"quad-rand",

View file

@ -14,15 +14,6 @@ debug = true
[profile.release]
debug = true
[features]
# disable file import and export
wasm = []
# may be needed for remote client
#[lib]
#name = "client"
#crate-type = ["cdylib", "rlib"]
[dependencies]
macroquad = "0.4.2"
hex2d = "1.1.0"
@ -35,6 +26,7 @@ lazy_static = "1.4.0"
log = "0.4.20"
async-std = "1.13.0"
serde-wasm-bindgen = "0.6.5"
console_error_panic_hook = "0.1.7"
[[bin]]
name = "local_client"

View file

@ -1,153 +0,0 @@
#!/usr/bin/env bash
set -e
# from https://gist.github.com/nicolas-sabbatini/8af10dddc96be76d2bf24fc671131add
HELP_STRING=$(
cat <<-END
usage: build_wasm.sh PROJECT_NAME [--release]
Build script for combining a Macroquad project with wasm-bindgen,
allowing integration with the greater wasm-ecosystem.
example: ./build_wasm.sh flappy-bird
This'll go through the following steps:
1. Build as target 'wasm32-unknown-unknown'.
2. Create the directory 'dist' if it doesn't already exist.
3. Run wasm-bindgen with output into the 'dist' directory.
- If the '--release' flag is provided, the build will be optimized for release.
4. Apply patches to the output js file (detailed here: https://github.com/not-fl3/macroquad/issues/212#issuecomment-835276147).
5. Generate coresponding 'index.html' file.
Author: Tom Solberg <me@sbg.dev>
Edit: Nik codes <nik.code.things@gmail.com>
Edit: Nobbele <realnobbele@gmail.com>
Edit: profan <robinhubner@gmail.com>
Edit: Nik codes <nik.code.things@gmail.com>
Version: 0.4
END
)
die() {
echo >&2 "$HELP_STRING"
echo >&2
echo >&2 "Error: $*"
exit 1
}
# Parse primary commands
while [[ $# -gt 0 ]]; do
key="$1"
case $key in
--release)
RELEASE=yes
shift
;;
-h | --help)
echo "$HELP_STRING"
exit 0
;;
*)
POSITIONAL+=("$1")
shift
;;
esac
done
# Restore positionals
set -- "${POSITIONAL[@]}"
[ $# -ne 1 ] && die "too many arguments provided"
PROJECT_NAME=$1
HTML=$(
cat <<-END
<html lang="en">
<head>
<meta charset="utf-8">
<title>${PROJECT_NAME}</title>
<style>
html,
body,
canvas {
margin: 0px;
padding: 0px;
width: 100%;
height: 100%;
overflow: hidden;
position: absolute;
z-index: 0;
}
</style>
</head>
<body >
<canvas id="glcanvas" tabindex='1' hidden></canvas>
<script src="https://not-fl3.github.io/miniquad-samples/mq_js_bundle.js"></script>
<script type="module">
import init, { set_wasm } from "./${PROJECT_NAME}.js";
async function impl_run() {
let wbg = await init();
miniquad_add_plugin({
register_plugin: (a) => (a.wbg = wbg),
on_init: () => set_wasm(wasm_exports),
version: "0.0.1",
name: "wbg",
});
load("./${PROJECT_NAME}_bg.wasm");
}
window.run = function() {
document.getElementById("run-container").remove();
document.getElementById("glcanvas").removeAttribute("hidden");
document.getElementById("glcanvas").focus();
impl_run();
}
</script>
<div id="run-container" style="display: flex; justify-content: center; align-items: center; height: 100%; flex-direction: column;">
<button onclick="run()">Run Game</button>
</div>
</body>
</html>
END
)
OUTER=$(
cat <<-END
<html lang="en">
<body><iframe src="iframe.html">
</iframe></body>
</html>
END
)
TARGET_DIR="target/wasm32-unknown-unknown"
# Build
echo "Building $PROJECT_NAME..."
if [ -n "$RELEASE" ]; then
cargo build --release --target wasm32-unknown-unknown --features "wasm"
TARGET_DIR="$TARGET_DIR/release"
else
cargo build --target wasm32-unknown-unknown --features "wasm"
TARGET_DIR="$TARGET_DIR/debug"
fi
# Generate bindgen outputs
echo "Running wasm-bindgen..."
mkdir -p dist
cp -r assets dist/
wasm-bindgen $TARGET_DIR/"$PROJECT_NAME".wasm --out-dir dist --target web --no-typescript
echo "Patching wasm-bindgen output..."
# Shim to tie the thing together
sed -i "s/import \* as __wbg_star0 from 'env';//" dist/"$PROJECT_NAME".js
sed -i "s/let wasm;/let wasm; export const set_wasm = (w) => wasm = w;/" dist/"$PROJECT_NAME".js
sed -i "s/imports\['env'\] = __wbg_star0;/return imports.wbg\;/" dist/"$PROJECT_NAME".js
sed -i "s/const imports = __wbg_get_imports();/return __wbg_get_imports();/" dist/"$PROJECT_NAME".js
# Create index from the HTML variable
echo "$HTML" >dist/iframe.html
echo "$OUTER" >dist/index.html
echo "Done!"

View file

@ -1,6 +1,6 @@
{
"name": "remote_client",
"version": "1.0.0",
"name": "@boardgamers/clash-client",
"version": "0.1.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {

27
client/js/package.json Normal file
View file

@ -0,0 +1,27 @@
{
"name": "@boardgamers/clash-client",
"description": "A client for Clash of Cultures",
"version": "0.1.0",
"license": "MIT",
"repository": {
"type": "git",
"url": "git@github.com:boardgamers/clash.git"
},
"files": [
"assets/",
"client.js",
"client.wasm"
],
"main": "index.js",
"homepage": "https://www.boardgamers.space/",
"scripts": {
"build": "webpack"
},
"devDependencies": {
"webpack": "^5.94.0",
"webpack-cli": "^5.1.4"
},
"dependencies": {
"events": "^3.3.0"
}
}

View file

@ -5,10 +5,16 @@ export class Control extends EventEmitter {
super();
this.state = null;
this.player_index = null;
this._assets_url = null;
this.addListener("state", (data) => {
this.state = data;
});
// When we receive log slices, when executing a move
this.addListener("gamelog", (logData) => {
// Ignore the log data and tell the backend we want the new state
this.emit("fetchState");
});
this.addListener("state:updated", () => {
this.emit("fetchState");
});
@ -36,6 +42,14 @@ export class Control extends EventEmitter {
send_ready() {
this.emit("ready");
}
get assets_url() {
return this._assets_url;
}
set assets_url(value) {
this._assets_url = value;
}
}
export function get_control() {

View file

@ -6,7 +6,7 @@ window.clash = {
const control = new Control();
window.clash_control = control;
run(selector);
run(selector, control);
return control;
},

View file

@ -8,7 +8,7 @@ function dynamicallyLoadScript(url, onload) {
document.head.appendChild(script);
}
export async function run(selector) {
export async function run(selector, control) {
const root = document.querySelector(selector);
const canvas = document.createElement("canvas");
canvas.setAttribute("id", "glcanvas");
@ -31,7 +31,9 @@ export async function run(selector) {
version: "0.0.1",
name: "wbg",
});
const url = document.head.getElementsByTagName("script")[0].src.replace("client.js", "client.wasm");
const src = document.head.getElementsByTagName("script")[0].src;
control.assets_url = src.replace("client.js", "assets/");
const url = src.replace("client.js", "client.wasm");
console.log("Loading wasm from", url);
await load(url);
});

View file

@ -1,20 +0,0 @@
{
"name": "remote_client",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "MIT",
"devDependencies": {
"webpack": "^5.94.0",
"webpack-cli": "^5.1.4"
},
"dependencies": {
"events": "^3.3.0"
}
}

View file

@ -25,21 +25,15 @@ impl Assets {
let mut map: HashMap<Terrain, Texture2D> = HashMap::new();
for (t, f) in [
(Terrain::Barren, "assets/barren.png"),
(Terrain::Mountain, "assets/mountain.png"),
(Terrain::Fertile, "assets/grassland.png"),
(Terrain::Forest, "assets/forest.png"),
(Terrain::Water, "assets/water.png"),
(Terrain::Barren, "barren.png"),
(Terrain::Mountain, "mountain.png"),
(Terrain::Fertile, "grassland.png"),
(Terrain::Forest, "forest.png"),
(Terrain::Water, "water.png"),
] {
let p = if features.local_assets {
f
} else {
// todo use asset prefix feature
&format!("http://localhost:4000/{f}")
};
map.insert(t, load_texture(p).await.unwrap());
let url = &features.assets_url;
map.insert(t, load_texture(&format!("{url}{f}")).await.unwrap());
}
map
}
}

View file

@ -203,7 +203,7 @@ pub fn try_click(game: &Game, state: &State, player: &ShownPlayer) -> StateUpdat
pub struct Features {
pub import_export: bool,
pub local_assets: bool,
pub assets_url: String,
}
pub enum GameSyncRequest {

View file

@ -233,14 +233,6 @@ impl State {
false
}
#[must_use]
pub fn has_modal_dialog(&self) -> bool {
!matches!(
self.active_dialog,
ActiveDialog::None | ActiveDialog::TileMenu(_) | ActiveDialog::Log
)
}
pub fn update(&mut self, game: &Game, update: StateUpdate) -> GameSyncRequest {
match update {
StateUpdate::None => GameSyncRequest::None,

View file

@ -6,11 +6,10 @@ use server::game::Game;
#[macroquad::main("Clash")]
async fn main() {
set_fullscreen(true);
let wasm = cfg!(feature = "wasm");
let features = Features {
import_export: !wasm,
local_assets: !wasm,
import_export: false,
assets_url: "assets/".to_string(),
};
//todo add button to decide random or fixed game

View file

@ -163,27 +163,25 @@ pub fn show_global_controls(game: &Game, state: &State) -> StateUpdate {
if game.can_redo() && root_ui().button(vec2(1250., 320.), "Redo") {
return StateUpdate::Execute(Action::Redo);
}
match game.state {
GameState::Playing if root_ui().button(vec2(1200., 350.), "End Turn") => {
let left = game.actions_left;
StateUpdate::execute_with_warning(
Action::Playing(PlayingAction::EndTurn),
if left > 0 {
vec![format!("{left} actions left")]
} else {
vec![]
},
)
}
GameState::Playing
if !state.has_modal_dialog()
&& player.can_play_action
&& root_ui().button(vec2(1200., 30.), "Move Units") =>
{
StateUpdate::execute(Action::Playing(PlayingAction::MoveUnits))
}
_ => StateUpdate::None,
if player.can_control
&& matches!(game.state, GameState::Playing)
&& root_ui().button(vec2(1200., 350.), "End Turn")
{
let left = game.actions_left;
return StateUpdate::execute_with_warning(
Action::Playing(PlayingAction::EndTurn),
if left > 0 {
vec![format!("{left} actions left")]
} else {
vec![]
},
);
}
if player.can_play_action && root_ui().button(vec2(1200., 30.), "Move Units") {
return StateUpdate::execute(Action::Playing(PlayingAction::MoveUnits));
}
StateUpdate::None
}
pub fn player_color(player_index: usize) -> Color {

View file

@ -2,9 +2,11 @@ use server::game::Game;
use macroquad::prelude::next_frame;
extern crate console_error_panic_hook;
use client::client::{init, render_and_update, Features, GameSyncRequest, GameSyncResult};
use client::client_state::State;
use server::action::Action;
use std::panic;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
@ -13,7 +15,7 @@ extern "C" {
fn log(s: &str);
}
#[wasm_bindgen(module = "/remote_client/src/control.js")]
#[wasm_bindgen(module = "/js/src/control.js")]
extern "C" {
type Control;
@ -26,10 +28,13 @@ extern "C" {
fn receive_player_index(this: &Control) -> JsValue;
#[wasm_bindgen(method)]
fn send_move(this: &Control, action: &str);
fn send_move(this: &Control, action: JsValue);
#[wasm_bindgen(method)]
fn send_ready(this: &Control);
#[wasm_bindgen(method, getter)]
fn assets_url(this: &Control) -> String;
}
enum SyncState {
@ -55,14 +60,16 @@ async fn main() {
#[wasm_bindgen]
impl RemoteClient {
pub async fn start() {
panic::set_hook(Box::new(console_error_panic_hook::hook));
let control = get_control();
let features = Features {
import_export: false,
local_assets: false,
assets_url: control.assets_url(),
};
let state = init(&features).await;
let mut client = RemoteClient {
control: get_control(),
control,
state,
sync_state: SyncState::New,
game: None,
@ -118,7 +125,7 @@ impl RemoteClient {
fn execute_action(&mut self, a: &Action) {
if let SyncState::Playing = &self.sync_state {
self.control
.send_move(serde_json::to_string(&a).unwrap().as_str());
.send_move(serde_wasm_bindgen::to_value(&a).unwrap());
self.sync_state = SyncState::WaitingForUpdate;
} else {
log("cannot execute action");

View file

@ -143,9 +143,9 @@ pub fn name(u: &UnitType) -> &str {
pub fn label(unit: &Unit) -> String {
let name = name(&unit.unit_type);
let res = if !unit.can_move() || (unit.unit_type == UnitType::Settler && !unit.can_attack()) {
let res = if !unit.can_move() {
" (can't move) "
} else if !unit.can_attack() {
} else if !unit.can_attack() && !unit.unit_type.is_settler() {
" (can't attack) "
} else {
""

View file

@ -1,6 +1,6 @@
#!/usr/bin/env bash
set -e
set -euo pipefail
# from https://gist.github.com/nicolas-sabbatini/8af10dddc96be76d2bf24fc671131add
@ -17,6 +17,7 @@ die() {
exit 1
}
RELEASE=no
# Parse primary commands
while [[ $# -gt 0 ]]; do
key="$1"
@ -42,16 +43,18 @@ done
set -- "${POSITIONAL[@]}"
[ $# -ne 0 ] && die "too many arguments provided"
pushd client
PROJECT_NAME=remote_client
TARGET_DIR="target/wasm32-unknown-unknown"
# Build
echo "Building $PROJECT_NAME..."
if [ -n "$RELEASE" ]; then
cargo build --release --target wasm32-unknown-unknown --features "wasm"
if [ "$RELEASE" == "yes" ]; then
cargo build --release --target wasm32-unknown-unknown
TARGET_DIR="$TARGET_DIR/release"
else
cargo build --target wasm32-unknown-unknown --features "wasm"
cargo build --target wasm32-unknown-unknown
TARGET_DIR="$TARGET_DIR/debug"
fi
@ -60,8 +63,6 @@ echo "Running wasm-bindgen..."
mkdir -p dist
#cp remote_client/*.js dist/
wasm-bindgen $TARGET_DIR/"$PROJECT_NAME".wasm --out-dir dist --target web --no-typescript
echo "Patching wasm-bindgen output..."
@ -71,17 +72,19 @@ sed -i "s/import \* as __wbg_star0 from 'env';//" dist/"$PROJECT_NAME".js
sed -i "s/let wasm;/let wasm; export const set_wasm = (w) => wasm = w;/" dist/"$PROJECT_NAME".js
sed -i "s/imports\['env'\] = __wbg_star0;/return imports.wbg\;/" dist/"$PROJECT_NAME".js
sed -i "s/const imports = __wbg_get_imports();/return __wbg_get_imports();/" dist/"$PROJECT_NAME".js
#sed -i "s#import { get_control }.*#import { get_control } from './control.js'#" dist/"$PROJECT_NAME".js
#rm -rf dist/snippets
pushd remote_client
pushd js
mkdir -p dist
rm -rf dist/*
npm install
npm run build
cp -r ../assets dist/
cp package.json dist/
pushd dist
mv *.wasm client.wasm
popd
popd
popd # js
popd # client
echo "Done!"

View file

@ -2,8 +2,32 @@
set -euo pipefail
RELEASE=no
# Parse primary commands
while [[ $# -gt 0 ]]; do
key="$1"
case $key in
--release)
RELEASE=yes
shift
;;
*)
POSITIONAL+=("$1")
shift
;;
esac
done
ARGS="--dev --debug"
if [ "$RELEASE" = "yes" ]; then
ARGS=""
fi
echo "Building server with release=$RELEASE..."
pushd server
wasm-pack build --target nodejs
wasm-pack build $ARGS --target nodejs
popd
echo "Done!"

20
scripts/publish-client.sh Executable file
View file

@ -0,0 +1,20 @@
#!/usr/bin/env bash
set -euo pipefail
VERSION=${1:-}
if [ -z "$VERSION" ]; then
echo "Usage: $0 <version>"
exit 1
fi
echo "Building client..."
./scripts/build-remote-client.sh # --release
echo "Publishing client..."
pushd client/js/dist
sed -i "s#\"version\": \"0.1.0\"#\"version\": \"$VERSION\"#" package.json
npm publish --access public
popd
echo "Done!"

View file

@ -2,14 +2,14 @@
set -euo pipefail
VERSION=$1
VERSION=${1:-}
if [ -z "$VERSION" ]; then
echo "Usage: $0 <version>"
exit 1
fi
echo "Building server..."
./scripts/build-wasm-server.sh
./scripts/build-wasm-server.sh --release
echo "Publishing server..."
pushd server

11
server/Cargo.lock generated
View file

@ -167,6 +167,16 @@ dependencies = [
"crossbeam-utils",
]
[[package]]
name = "console_error_panic_hook"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc"
dependencies = [
"cfg-if",
"wasm-bindgen",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.20"
@ -559,6 +569,7 @@ name = "server"
version = "0.1.0"
dependencies = [
"async-std",
"console_error_panic_hook",
"hex2d",
"itertools",
"quad-rand",

View file

@ -24,3 +24,4 @@ wasm-bindgen-futures = "0.4.33"
serde-wasm-bindgen = "0.6.0"
itertools = "0.13.0"
quad-rand = "0.2.2"
console_error_panic_hook = "0.1.7"

View file

@ -4,6 +4,7 @@ use serde::{Deserialize, Serialize};
use wasm_bindgen::prelude::*;
use crate::{game::Game, game_api};
extern crate console_error_panic_hook;
#[derive(Serialize, Deserialize)]
pub struct PlayerMetaData {
@ -11,6 +12,7 @@ pub struct PlayerMetaData {
}
fn get_game(data: JsValue) -> Game {
console_error_panic_hook::set_once();
Game::from_data(serde_wasm_bindgen::from_value(data).expect("game should be of type game data"))
}