Some refactoring

This commit is contained in:
schmelczerandras 2020-09-14 19:18:59 +02:00
commit 99f47e2961
45 changed files with 72 additions and 113 deletions

View file

@ -1,48 +0,0 @@
#version 300 es
precision mediump float;
const float inf = 1000000.0;
const float pi = atan(1.0) * 4.0;
float interpolate(float from, float to, float quotient) {
float steppedQ = sin(quotient * pi - pi * 0.5) * 0.5 + 0.5;
return from + (to - from) * clamp(steppedQ, 0.0, 1.0);
}
float noise(float x){
return fract(sin(x) * 43758.5453123);
}
float terrain(float x) {
float result = 0.0;
float frequency = 0.01;
float amplitude = 1.0;
for (int i = 0; i < 8; i++) {
result += sin(2.0 * pi * x * frequency - 2.0 * pi * noise(float(i) * 200.0)) * amplitude;
frequency *= 1.5;
amplitude /= 1.2;
}
return result;
}
vec2 random2(vec2 st){
st = vec2( dot(st,vec2(127.1,311.7)),
dot(st,vec2(269.5,183.3)) );
return -1.0 + 2.0*fract(sin(st)*43758.5453123);
}
float noise(vec2 st) {
vec2 i = floor(st);
vec2 f = fract(st);
vec2 u = f*f*(3.0-2.0*f);
return mix( mix( dot( random2(i + vec2(0.0,0.0) ), f - vec2(0.0,0.0) ),
dot( random2(i + vec2(1.0,0.0) ), f - vec2(1.0,0.0) ), u.x),
mix( dot( random2(i + vec2(0.0,1.0) ), f - vec2(0.0,1.0) ),
dot( random2(i + vec2(1.0,1.0) ), f - vec2(1.0,1.0) ), u.x), u.y);
}

View file

@ -1,8 +1,8 @@
import { CommandBroadcaster } from './commands/command-broadcaster'; import { CommandBroadcaster } from './commands/command-broadcaster';
import { BeforeRenderCommand } from './drawing/commands/before-render'; import { BeforeRenderCommand } from './graphics/commands/before-render';
import { RenderCommand } from './drawing/commands/render'; import { RenderCommand } from './graphics/commands/render';
import { IRenderer } from './drawing/i-renderer'; import { IRenderer } from './graphics/i-renderer';
import { WebGl2Renderer } from './drawing/rendering/webgl2-renderer'; import { WebGl2Renderer } from './graphics/rendering/webgl2-renderer';
import { timeIt } from './helper/timing'; import { timeIt } from './helper/timing';
import { IGame } from './i-game'; import { IGame } from './i-game';
import { KeyboardListener } from './input/keyboard-listener'; import { KeyboardListener } from './input/keyboard-listener';
@ -128,13 +128,12 @@ export class Game implements IGame {
this.previousFpsValues.push(1000 / deltaTime); this.previousFpsValues.push(1000 / deltaTime);
if (this.previousFpsValues.length > 30) { if (this.previousFpsValues.length > 30) {
this.previousFpsValues.sort(); this.previousFpsValues.sort();
const text = `Min: ${this.previousFpsValues[0].toFixed( const min = this.previousFpsValues[0];
2 const median = this.previousFpsValues[
)}\n\tMedian: ${this.previousFpsValues[
Math.floor(this.previousFpsValues.length / 2) Math.floor(this.previousFpsValues.length / 2)
].toFixed(2)}`; ];
InfoText.modifyRecord('FPS', text); InfoText.modifyRecord('FPS', { min, median });
this.previousFpsValues = []; this.previousFpsValues = [];
} }

View file

@ -0,0 +1,12 @@
import { Command } from '../../commands/command';
import { IRenderer } from '../i-renderer';
export class BeforeRenderCommand extends Command {
public constructor(public readonly renderer?: IRenderer) {
super();
}
public get type(): string {
return 'BeforeRenderCommand';
}
}

View file

@ -0,0 +1,12 @@
import { Command } from '../../commands/command';
import { IRenderer } from '../../graphics/i-renderer';
export class RenderCommand extends Command {
public constructor(public readonly renderer?: IRenderer) {
super();
}
public get type(): string {
return 'RenderCommand';
}
}

View file

@ -0,0 +1,32 @@
import { mat2d, vec2 } from 'gl-matrix';
import { Blob } from '../../shapes/types/blob';
import { settings } from '../settings';
import { IDrawable } from './i-drawable';
import { IDrawableDescriptor } from './i-drawable-descriptor';
export class DrawableBlob extends Blob implements IDrawable {
public static descriptor: IDrawableDescriptor = {
uniformName: 'blobs',
countMacroName: 'blobCount',
shaderCombinationSteps: settings.shaderCombinations.blobSteps,
empty: new DrawableBlob(vec2.fromValues(0, 0)),
};
public serializeToUniforms(uniforms: any, scale: number, transform: mat2d): void {
const { uniformName } = DrawableBlob.descriptor;
if (!Object.prototype.hasOwnProperty.call(uniforms, uniformName)) {
uniforms[uniformName] = [];
}
uniforms[uniformName].push({
headCenter: vec2.transformMat2d(vec2.create(), this.head.center, transform),
leftFootCenter: vec2.transformMat2d(vec2.create(), this.leftFoot.center, transform),
rightFootCenter: vec2.transformMat2d(
vec2.create(),
this.rightFoot.center,
transform
),
headRadius: this.headRadius * scale,
footRadius: this.footRadius * scale,
});
}
}

View file

@ -0,0 +1,28 @@
import { mat2d, vec2 } from 'gl-matrix';
import TunnelShape from '../../shapes/types/tunnel-shape';
import { settings } from '../settings';
import { IDrawable } from './i-drawable';
import { IDrawableDescriptor } from './i-drawable-descriptor';
export class DrawableTunnel extends TunnelShape implements IDrawable {
public static descriptor: IDrawableDescriptor = {
uniformName: 'lines',
countMacroName: 'lineCount',
shaderCombinationSteps: settings.shaderCombinations.lineSteps,
empty: new DrawableTunnel(vec2.fromValues(0, 0), vec2.fromValues(0, 0), 0, 0),
};
public serializeToUniforms(uniforms: any, scale: number, transform: mat2d): void {
const { uniformName } = DrawableTunnel.descriptor;
if (!Object.prototype.hasOwnProperty.call(uniforms, uniformName)) {
uniforms[uniformName] = [];
}
uniforms[uniformName].push({
from: vec2.transformMat2d(vec2.create(), this.from, transform),
toFromDelta: vec2.scale(vec2.create(), this.toFromDelta, scale),
fromRadius: this.fromRadius * scale,
toRadius: this.toRadius * scale,
});
}
}

View file

@ -0,0 +1,8 @@
import { IDrawable } from './i-drawable';
export interface IDrawableDescriptor {
uniformName: string;
countMacroName: string;
shaderCombinationSteps: Array<number>;
readonly empty: IDrawable;
}

View file

@ -0,0 +1,6 @@
import { vec2, mat2d } from 'gl-matrix';
export interface IDrawable {
distance(target: vec2): number;
serializeToUniforms(uniforms: any, scale: number, transform: mat2d): void;
}

View file

@ -0,0 +1,46 @@
import { mat2d, vec2, vec3 } from 'gl-matrix';
import { settings } from '../../settings';
import { IDrawableDescriptor } from '../i-drawable-descriptor';
import { ILight } from './i-light';
export class CircleLight implements ILight {
public static descriptor: IDrawableDescriptor = {
uniformName: 'circleLights',
countMacroName: 'circleLightCount',
shaderCombinationSteps: settings.shaderCombinations.circleLightSteps,
empty: new CircleLight(vec2.fromValues(0, 0), 0, vec3.fromValues(0, 0, 0), 0),
};
constructor(
public center: vec2,
public lightDrop: number,
public color: vec3,
public lightness: number
) {}
public distance(_: vec2): number {
return 0;
}
public serializeToUniforms(uniforms: any, scale: number, transform: mat2d): void {
const { uniformName } = CircleLight.descriptor;
if (!Object.prototype.hasOwnProperty.call(uniforms, uniformName)) {
uniforms[uniformName] = [];
}
uniforms[uniformName].push({
center: vec2.transformMat2d(vec2.create(), this.center, transform),
lightDrop: this.lightDrop,
value: this.value,
});
}
public get value(): vec3 {
return vec3.scale(
vec3.create(),
vec3.normalize(this.color, this.color),
this.lightness
);
}
}

View file

@ -0,0 +1,50 @@
import { mat2d, vec2, vec3 } from 'gl-matrix';
import { settings } from '../../settings';
import { IDrawableDescriptor } from '../i-drawable-descriptor';
import { ILight } from './i-light';
export class Flashlight implements ILight {
public static descriptor: IDrawableDescriptor = {
uniformName: 'flashlights',
countMacroName: 'flashlightCount',
shaderCombinationSteps: settings.shaderCombinations.flashlightSteps,
empty: new Flashlight(
vec2.fromValues(0, 0),
vec2.fromValues(0, 0),
0,
vec3.fromValues(0, 0, 0),
0
),
};
public constructor(
public center: vec2,
public direction: vec2,
public lightDrop: number,
public color: vec3,
public lightness: number
) {}
public distance(_: vec2): number {
return 0;
}
public serializeToUniforms(uniforms: any, scale: number, transform: mat2d): void {
const listName = Flashlight.descriptor.uniformName;
if (!Object.prototype.hasOwnProperty.call(uniforms, listName)) {
uniforms[listName] = [];
}
uniforms[listName].push({
center: vec2.transformMat2d(vec2.create(), this.center, transform),
direction: this.direction,
lightDrop: this.lightDrop,
value: this.value,
});
}
public get value(): vec3 {
return vec3.scale(vec3.create(), this.color, this.lightness);
}
}

View file

@ -0,0 +1,3 @@
import { IDrawable } from '../i-drawable';
export type ILight = IDrawable;

View file

@ -0,0 +1,13 @@
import { checkShader } from './check-shader';
export const checkProgram = (gl: WebGL2RenderingContext, program: WebGLProgram) => {
const success = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!success) {
gl.getAttachedShaders(program).forEach((s) => {
checkShader(gl, s);
});
throw new Error(gl.getProgramInfoLog(program));
}
};

View file

@ -0,0 +1,7 @@
export const checkShader = (gl: WebGL2RenderingContext, shader: WebGLShader) => {
const success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (!success) {
throw new Error(gl.getShaderInfoLog(shader));
}
};

View file

@ -0,0 +1,44 @@
import { waitWhileFalse } from '../../../helper/wait-while-false';
import { tryEnableExtension } from '../helper/enable-extension';
import { checkProgram } from './check-program';
import { createShader } from './create-shader';
export const createProgram = async (
gl: WebGL2RenderingContext,
vertexShaderSource: string,
fragmentShaderSource: string,
substitutions: { [name: string]: string }
): Promise<WebGLProgram> => {
const program = gl.createProgram();
const extension = tryEnableExtension(gl, 'KHR_parallel_shader_compile');
const vertexShader = createShader(
gl,
gl.VERTEX_SHADER,
vertexShaderSource,
substitutions
);
gl.attachShader(program, vertexShader);
const fragmentShader = createShader(
gl,
gl.FRAGMENT_SHADER,
fragmentShaderSource,
substitutions
);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
if (extension) {
const checkCompileStatus = () =>
gl.getProgramParameter(program, extension.COMPLETION_STATUS_KHR);
await waitWhileFalse(checkCompileStatus);
}
checkProgram(gl, program);
return program;
};

View file

@ -0,0 +1,17 @@
export const createShader = (
gl: WebGL2RenderingContext,
type: GLenum,
source: string,
substitutions: { [name: string]: string }
): WebGLShader => {
source = source.replace(/{(.+)}/gm, (_, name: string): string => {
const value = substitutions[name];
return Number.isInteger(value) ? `${value}.0` : value;
});
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
return shader;
};

View file

@ -0,0 +1,19 @@
import { FrameBuffer } from './frame-buffer';
export class DefaultFrameBuffer extends FrameBuffer {
constructor(gl: WebGL2RenderingContext) {
super(gl);
this.frameBuffer = null;
this.setSize();
}
public setSize(): boolean {
const hasChanged = super.setSize();
if (hasChanged) {
this.gl.canvas.width = this.size.x;
this.gl.canvas.height = this.size.y;
}
return hasChanged;
}
}

View file

@ -0,0 +1,44 @@
import { vec2 } from 'gl-matrix';
import { settings } from '../../settings';
export abstract class FrameBuffer {
public renderScale = 1;
public enableHighDpiRendering = settings.enableHighDpiRendering;
protected size = vec2.create();
protected frameBuffer: WebGLFramebuffer;
constructor(protected gl: WebGL2RenderingContext) {}
public bindAndClear(colorInput?: WebGLTexture) {
this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, this.frameBuffer);
if (colorInput !== null) {
this.gl.bindTexture(this.gl.TEXTURE_2D, colorInput);
}
this.gl.viewport(0, 0, this.size.x, this.size.y);
this.gl.clearColor(0, 0, 0, 0);
this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT);
}
public setSize(): boolean {
const realToCssPixels =
(this.enableHighDpiRendering ? window.devicePixelRatio : 1) * this.renderScale;
const canvasWidth = (this.gl.canvas as HTMLCanvasElement).clientWidth;
const canvasHeight = (this.gl.canvas as HTMLCanvasElement).clientHeight;
const displayWidth = Math.floor(canvasWidth * realToCssPixels);
const displayHeight = Math.floor(canvasHeight * realToCssPixels);
const oldSize = vec2.clone(this.getSize());
this.size = vec2.fromValues(displayWidth, displayHeight);
return this.size.x != oldSize.x || this.size.y != oldSize.y;
}
public getSize(): vec2 {
return this.size;
}
}

View file

@ -0,0 +1,89 @@
import { enableExtension } from '../helper/enable-extension';
import { FrameBuffer } from './frame-buffer';
export class IntermediateFrameBuffer extends FrameBuffer {
private frameTexture: WebGLTexture;
private floatLinearEnabled = false;
constructor(gl: WebGL2RenderingContext) {
super(gl);
enableExtension(gl, 'EXT_color_buffer_float');
try {
enableExtension(gl, 'OES_texture_float_linear');
this.floatLinearEnabled = true;
} catch {
// it's okay
}
this.frameTexture = this.gl.createTexture();
this.configureTexture();
this.frameBuffer = this.gl.createFramebuffer();
this.configureFrameBuffer();
this.setSize();
}
public get colorTexture(): WebGLTexture {
return this.frameTexture;
}
public setSize(): boolean {
const hasChanged = super.setSize();
if (hasChanged) {
this.gl.bindTexture(this.gl.TEXTURE_2D, this.frameTexture);
this.gl.texImage2D(
this.gl.TEXTURE_2D,
0,
this.gl.RG16F,
this.size.x,
this.size.y,
0,
this.gl.RG,
this.gl.FLOAT,
null
);
}
return hasChanged;
}
private configureTexture() {
this.gl.bindTexture(this.gl.TEXTURE_2D, this.frameTexture);
this.gl.texParameteri(
this.gl.TEXTURE_2D,
this.gl.TEXTURE_MAG_FILTER,
this.floatLinearEnabled ? this.gl.LINEAR : this.gl.NEAREST
);
this.gl.texParameteri(
this.gl.TEXTURE_2D,
this.gl.TEXTURE_MIN_FILTER,
this.floatLinearEnabled ? this.gl.LINEAR : this.gl.NEAREST
);
this.gl.texParameteri(
this.gl.TEXTURE_2D,
this.gl.TEXTURE_WRAP_S,
this.gl.CLAMP_TO_EDGE
);
this.gl.texParameteri(
this.gl.TEXTURE_2D,
this.gl.TEXTURE_WRAP_T,
this.gl.CLAMP_TO_EDGE
);
}
private configureFrameBuffer() {
this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, this.frameBuffer);
const attachmentPoint = this.gl.COLOR_ATTACHMENT0;
this.gl.framebufferTexture2D(
this.gl.FRAMEBUFFER,
attachmentPoint,
this.gl.TEXTURE_2D,
this.frameTexture,
0
);
}
}

View file

@ -0,0 +1,41 @@
import { InfoText } from '../../../objects/types/info-text';
const extensions: Map<string, any> = new Map();
const printExtensions = () => {
const values = {};
for (const [k, v] of extensions.entries()) {
values[k] = v !== null;
}
InfoText.modifyRecord('extensions', values);
};
export const tryEnableExtension = (
gl: WebGL2RenderingContext,
name: string
): any | null => {
if (extensions.has(name)) {
return extensions.get(name);
}
let extension = null;
if (gl.getSupportedExtensions().indexOf(name) != -1) {
extension = gl.getExtension(name);
}
extensions.set(name, extension);
printExtensions();
return extension;
};
export const enableExtension = (gl: WebGL2RenderingContext, name: string): any => {
const extension = tryEnableExtension(gl, name);
if (extension === null) {
throw new Error(`Unsupported extension ${name}`);
}
return extension;
};

View file

@ -0,0 +1,9 @@
export const getWebGl2Context = (canvas: HTMLCanvasElement): WebGL2RenderingContext => {
const gl = canvas.getContext('webgl2');
if (!gl) {
throw new Error('WebGl2 is not supported');
}
return gl;
};

Some files were not shown because too many files have changed in this diff Show more