Improve gameplay
This commit is contained in:
parent
e02a5b264c
commit
7c76b16d13
53 changed files with 1084 additions and 404 deletions
|
|
@ -1,11 +1,13 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
import {
|
||||
CircleLight,
|
||||
ColorfulCircle,
|
||||
compile,
|
||||
FilteringOptions,
|
||||
Flashlight,
|
||||
Renderer,
|
||||
renderNoise,
|
||||
runAnimation,
|
||||
WrapOptions,
|
||||
} from 'sdf-2d';
|
||||
import {
|
||||
|
|
@ -17,36 +19,41 @@ import {
|
|||
SetAspectRatioActionCommand,
|
||||
rgb,
|
||||
PlayerInformation,
|
||||
PlayerDiedCommand,
|
||||
UpdatePlanetOwnershipCommand,
|
||||
} from 'shared';
|
||||
import io from 'socket.io-client';
|
||||
import { KeyboardListener } from './commands/generators/keyboard-listener';
|
||||
import { MouseListener } from './commands/generators/mouse-listener';
|
||||
import { TouchListener } from './commands/generators/touch-listener';
|
||||
import { CommandReceiverSocket } from './commands/receivers/command-receiver-socket';
|
||||
|
||||
import { DeltaTimeCalculator } from './helper/delta-time-calculator';
|
||||
import { PlayerDecision } from './join-form-handler';
|
||||
import { GameObjectContainer } from './objects/game-object-container';
|
||||
import { BlobShape } from './shapes/blob-shape';
|
||||
import { Circle } from './shapes/circle';
|
||||
import { Polygon } from './shapes/polygon';
|
||||
import { PlanetShape } from './shapes/planet-shape';
|
||||
|
||||
export class Game {
|
||||
public readonly gameObjects = new GameObjectContainer(this);
|
||||
private renderer!: Renderer;
|
||||
private renderer?: Renderer;
|
||||
private socket!: SocketIOClient.Socket;
|
||||
private promises: Promise<[void, void]>;
|
||||
private deltaTimeCalculator = new DeltaTimeCalculator();
|
||||
private deadTimeout = 0;
|
||||
|
||||
private declaPlanetCountElement = document.createElement('div');
|
||||
private redPlanetCountElement = document.createElement('div');
|
||||
private neutralPlanetCountElement = document.createElement('div');
|
||||
|
||||
constructor(
|
||||
private readonly playerDecision: PlayerDecision,
|
||||
private readonly canvas: HTMLCanvasElement,
|
||||
private readonly overlay: HTMLElement,
|
||||
) {
|
||||
this.promises = Promise.all([
|
||||
this.setupCommunication(playerDecision.server),
|
||||
this.setupRenderer(),
|
||||
]);
|
||||
this.start();
|
||||
const progressBar = document.createElement('div');
|
||||
progressBar.className = 'planet-progress';
|
||||
overlay.appendChild(progressBar);
|
||||
progressBar.appendChild(this.declaPlanetCountElement);
|
||||
progressBar.appendChild(this.neutralPlanetCountElement);
|
||||
progressBar.appendChild(this.redPlanetCountElement);
|
||||
}
|
||||
|
||||
private async setupCommunication(serverUrl: string): Promise<void> {
|
||||
|
|
@ -61,7 +68,26 @@ export class Game {
|
|||
|
||||
this.socket.on(TransportEvents.ServerToPlayer, (serialized: string) => {
|
||||
const command = deserialize(serialized);
|
||||
this.gameObjects.sendCommand(command);
|
||||
if (command instanceof PlayerDiedCommand) {
|
||||
this.deadTimeout = command.timeout;
|
||||
this.overlay.appendChild(this.announcmentText);
|
||||
} else if (command instanceof UpdatePlanetOwnershipCommand) {
|
||||
const all = command.declaCount + command.redCount + command.neutralCount;
|
||||
this.declaPlanetCountElement.style.width = (command.declaCount / all) * 100 + '%';
|
||||
this.neutralPlanetCountElement.style.width =
|
||||
(command.neutralCount / all) * 100 + '%';
|
||||
this.redPlanetCountElement.style.width = (command.redCount / all) * 100 + '%';
|
||||
|
||||
if (command.declaCount > all * 0.5) {
|
||||
this.overlay.appendChild(this.announcmentText);
|
||||
this.announcmentText.innerText = 'Decla team won 🎉';
|
||||
}
|
||||
|
||||
if (command.redCount > all * 0.5) {
|
||||
this.overlay.appendChild(this.announcmentText);
|
||||
this.announcmentText.innerText = 'Red team won 🎉';
|
||||
}
|
||||
} else this.gameObjects.sendCommand(command);
|
||||
});
|
||||
|
||||
this.socket.on(TransportEvents.Ping, () => {
|
||||
|
|
@ -82,14 +108,14 @@ export class Game {
|
|||
);
|
||||
}
|
||||
|
||||
private async setupRenderer(): Promise<void> {
|
||||
private async start(): Promise<void> {
|
||||
const noiseTexture = await renderNoise([256, 256], 2, 1);
|
||||
|
||||
this.renderer = await compile(
|
||||
this.setupCommunication(this.playerDecision.server);
|
||||
runAnimation(
|
||||
this.canvas,
|
||||
[
|
||||
{
|
||||
...Polygon.descriptor,
|
||||
...PlanetShape.descriptor,
|
||||
shaderCombinationSteps: [0, 1, 2, 3],
|
||||
},
|
||||
{
|
||||
|
|
@ -97,55 +123,49 @@ export class Game {
|
|||
shaderCombinationSteps: [0, 1, 2, 8],
|
||||
},
|
||||
{
|
||||
...Circle.descriptor,
|
||||
...ColorfulCircle.descriptor,
|
||||
shaderCombinationSteps: [0, 2, 16],
|
||||
},
|
||||
{
|
||||
...CircleLight.descriptor,
|
||||
shaderCombinationSteps: [0, 1, 2, 4, 8],
|
||||
shaderCombinationSteps: [0, 1, 2, 4, 8, 16],
|
||||
},
|
||||
{
|
||||
...Flashlight.descriptor,
|
||||
shaderCombinationSteps: [0],
|
||||
},
|
||||
],
|
||||
this.gameLoop.bind(this),
|
||||
{
|
||||
shadowTraceCount: 16,
|
||||
paletteSize: 10,
|
||||
paletteSize: settings.palette.length,
|
||||
//enableStopwatch: true,
|
||||
},
|
||||
);
|
||||
|
||||
this.renderer.setRuntimeSettings({
|
||||
ambientLight: rgb(0.45, 0.4, 0.45),
|
||||
colorPalette: [
|
||||
rgb(1, 1, 1),
|
||||
rgb(0.4, 0.4, 0.4),
|
||||
rgb(1, 1, 1),
|
||||
...settings.playerColors,
|
||||
],
|
||||
enableHighDpiRendering: true,
|
||||
lightCutoffDistance: settings.lightCutoffDistance,
|
||||
textures: {
|
||||
noiseTexture: {
|
||||
source: noiseTexture,
|
||||
overrides: {
|
||||
maxFilter: FilteringOptions.LINEAR,
|
||||
wrapS: WrapOptions.MIRRORED_REPEAT,
|
||||
wrapT: WrapOptions.MIRRORED_REPEAT,
|
||||
{
|
||||
ambientLight: rgb(0.45, 0.4, 0.45),
|
||||
colorPalette: settings.palette,
|
||||
enableHighDpiRendering: true,
|
||||
lightCutoffDistance: settings.lightCutoffDistance,
|
||||
textures: {
|
||||
noiseTexture: {
|
||||
source: noiseTexture,
|
||||
overrides: {
|
||||
maxFilter: FilteringOptions.LINEAR,
|
||||
wrapS: WrapOptions.MIRRORED_REPEAT,
|
||||
wrapT: WrapOptions.MIRRORED_REPEAT,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
public async start(): Promise<void> {
|
||||
await this.promises;
|
||||
requestAnimationFrame(this.gameLoop.bind(this));
|
||||
);
|
||||
}
|
||||
|
||||
public displayToWorldCoordinates(p: vec2): vec2 {
|
||||
return this.renderer?.displayToWorldCoordinates(p);
|
||||
const result = this.renderer?.displayToWorldCoordinates(p);
|
||||
if (!result) {
|
||||
return vec2.create();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public aspectRatioChanged(aspectRatio: number) {
|
||||
|
|
@ -155,14 +175,23 @@ export class Game {
|
|||
);
|
||||
}
|
||||
|
||||
private gameLoop(time: DOMHighResTimeStamp) {
|
||||
const deltaTime = this.deltaTimeCalculator.getNextDeltaTimeInMilliseconds(time);
|
||||
private announcmentText = document.createElement('h2');
|
||||
private gameLoop(
|
||||
renderer: Renderer,
|
||||
currentTime: DOMHighResTimeStamp,
|
||||
deltaTime: DOMHighResTimeStamp,
|
||||
): boolean {
|
||||
this.renderer = renderer;
|
||||
|
||||
if ((this.deadTimeout -= deltaTime / 1000) > 0) {
|
||||
this.announcmentText.innerText = `Respawning in ${Math.floor(this.deadTimeout)} …`;
|
||||
} else {
|
||||
this.announcmentText.parentElement?.removeChild(this.announcmentText);
|
||||
}
|
||||
|
||||
this.gameObjects.stepObjects(deltaTime);
|
||||
this.gameObjects.drawObjects(this.renderer);
|
||||
this.renderer.renderDrawables();
|
||||
this.gameObjects.drawObjects(this.renderer, this.overlay);
|
||||
|
||||
// this.overlay.innerText = prettyPrint(this.renderer.insights);
|
||||
requestAnimationFrame(this.gameLoop.bind(this));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
27
frontend/src/scripts/handle-full-screen.ts
Normal file
27
frontend/src/scripts/handle-full-screen.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
export const handleFullScreen = (
|
||||
minimizeButton: HTMLElement,
|
||||
maximizeButton: HTMLElement,
|
||||
) => {
|
||||
if (!document.fullscreenEnabled) {
|
||||
minimizeButton.style.visibility = 'hidden';
|
||||
maximizeButton.style.visibility = 'hidden';
|
||||
return;
|
||||
}
|
||||
|
||||
let isInFullScreen = document.fullscreenElement !== null;
|
||||
|
||||
const showButtons = () => {
|
||||
minimizeButton.style.visibility = isInFullScreen ? 'visible' : 'hidden';
|
||||
maximizeButton.style.visibility = isInFullScreen ? 'hidden' : 'visible';
|
||||
};
|
||||
|
||||
showButtons();
|
||||
|
||||
maximizeButton.addEventListener('click', () => document.body.requestFullscreen());
|
||||
minimizeButton.addEventListener('click', () => document.exitFullscreen());
|
||||
|
||||
document.addEventListener('fullscreenchange', () => {
|
||||
isInFullScreen = !isInFullScreen;
|
||||
showButtons();
|
||||
});
|
||||
};
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
export class DeltaTimeCalculator {
|
||||
private previousTime: DOMHighResTimeStamp | null = null;
|
||||
|
||||
constructor() {
|
||||
document.addEventListener('visibilitychange', this.handleVisibilityChange.bind(this));
|
||||
}
|
||||
|
||||
public getNextDeltaTimeInMilliseconds(
|
||||
currentTime: DOMHighResTimeStamp,
|
||||
): DOMHighResTimeStamp {
|
||||
if (this.previousTime === null) {
|
||||
this.previousTime = currentTime;
|
||||
}
|
||||
|
||||
const delta = currentTime - this.previousTime;
|
||||
this.previousTime = currentTime;
|
||||
return delta;
|
||||
}
|
||||
|
||||
private handleVisibilityChange() {
|
||||
if (!document.hidden) {
|
||||
this.previousTime = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@ import {
|
|||
NoisyPolygonFactory,
|
||||
Renderer,
|
||||
renderNoise,
|
||||
runAnimation,
|
||||
WrapOptions,
|
||||
} from 'sdf-2d';
|
||||
import { settings, rgb, PlanetBase, Random } from 'shared';
|
||||
|
|
@ -18,17 +19,17 @@ const LangindPagePolygon = NoisyPolygonFactory(
|
|||
);
|
||||
|
||||
export class LandingPageBackground {
|
||||
private renderer!: Renderer;
|
||||
private isActive = true;
|
||||
|
||||
constructor(private readonly canvas: HTMLCanvasElement) {
|
||||
this.start();
|
||||
constructor(canvas: HTMLCanvasElement) {
|
||||
this.start(canvas);
|
||||
}
|
||||
|
||||
private async start(): Promise<void> {
|
||||
private async start(canvas: HTMLCanvasElement): Promise<void> {
|
||||
const noiseTexture = await renderNoise([256, 256], 1.2, 2);
|
||||
|
||||
this.renderer = await compile(
|
||||
this.canvas,
|
||||
runAnimation(
|
||||
canvas,
|
||||
[
|
||||
{
|
||||
...LangindPagePolygon.descriptor,
|
||||
|
|
@ -39,45 +40,36 @@ export class LandingPageBackground {
|
|||
shaderCombinationSteps: [0, 2],
|
||||
},
|
||||
],
|
||||
this.gameLoop.bind(this),
|
||||
{
|
||||
shadowTraceCount: 16,
|
||||
paletteSize: 1,
|
||||
},
|
||||
);
|
||||
|
||||
this.renderer.setRuntimeSettings({
|
||||
ambientLight: rgb(0, 0, 0),
|
||||
lightCutoffDistance: settings.lightCutoffDistance,
|
||||
textures: {
|
||||
noiseTexture: {
|
||||
source: noiseTexture,
|
||||
overrides: {
|
||||
maxFilter: FilteringOptions.LINEAR,
|
||||
wrapS: WrapOptions.MIRRORED_REPEAT,
|
||||
wrapT: WrapOptions.MIRRORED_REPEAT,
|
||||
{
|
||||
ambientLight: rgb(0, 0, 0),
|
||||
lightCutoffDistance: settings.lightCutoffDistance,
|
||||
textures: {
|
||||
noiseTexture: {
|
||||
source: noiseTexture,
|
||||
overrides: {
|
||||
maxFilter: FilteringOptions.LINEAR,
|
||||
wrapS: WrapOptions.MIRRORED_REPEAT,
|
||||
wrapT: WrapOptions.MIRRORED_REPEAT,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
requestAnimationFrame(this.gameLoop.bind(this));
|
||||
);
|
||||
}
|
||||
|
||||
public destroy() {
|
||||
this.renderer.destroy();
|
||||
}
|
||||
|
||||
private gameLoop(time: DOMHighResTimeStamp) {
|
||||
private gameLoop(renderer: Renderer, time: DOMHighResTimeStamp, _: number): boolean {
|
||||
Random.seed = 42;
|
||||
|
||||
this.renderer.setViewArea(
|
||||
vec2.fromValues(0, this.renderer.canvasSize.y),
|
||||
this.renderer.canvasSize,
|
||||
);
|
||||
renderer.setViewArea(vec2.fromValues(0, renderer.canvasSize.y), renderer.canvasSize);
|
||||
|
||||
const topPlanetPosition = vec2.fromValues(
|
||||
0.7 * this.renderer.canvasSize.x,
|
||||
0.7 * this.renderer.canvasSize.y,
|
||||
0.7 * renderer.canvasSize.x,
|
||||
0.7 * renderer.canvasSize.y,
|
||||
);
|
||||
|
||||
const topPlanet = new LangindPagePolygon(
|
||||
|
|
@ -93,8 +85,8 @@ export class LandingPageBackground {
|
|||
(topPlanet as any).randomOffset = 0.5 + time / 3500;
|
||||
|
||||
const bottomPlanetPosition = vec2.fromValues(
|
||||
0.3 * this.renderer.canvasSize.x,
|
||||
0.3 * this.renderer.canvasSize.y,
|
||||
0.3 * renderer.canvasSize.x,
|
||||
0.3 * renderer.canvasSize.y,
|
||||
);
|
||||
|
||||
const bottomPlanet = new LangindPagePolygon(
|
||||
|
|
@ -118,11 +110,12 @@ export class LandingPageBackground {
|
|||
const planetDirection = vec2.normalize(planetDistance, planetDistance);
|
||||
const planetAngle = Math.atan2(planetDirection.y, planetDirection.x);
|
||||
|
||||
this.renderer.addDrawable(topPlanet);
|
||||
this.renderer.addDrawable(bottomPlanet);
|
||||
this.renderer.addDrawable(
|
||||
renderer.addDrawable(topPlanet);
|
||||
renderer.addDrawable(bottomPlanet);
|
||||
renderer.addDrawable(
|
||||
new CircleLight(
|
||||
this.calculateLightPosition(
|
||||
renderer,
|
||||
planetAngle,
|
||||
planetDistanceLength * 1.2,
|
||||
-time / 3000,
|
||||
|
|
@ -132,9 +125,10 @@ export class LandingPageBackground {
|
|||
),
|
||||
);
|
||||
|
||||
this.renderer.addDrawable(
|
||||
renderer.addDrawable(
|
||||
new CircleLight(
|
||||
this.calculateLightPosition(
|
||||
renderer,
|
||||
planetAngle,
|
||||
planetDistanceLength * 1.2,
|
||||
time / 2000 + Math.PI,
|
||||
|
|
@ -144,21 +138,28 @@ export class LandingPageBackground {
|
|||
),
|
||||
);
|
||||
|
||||
this.renderer.renderDrawables();
|
||||
|
||||
requestAnimationFrame(this.gameLoop.bind(this));
|
||||
return this.isActive;
|
||||
}
|
||||
|
||||
private calculateLightPosition(angle: number, length: number, t: number): vec2 {
|
||||
private calculateLightPosition(
|
||||
renderer: Renderer,
|
||||
angle: number,
|
||||
length: number,
|
||||
t: number,
|
||||
): vec2 {
|
||||
const lightPosition = vec2.fromValues(
|
||||
length * Math.sin(t),
|
||||
length * Math.sin(t) * Math.cos(t),
|
||||
);
|
||||
|
||||
const canvasCenter = vec2.scale(vec2.create(), this.renderer.canvasSize, 0.5);
|
||||
const canvasCenter = vec2.scale(vec2.create(), renderer.canvasSize, 0.5);
|
||||
|
||||
vec2.add(lightPosition, lightPosition, canvasCenter);
|
||||
vec2.rotate(lightPosition, lightPosition, canvasCenter, angle);
|
||||
return lightPosition;
|
||||
}
|
||||
|
||||
public destroy() {
|
||||
this.isActive = false;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,13 +14,11 @@ export class Camera extends GameObject implements ViewObject {
|
|||
super(null);
|
||||
}
|
||||
|
||||
public update(updates: Array<UpdateMessage>) {
|
||||
throw new Error();
|
||||
}
|
||||
public beforeDestroy(): void {}
|
||||
|
||||
public step(deltaTimeInMilliseconds: number): void {}
|
||||
|
||||
public draw(renderer: Renderer) {
|
||||
public draw(renderer: Renderer, overlay: HTMLElement) {
|
||||
const canvasAspectRatio = renderer.canvasSize.x / renderer.canvasSize.y;
|
||||
if (canvasAspectRatio !== this.aspectRatio) {
|
||||
this.aspectRatio = canvasAspectRatio;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
import { Renderer } from 'sdf-2d';
|
||||
import { CharacterBase, Circle, Id, UpdateMessage } from 'shared';
|
||||
import { CharacterBase, CharacterTeam, Circle, Id, UpdateMessage } from 'shared';
|
||||
|
||||
import { BlobShape } from '../shapes/blob-shape';
|
||||
import { ViewObject } from './view-object';
|
||||
|
|
@ -11,25 +11,25 @@ export class CharacterView extends CharacterBase implements ViewObject {
|
|||
constructor(
|
||||
id: Id,
|
||||
colorIndex: number,
|
||||
team: CharacterTeam,
|
||||
health: number,
|
||||
head?: Circle,
|
||||
leftFoot?: Circle,
|
||||
rightFoot?: Circle,
|
||||
) {
|
||||
super(id, colorIndex, head, leftFoot, rightFoot);
|
||||
super(id, colorIndex, team, health, head, leftFoot, rightFoot);
|
||||
this.shape = new BlobShape(colorIndex);
|
||||
}
|
||||
|
||||
public update(updates: Array<UpdateMessage>) {
|
||||
updates.forEach((u) => ((this as any)[u.key] = u.value));
|
||||
}
|
||||
|
||||
public get position(): vec2 {
|
||||
return this.head!.center;
|
||||
}
|
||||
|
||||
public beforeDestroy(): void {}
|
||||
|
||||
public step(deltaTimeInMilliseconds: number): void {}
|
||||
|
||||
public draw(renderer: Renderer): void {
|
||||
public draw(renderer: Renderer, overlay: HTMLElement): void {
|
||||
this.shape.setCircles([this.head!, this.leftFoot!, this.rightFoot!]);
|
||||
renderer.addDrawable(this.shape);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ export class GameObjectContainer extends CommandReceiver {
|
|||
protected commandExecutors: CommandExecutors = {
|
||||
[CreatePlayerCommand.type]: (c: CreatePlayerCommand) => {
|
||||
this.player = c.character as PlayerCharacterView;
|
||||
console.log(c.character);
|
||||
this.camera = new Camera(this.game);
|
||||
this.addObject(this.player);
|
||||
this.addObject(this.camera);
|
||||
|
|
@ -31,7 +32,7 @@ export class GameObjectContainer extends CommandReceiver {
|
|||
c.objects.forEach((o) => this.addObject(o as ViewObject)),
|
||||
|
||||
[DeleteObjectsCommand.type]: (c: DeleteObjectsCommand) =>
|
||||
c.ids.forEach((id: Id) => this.objects.delete(id)),
|
||||
c.ids.forEach((id: Id) => this.deleteObject(id)),
|
||||
|
||||
[UpdateObjectsCommand.type]: (c: UpdateObjectsCommand) => {
|
||||
c.updates.forEach((u) => this.objects.get(u.id)?.update(u.updates));
|
||||
|
|
@ -50,11 +51,17 @@ export class GameObjectContainer extends CommandReceiver {
|
|||
this.objects.forEach((o) => o.step(delta));
|
||||
}
|
||||
|
||||
public drawObjects(renderer: Renderer) {
|
||||
this.objects.forEach((o) => o.draw(renderer));
|
||||
public drawObjects(renderer: Renderer, overlay: HTMLElement) {
|
||||
this.objects.forEach((o) => o.draw(renderer, overlay));
|
||||
}
|
||||
|
||||
private addObject(object: ViewObject) {
|
||||
this.objects.set(object.id, object);
|
||||
}
|
||||
|
||||
private deleteObject(id: Id) {
|
||||
const object = this.objects.get(id);
|
||||
object?.beforeDestroy();
|
||||
this.objects.delete(id);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,13 +16,11 @@ export class LampView extends LampBase implements ViewObject {
|
|||
this.light = new CircleLight(center, color, lightness);
|
||||
}
|
||||
|
||||
public update(message: Array<UpdateMessage>): void {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
|
||||
public step(deltaTimeInMilliseconds: number): void {}
|
||||
|
||||
public draw(renderer: Renderer): void {
|
||||
public beforeDestroy(): void {}
|
||||
|
||||
public draw(renderer: Renderer, overlay: HTMLElement): void {
|
||||
renderer.addDrawable(this.light);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,32 +1,62 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
import { Drawable, Renderer } from 'sdf-2d';
|
||||
import { CommandExecutors, Id, Random, PlanetBase, UpdateMessage } from 'shared';
|
||||
import {
|
||||
CommandExecutors,
|
||||
Id,
|
||||
Random,
|
||||
PlanetBase,
|
||||
UpdateMessage,
|
||||
settings,
|
||||
} from 'shared';
|
||||
import { RenderCommand } from '../commands/types/render';
|
||||
import { Polygon } from '../shapes/polygon';
|
||||
import { PlanetShape } from '../shapes/planet-shape';
|
||||
import { ViewObject } from './view-object';
|
||||
|
||||
export class PlanetView extends PlanetBase implements ViewObject {
|
||||
private shape: Drawable;
|
||||
private shape: PlanetShape;
|
||||
private ownershipProgess: HTMLElement;
|
||||
|
||||
protected commandExecutors: CommandExecutors = {
|
||||
[RenderCommand.type]: (c: RenderCommand) => c.renderer.addDrawable(this.shape),
|
||||
};
|
||||
|
||||
constructor(id: Id, vertices: Array<vec2>) {
|
||||
constructor(id: Id, vertices: Array<vec2>, ownership: number) {
|
||||
super(id, vertices);
|
||||
this.shape = new Polygon(vertices);
|
||||
this.shape = new PlanetShape(vertices, ownership);
|
||||
(this.shape as any).randomOffset = Random.getRandom();
|
||||
}
|
||||
|
||||
public update(message: Array<UpdateMessage>): void {
|
||||
throw new Error('Method not implemented.');
|
||||
this.ownershipProgess = document.createElement('div');
|
||||
this.ownershipProgess.className = 'ownership';
|
||||
}
|
||||
|
||||
public step(deltaTimeInMilliseconds: number): void {
|
||||
(this.shape as any).randomOffset += deltaTimeInMilliseconds / 4000;
|
||||
this.shape.randomOffset += deltaTimeInMilliseconds / 4000;
|
||||
this.shape.colorMixQ = this.ownership;
|
||||
let teamName = 'Neutral';
|
||||
if (this.ownership < 0.5 - settings.planetControlThreshold) {
|
||||
teamName = 'Decla';
|
||||
} else if (this.ownership > 0.5 + settings.planetControlThreshold) {
|
||||
teamName = 'Red';
|
||||
}
|
||||
|
||||
this.ownershipProgess.innerText = `${teamName} ${Math.round(
|
||||
(Math.abs(this.ownership - 0.5) / 0.5) * 100,
|
||||
)}%`;
|
||||
}
|
||||
|
||||
public draw(renderer: Renderer): void {
|
||||
public beforeDestroy(): void {
|
||||
this.ownershipProgess.parentElement?.removeChild(this.ownershipProgess);
|
||||
}
|
||||
|
||||
public draw(renderer: Renderer, overlay: HTMLElement): void {
|
||||
if (!this.ownershipProgess.parentElement) {
|
||||
overlay.appendChild(this.ownershipProgess);
|
||||
}
|
||||
|
||||
const screenPosition = renderer.worldToDisplayCoordinates(this.center);
|
||||
this.ownershipProgess.style.left = screenPosition.x + 'px';
|
||||
this.ownershipProgess.style.top = screenPosition.y + 'px';
|
||||
|
||||
renderer.addDrawable(this.shape);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,37 +1,84 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
import { Renderer } from 'sdf-2d';
|
||||
import { Circle, Id, PlayerCharacterBase, UpdateMessage } from 'shared';
|
||||
import { Circle, Id, PlayerCharacterBase, UpdateMessage, CharacterTeam } from 'shared';
|
||||
|
||||
import { BlobShape } from '../shapes/blob-shape';
|
||||
import { ViewObject } from './view-object';
|
||||
|
||||
export class PlayerCharacterView extends PlayerCharacterBase implements ViewObject {
|
||||
private shape: BlobShape;
|
||||
private nameElement: HTMLElement;
|
||||
private healthElement: HTMLElement;
|
||||
private timeSinceLastNameElementUpdate = 0;
|
||||
|
||||
constructor(
|
||||
id: Id,
|
||||
name: string,
|
||||
colorIndex: number,
|
||||
team: CharacterTeam,
|
||||
health: number,
|
||||
head?: Circle,
|
||||
leftFoot?: Circle,
|
||||
rightFoot?: Circle,
|
||||
) {
|
||||
super(id, name, colorIndex, head, leftFoot, rightFoot);
|
||||
super(id, name, colorIndex, team, health, head, leftFoot, rightFoot);
|
||||
this.shape = new BlobShape(colorIndex);
|
||||
}
|
||||
|
||||
public update(updates: Array<UpdateMessage>) {
|
||||
updates.forEach((u) => ((this as any)[u.key] = u.value));
|
||||
console.log(this.id, 'created');
|
||||
|
||||
this.nameElement = document.createElement('div');
|
||||
this.nameElement.className = 'player-tag';
|
||||
this.nameElement.innerText = this.name;
|
||||
this.healthElement = document.createElement('div');
|
||||
this.nameElement.appendChild(this.healthElement);
|
||||
}
|
||||
|
||||
public get position(): vec2 {
|
||||
return this.head!.center;
|
||||
}
|
||||
|
||||
public step(deltaTimeInMilliseconds: number): void {}
|
||||
public step(deltaTimeInMilliseconds: number): void {
|
||||
this.timeSinceLastNameElementUpdate += deltaTimeInMilliseconds;
|
||||
this.healthElement.style.width = this.health + '%';
|
||||
}
|
||||
|
||||
public beforeDestroy(): void {
|
||||
console.log(this.id, 'destroyes');
|
||||
this.nameElement.parentElement?.removeChild(this.nameElement);
|
||||
}
|
||||
|
||||
private elementAdded = false;
|
||||
public draw(renderer: Renderer, overlay: HTMLElement): void {
|
||||
if (!this.elementAdded) {
|
||||
this.elementAdded = true;
|
||||
console.log(this.id, 'add', this.nameElement, this.nameElement.parentElement);
|
||||
overlay.appendChild(this.nameElement);
|
||||
}
|
||||
|
||||
if (this.timeSinceLastNameElementUpdate > 0.15) {
|
||||
const screenPosition = renderer.worldToDisplayCoordinates(
|
||||
this.calculateTextPosition(),
|
||||
);
|
||||
this.nameElement.style.left = screenPosition.x + 'px';
|
||||
this.nameElement.style.top = screenPosition.y + 'px';
|
||||
this.timeSinceLastNameElementUpdate = 0;
|
||||
}
|
||||
|
||||
public draw(renderer: Renderer): void {
|
||||
this.shape.setCircles([this.head!, this.leftFoot!, this.rightFoot!]);
|
||||
renderer.addDrawable(this.shape);
|
||||
}
|
||||
|
||||
private calculateTextPosition(): vec2 {
|
||||
const footAverage = vec2.add(
|
||||
vec2.create(),
|
||||
this.leftFoot!.center,
|
||||
this.rightFoot!.center,
|
||||
);
|
||||
vec2.scale(footAverage, footAverage, 0.5);
|
||||
|
||||
const headFeetDelta = vec2.subtract(footAverage, this.head!.center, footAverage);
|
||||
vec2.normalize(headFeetDelta, headFeetDelta);
|
||||
const textOffset = vec2.scale(headFeetDelta, headFeetDelta, this.head!.radius + 50);
|
||||
return vec2.add(textOffset, this.head!.center, textOffset);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,29 +1,33 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
import { CircleLight, Renderer } from 'sdf-2d';
|
||||
import { Id, ProjectileBase, rgb, UpdateMessage } from 'shared';
|
||||
import { CircleLight, ColorfulCircle, Renderer } from 'sdf-2d';
|
||||
import { Id, ProjectileBase, settings, UpdateMessage } from 'shared';
|
||||
import { ViewObject } from './view-object';
|
||||
import { Circle } from '../shapes/circle';
|
||||
|
||||
export class ProjectileView extends ProjectileBase implements ViewObject {
|
||||
private circle: InstanceType<typeof Circle>;
|
||||
private circle: ColorfulCircle;
|
||||
private light: CircleLight;
|
||||
|
||||
constructor(id: Id, center: vec2, radius: number) {
|
||||
super(id, center, radius);
|
||||
this.circle = new Circle(center, radius / 2);
|
||||
this.light = new CircleLight(center, rgb(1, 0.5, 0), 0.15);
|
||||
}
|
||||
|
||||
update(updates: Array<UpdateMessage>): void {
|
||||
updates.forEach((u) => ((this as any)[u.key] = u.value));
|
||||
constructor(
|
||||
id: Id,
|
||||
center: vec2,
|
||||
radius: number,
|
||||
colorIndex: number,
|
||||
strength: number,
|
||||
) {
|
||||
super(id, center, radius, colorIndex, strength);
|
||||
this.circle = new ColorfulCircle(center, radius / 2, colorIndex);
|
||||
this.light = new CircleLight(center, settings.palette[colorIndex], 0);
|
||||
}
|
||||
|
||||
public step(deltaTimeInMilliseconds: number): void {
|
||||
this.circle.center = this.center;
|
||||
this.light.center = this.center;
|
||||
this.light.intensity = (0.15 * this.strength) / settings.projectileMaxStrength;
|
||||
}
|
||||
|
||||
public draw(renderer: Renderer): void {
|
||||
public beforeDestroy(): void {}
|
||||
|
||||
public draw(renderer: Renderer, overlay: HTMLElement): void {
|
||||
renderer.addDrawable(this.circle);
|
||||
renderer.addDrawable(this.light);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { Renderer } from 'sdf-2d';
|
|||
import { GameObject, UpdateMessage } from 'shared';
|
||||
|
||||
export interface ViewObject extends GameObject {
|
||||
update(updates: Array<UpdateMessage>): void;
|
||||
step(deltaTimeInMilliseconds: number): void;
|
||||
draw(renderer: Renderer): void;
|
||||
draw(renderer: Renderer, overlay: HTMLElement): void;
|
||||
beforeDestroy(): void;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +0,0 @@
|
|||
import { CircleFactory } from 'sdf-2d';
|
||||
|
||||
export const Circle = CircleFactory(2);
|
||||
163
frontend/src/scripts/shapes/planet-shape.ts
Normal file
163
frontend/src/scripts/shapes/planet-shape.ts
Normal file
|
|
@ -0,0 +1,163 @@
|
|||
import { mat2d, vec2, vec3, vec4 } from 'gl-matrix';
|
||||
import { PolygonFactory, DrawableDescriptor, Drawable } from 'sdf-2d';
|
||||
import { settings } from 'shared';
|
||||
|
||||
export const colorToString = (v: vec3 | vec4): string =>
|
||||
`vec4(${v[0]}, ${v[1]}, ${v[2]}, ${v.length > 3 ? v[3] : 1})`;
|
||||
|
||||
export class PlanetShape extends PolygonFactory(settings.planetEdgeCount, 0) {
|
||||
public static descriptor: DrawableDescriptor = {
|
||||
sdf: {
|
||||
shader: `
|
||||
uniform vec2 planetVertices[PLANET_COUNT * ${settings.planetEdgeCount}];
|
||||
uniform vec2 planetCenters[PLANET_COUNT];
|
||||
uniform float planetLengths[PLANET_COUNT];
|
||||
uniform float planetRandoms[PLANET_COUNT];
|
||||
uniform float planetColorMixQ[PLANET_COUNT];
|
||||
|
||||
uniform sampler2D noiseTexture;
|
||||
|
||||
#ifdef WEBGL2_IS_AVAILABLE
|
||||
float planetTerrain(vec2 h) {
|
||||
return texture(noiseTexture, h)[0] - 0.5;
|
||||
}
|
||||
#else
|
||||
float planetTerrain(vec2 h) {
|
||||
return texture2D(noiseTexture, h)[0] - 0.5;
|
||||
}
|
||||
#endif
|
||||
|
||||
vec2 planetLineDistance(vec2 target, vec2 from, vec2 to) {
|
||||
vec2 targetFromDelta = target - from;
|
||||
vec2 toFromDelta = to - from;
|
||||
float h = clamp(
|
||||
dot(targetFromDelta, toFromDelta) / dot(toFromDelta, toFromDelta),
|
||||
0.0, 1.0
|
||||
);
|
||||
|
||||
vec2 diff = targetFromDelta - toFromDelta * h;
|
||||
return vec2(
|
||||
dot(diff, diff),
|
||||
toFromDelta.x * targetFromDelta.y - toFromDelta.y * targetFromDelta.x
|
||||
);
|
||||
}
|
||||
|
||||
float planetMinDistance(vec2 target, out vec4 color) {
|
||||
float minDistance = 100.0;
|
||||
|
||||
for (int j = 0; j < PLANET_COUNT; j++) {
|
||||
vec2 startEnd = planetVertices[j * ${settings.planetEdgeCount}];
|
||||
vec2 vb = startEnd;
|
||||
|
||||
vec2 center = planetCenters[j];
|
||||
float l = planetLengths[j];
|
||||
float randomOffset = planetRandoms[j];
|
||||
vec2 targetTangent = normalize(target - center);
|
||||
vec2 noisyTarget = target - (
|
||||
targetTangent * planetTerrain(vec2(
|
||||
l * abs(atan(targetTangent.y, targetTangent.x)),
|
||||
randomOffset
|
||||
)) / 12.0
|
||||
);
|
||||
|
||||
float d = 10000.0;
|
||||
float s = 1.0;
|
||||
for (int k = 1; k < ${settings.planetEdgeCount}; k++) {
|
||||
vec2 va = vb;
|
||||
vb = planetVertices[j * ${settings.planetEdgeCount} + k];
|
||||
vec2 ds = planetLineDistance(noisyTarget, va, vb);
|
||||
|
||||
bvec3 cond = bvec3(noisyTarget.y >= va.y, noisyTarget.y < vb.y, ds.y > 0.0);
|
||||
if (all(cond) || all(not(cond))) {
|
||||
s *= -1.0;
|
||||
}
|
||||
|
||||
d = min(d, ds.x);
|
||||
}
|
||||
|
||||
vec2 ds = planetLineDistance(noisyTarget, vb, startEnd);
|
||||
bvec3 cond = bvec3(noisyTarget.y >= vb.y, noisyTarget.y < startEnd.y, ds.y > 0.0);
|
||||
if (all(cond) || all(not(cond))) {
|
||||
s *= -1.0;
|
||||
}
|
||||
|
||||
d = min(d, ds.x);
|
||||
float dist = s * sqrt(d);
|
||||
|
||||
if (dist < minDistance) {
|
||||
minDistance = dist;
|
||||
color = mix(${colorToString(settings.declaPlanetColor)}, ${colorToString(
|
||||
settings.redPlanetColor,
|
||||
)}, planetColorMixQ[j]);
|
||||
}
|
||||
}
|
||||
|
||||
return minDistance;
|
||||
}
|
||||
`,
|
||||
distanceFunctionName: 'planetMinDistance',
|
||||
},
|
||||
propertyUniformMapping: {
|
||||
length: 'planetLengths',
|
||||
random: 'planetRandoms',
|
||||
center: 'planetCenters',
|
||||
vertices: 'planetVertices',
|
||||
colorMixQ: 'planetColorMixQ',
|
||||
},
|
||||
uniformCountMacroName: `PLANET_COUNT`,
|
||||
shaderCombinationSteps: [0, 1, 2, 3, 8, 16],
|
||||
empty: new PlanetShape(new Array(settings.planetEdgeCount).fill(vec2.create()), 0),
|
||||
};
|
||||
|
||||
public randomOffset = 0;
|
||||
|
||||
constructor(public vertices: Array<vec2>, public colorMixQ: number) {
|
||||
super(vertices);
|
||||
}
|
||||
|
||||
protected getObjectToSerialize(transform2d: mat2d, transform1d: number): any {
|
||||
const transformedVertices = (this as any).actualVertices.map((v: vec2) =>
|
||||
vec2.transformMat2d(vec2.create(), v, transform2d),
|
||||
);
|
||||
|
||||
const center = transformedVertices.reduce(
|
||||
(sum: vec2, v: vec2) => vec2.add(sum, sum, v),
|
||||
vec2.create(),
|
||||
);
|
||||
vec2.scale(center, center, 1 / transformedVertices.length);
|
||||
|
||||
let length = 0;
|
||||
for (let i = 1; i < this.vertices.length; i++) {
|
||||
length += vec2.distance(transformedVertices[i - 1], transformedVertices[i]);
|
||||
}
|
||||
|
||||
return {
|
||||
vertices: transformedVertices,
|
||||
center,
|
||||
length,
|
||||
random: this.randomOffset,
|
||||
colorMixQ: this.colorMixQ,
|
||||
};
|
||||
}
|
||||
|
||||
public serializeToUniforms(
|
||||
uniforms: any,
|
||||
transform2d: mat2d,
|
||||
transform1d: number,
|
||||
): void {
|
||||
const { propertyUniformMapping } = (this.constructor as typeof Drawable).descriptor;
|
||||
|
||||
const serialized = this.getObjectToSerialize(transform2d, transform1d);
|
||||
Object.entries(propertyUniformMapping).forEach(([k, v]) => {
|
||||
if (!Object.prototype.hasOwnProperty.call(uniforms, v)) {
|
||||
uniforms[v] = [];
|
||||
}
|
||||
|
||||
if (k === 'vertices') {
|
||||
uniforms[v].push(...serialized[k]);
|
||||
} else {
|
||||
uniforms[v].push(serialized[k]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
import { NoisyPolygonFactory } from 'sdf-2d';
|
||||
import { settings } from 'shared';
|
||||
|
||||
export const Polygon = NoisyPolygonFactory(settings.polygonEdgeCount, 1);
|
||||
Loading…
Add table
Add a link
Reference in a new issue