Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 89 additions & 12 deletions .github/scripts/captures.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Lance le build WebGL dans Chromium headless (rendu logiciel) et prend des captures.
// Usage : node captures.mjs <dossier du build> <dossier de sortie>
// Runs the WebGL build in headless Chromium (software rendering) and takes screenshots.
// The drone is flown with a virtual Xbox 360 pad steering towards the yellow orbs.
// Usage: node captures.mjs <build folder> <output folder>
import { chromium } from 'playwright';
import { createServer } from 'node:http';
import { readFile, mkdir } from 'node:fs/promises';
Expand All @@ -20,29 +21,105 @@ const server = createServer(async (req, res) => {
}
}).listen(8080);

// Virtual gamepad (standard mapping): axes = [left x, left y, right x, right y], button 7 = right trigger.
// window.pad.set({ axes, buttons }) updates it; window.autopilot(true) steers towards yellow pixels.
const padScript = () => {
const pad = {
id: 'Xbox 360 Controller (XInput STANDARD GAMEPAD)', index: 0, connected: true, mapping: 'standard',
axes: [0, 0, 0, 0], buttons: Array.from({ length: 17 }, () => ({ pressed: false, touched: false, value: 0 })),
timestamp: performance.now(),
};
window.pad = {
set({ axes, buttons = {} }) {
if (axes) pad.axes = axes.slice();
pad.buttons = pad.buttons.map((b, i) => (i in buttons ? { pressed: buttons[i] > 0.1, touched: buttons[i] > 0, value: buttons[i] } : b));
pad.timestamp = performance.now();
},
};
// Count the polls to check in the log that the game reads the pad.
window.padPolls = 0;
navigator.getGamepads = () => { window.padPolls++; return [pad, null, null, null]; };
// Keep the WebGL frame readable after presentation, so the autopilot can sample it.
const getContext = HTMLCanvasElement.prototype.getContext;
HTMLCanvasElement.prototype.getContext = function (type, attributes) {
if (type === 'webgl' || type === 'webgl2') attributes = { ...attributes, preserveDrawingBuffer: true };
return getContext.call(this, type, attributes);
};
// The game registers its listeners late (after the wasm start), so announce the pad again later.
window.announcePad = () => {
const event = new Event('gamepadconnected');
event.gamepad = pad;
window.dispatchEvent(event);
};
window.addEventListener('load', window.announcePad);

// Reads the last frame at low resolution and steers towards the centroid of the yellow pixels.
let timer = null;
window.autopilotStats = { frames: 0, seen: 0 };
window.autopilot = (on) => {
clearInterval(timer);
if (!on) return;
const probe = document.createElement('canvas');
probe.width = 96;
probe.height = 60;
const ctx = probe.getContext('2d', { willReadFrequently: true });
timer = setInterval(() => {
const source = document.querySelector('canvas');
ctx.drawImage(source, 0, 0, probe.width, probe.height);
const { data } = ctx.getImageData(0, 0, probe.width, probe.height);
let sx = 0, sy = 0, n = 0;
// Skip the HUD bands and the drone with its yellow exhaust (lower centre).
for (let y = 6; y < probe.height - 8; y++) {
for (let x = 0; x < probe.width; x++) {
if (y > probe.height * 0.4 && x > probe.width * 0.3 && x < probe.width * 0.7) continue;
const i = (y * probe.width + x) * 4;
const [r, g, b] = [data[i], data[i + 1], data[i + 2]];
// Saturated yellow orbs, not the hazy yellowish cliffs nor the orange ground.
if (r > 200 && g > 180 && b < 110 && r - b > 120 && g - b > 100) { sx += x; sy += y; n++; }
}
}
window.autopilotStats.frames++;
window.autopilotStats.brightness = Math.round(data.reduce((sum, v, i) => (i % 4 === 3 ? sum : sum + v), 0) / (data.length * 0.75));
// Without a target, weave and climb a little (the orbs float above the ground).
let steerX = Math.sin(performance.now() / 1500) * 0.4, steerY = 0.3;
if (n > 0) {
window.autopilotStats.seen++;
steerX = Math.max(-1, Math.min(1, (sx / n / probe.width - 0.5) * 3));
steerY = Math.max(-1, Math.min(1, (0.42 - sy / n / probe.height) * 4));
}
// Browsers report stick up as -1 (Unity inverts it back), hence -steerY.
window.pad.set({ axes: [steerX, 0, 0, -steerY], buttons: { 7: 1 } });
}, 100);
};
};

await mkdir(out, { recursive: true });
const browser = await chromium.launch({ args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'] });
const page = await browser.newPage({ viewport: { width: 960, height: 600 } });
page.on('console', (m) => console.log('[jeu]', m.text()));
page.on('console', (m) => console.log('[game]', m.text()));
await page.addInitScript(padScript);
await page.goto('http://localhost:8080/');

const canvas = page.locator('canvas').first();
const shot = async (name, wait) => {
await page.waitForTimeout(wait);
await canvas.screenshot({ path: join(out, `${name}.png`) });
console.log('capture', name);
console.log('screenshot', name);
};

await shot('01-demarrage', 20000);
await shot('01-startup', 20000);
await shot('02-menu', 15000);
// Quelques entrées clavier et souris pour quitter le menu et faire voler le drone.
// Start the game: click the Play button area, then Enter and the pad A button.
await canvas.click();
for (const key of ['Enter', 'Space']) await page.keyboard.press(key);
await shot('03-jeu', 8000);
await page.keyboard.down('ArrowUp');
await shot('04-vol', 4000);
await page.keyboard.up('ArrowUp');
await shot('05-vol', 4000);
await page.keyboard.press('Enter');
await page.evaluate(() => { window.announcePad(); window.pad.set({ buttons: { 0: 1 } }); });
await page.waitForTimeout(300);
await page.evaluate(() => window.pad.set({ buttons: { 0: 0 } }));
await shot('03-game', 8000);

await page.evaluate(() => { window.announcePad(); window.autopilot(true); });
for (let i = 4; i <= 10; i++) await shot(`${String(i).padStart(2, '0')}-flight`, 5000);
console.log('autopilot', JSON.stringify(await page.evaluate(() => ({ ...window.autopilotStats, padPolls: window.padPolls }))));

await browser.close();
server.close();
27 changes: 27 additions & 0 deletions .github/webgl/CIWebGLSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#if UNITY_EDITOR
using System.IO;
using System.Linq;
using UnityEditor;

// Copied into Assets/Editor during the CI build only (never committed to the project).
// Makes the WebGL build loadable on GitHub Pages and selects the scenes to build.
[InitializeOnLoad]
static class CIWebGLSettings
{
const string ScenesFile = "Assets/Editor/webgl-scenes.txt";

static CIWebGLSettings()
{
#if UNITY_2020_1_OR_NEWER
// GitHub Pages sends no Content-Encoding header: the loader decompresses by itself.
PlayerSettings.WebGL.compressionFormat = WebGLCompressionFormat.Gzip;
PlayerSettings.WebGL.decompressionFallback = true;
#endif
if (File.Exists(ScenesFile))
EditorBuildSettings.scenes = File.ReadAllLines(ScenesFile)
.Where(line => line.Trim().Length > 0)
.Select(path => new EditorBuildSettingsScene(path.Trim(), true))
.ToArray();
}
}
#endif
27 changes: 21 additions & 6 deletions .github/workflows/webgl.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Build WebGL du projet Unity via GameCI, captures d'écran automatiques
# et publication de la version jouable sur GitHub Pages.
# Secrets requis : UNITY_LICENSE (contenu du fichier .ulf), UNITY_EMAIL, UNITY_PASSWORD.
# WebGL build of the Unity project with GameCI, automatic screenshots
# and publication of the playable build on GitHub Pages.
# Required secrets: UNITY_LICENSE (content of the .ulf file), UNITY_EMAIL, UNITY_PASSWORD.
name: WebGL

on:
Expand All @@ -16,8 +16,8 @@ concurrency:
cancel-in-progress: true

env:
# Version la plus proche disponible chez GameCI (le projet est en 2019.3.0b6).
UNITY_VERSION: 2019.3.0f1
# Must match ProjectSettings/ProjectVersion.txt (GameCI image unityci/editor:ubuntu-<version>-webgl-3).
UNITY_VERSION: 2023.2.8f1

jobs:
build:
Expand All @@ -34,6 +34,21 @@ jobs:
key: Library-WebGL-${{ env.UNITY_VERSION }}-${{ hashFiles('Packages/manifest.json', 'ProjectSettings/ProjectVersion.txt') }}
restore-keys: Library-WebGL-${{ env.UNITY_VERSION }}-

- name: CI WebGL settings
run: |
mkdir -p Assets/Editor && cp .github/webgl/CIWebGLSettings.cs Assets/Editor/
# The pinned Standard Assets submodule has Editor asmdefs without platform filter, which breaks
# player builds (fixed upstream since): restrict every asmdef under an Editor folder to the editor.
find Assets -path '*/Editor/*.asmdef' -print0 | xargs -0 -r node -e '
const fs = require("fs");
for (const file of process.argv.slice(1)) {
const asmdef = JSON.parse(fs.readFileSync(file, "utf8").replace(/^\uFEFF/, ""));
if ((asmdef.includePlatforms ?? []).length) continue;
asmdef.includePlatforms = ["Editor"];
fs.writeFileSync(file, JSON.stringify(asmdef, null, 4));
console.log("editor only:", file);
}'

- uses: game-ci/unity-builder@v4
env:
UNITY_LICENSE: ${{ secrets.UNITY_LICENSE }}
Expand All @@ -45,7 +60,7 @@ jobs:
buildName: web
allowDirtyBuild: true

- name: Captures d'écran
- name: Screenshots
run: |
sudo chown -R "$USER" build
npm install --no-save --no-package-lock [email protected]
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,5 @@ sysinfo.txt
# Builds
*.apk
*.unitypackage
UserSettings
.vsconfig
15 changes: 15 additions & 0 deletions Assets/DefaultVolumeProfile.asset
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 0}
m_Name: DefaultVolumeProfile
m_EditorClassIdentifier:
components: []
8 changes: 8 additions & 0 deletions Assets/DefaultVolumeProfile.asset.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 4 additions & 16 deletions Assets/DroneEngine/Data/DroneConfigObservation.asset
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,11 @@ MonoBehaviour:
rollSpeed: 100
powerSpeed: 5
maxPower: 40
minPower: 0
pitchPowerPositiveImpact: 0
pitchPowerNegativeImpact: 0
pitchClamp:
clamp: 1
min: -75
max: 75
yawClamp:
clamp: 0
min: -45
max: 45
rollClamp:
clamp: 1
min: -45
max: 45
maxPitchAngle: 55
maxRollAngle: 45
maintainHeight: 1
freeDragRatio: 0.9
horizontalAutoStability: 5
easyDrive: 0
easyDrive: 1
rollToYawRatio: -2
rollToPitchRatio: 0.5
Loading
Loading