Add files
This commit is contained in:
commit
77bde04db3
45 changed files with 10327 additions and 0 deletions
121
src/game.ts
Normal file
121
src/game.ts
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
/*
|
||||
export class Game implements IGame {
|
||||
public readonly objects = new Objects();
|
||||
public readonly physics = new Physics();
|
||||
public readonly camera = new Camera();
|
||||
private previousTime?: DOMHighResTimeStamp = null;
|
||||
private previousFpsValues: Array<number> = [];
|
||||
private infoText = new InfoText();
|
||||
private character: Character;
|
||||
private renderer: IRenderer;
|
||||
private initializeRendererPromise: Promise<void>;
|
||||
|
||||
constructor() {
|
||||
const canvas: HTMLCanvasElement = document.querySelector('canvas#main');
|
||||
const overlay: HTMLElement = document.querySelector('#overlay');
|
||||
|
||||
document.addEventListener('visibilitychange', this.handleVisibilityChange.bind(this));
|
||||
|
||||
new CommandBroadcaster(
|
||||
[
|
||||
new KeyboardListener(document.body),
|
||||
new MouseListener(canvas),
|
||||
new TouchListener(canvas),
|
||||
],
|
||||
[this.objects]
|
||||
);
|
||||
|
||||
this.renderer = new WebGl2Renderer(canvas, overlay);
|
||||
this.initializeRendererPromise = this.renderer.initialize();
|
||||
this.initializeScene();
|
||||
this.physics.start();
|
||||
}
|
||||
|
||||
public async start(): Promise<void> {
|
||||
await this.initializeRendererPromise;
|
||||
requestAnimationFrame(this.gameLoop.bind(this));
|
||||
}
|
||||
|
||||
public addObject(o: GameObject) {
|
||||
this.objects.addObject(o);
|
||||
}
|
||||
|
||||
public get viewArea(): BoundingBoxBase {
|
||||
return this.camera.viewArea;
|
||||
}
|
||||
|
||||
public findIntersecting(box: BoundingBoxBase): Array<BoundingBoxBase> {
|
||||
return this.physics.findIntersecting(box);
|
||||
}
|
||||
|
||||
private initializeScene() {
|
||||
this.objects.addObject(this.infoText);
|
||||
|
||||
const start = createDungeon(this.objects, this.physics);
|
||||
createDungeon(this.objects, this.physics);
|
||||
|
||||
this.character = new Character(this);
|
||||
// this.physics.addDynamicBoundingBox(this.character.boundingBox);
|
||||
this.addObject(this.character);
|
||||
this.addObject(this.camera);
|
||||
let pos: any = localStorage.getItem('character-position');
|
||||
pos = pos ? JSON.parse(pos) : start.from;
|
||||
this.character.sendCommand(new TeleportToCommand(pos));
|
||||
}
|
||||
|
||||
private handleVisibilityChange() {
|
||||
if (!document.hidden) {
|
||||
this.previousTime = null;
|
||||
}
|
||||
}
|
||||
|
||||
@timeIt()
|
||||
private gameLoop(time: DOMHighResTimeStamp) {
|
||||
if (this.previousTime === null) {
|
||||
this.previousTime = time;
|
||||
}
|
||||
|
||||
const deltaTime = time - this.previousTime;
|
||||
this.previousTime = time;
|
||||
this.calculateFps(deltaTime);
|
||||
|
||||
this.objects.sendCommand(new StepCommand(deltaTime));
|
||||
this.camera.sendCommand(new MoveToCommand(this.character.position));
|
||||
|
||||
this.renderer.startFrame(deltaTime);
|
||||
|
||||
this.camera.sendCommand(new BeforeRenderCommand(this.renderer));
|
||||
|
||||
const shouldBeDrawn = this.physics
|
||||
.findIntersecting(this.camera.viewArea)
|
||||
.map((b) => b.shape?.gameObject);
|
||||
|
||||
for (const object of shouldBeDrawn) {
|
||||
object?.sendCommand(new BeforeRenderCommand(this.renderer));
|
||||
object?.sendCommand(new RenderCommand(this.renderer));
|
||||
}
|
||||
|
||||
this.character.sendCommand(new RenderCommand(this.renderer));
|
||||
this.infoText.sendCommand(new RenderCommand(this.renderer));
|
||||
this.renderer.finishFrame();
|
||||
|
||||
localStorage.setItem('character-position', JSON.stringify(this.character.position));
|
||||
window.requestAnimationFrame(this.gameLoop.bind(this));
|
||||
}
|
||||
|
||||
private calculateFps(deltaTime: number) {
|
||||
this.previousFpsValues.push(1000 / deltaTime);
|
||||
if (this.previousFpsValues.length > 30) {
|
||||
this.previousFpsValues.sort();
|
||||
const min = this.previousFpsValues[0];
|
||||
const median = this.previousFpsValues[
|
||||
Math.floor(this.previousFpsValues.length / 2)
|
||||
];
|
||||
|
||||
InfoText.modifyRecord('FPS', { min, median });
|
||||
|
||||
this.previousFpsValues = [];
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
8
src/graphics/drawables/i-drawable-descriptor.ts
Normal file
8
src/graphics/drawables/i-drawable-descriptor.ts
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
import { IDrawable } from './i-drawable';
|
||||
|
||||
export interface IDrawableDescriptor {
|
||||
uniformName: string;
|
||||
countMacroName: string;
|
||||
shaderCombinationSteps: Array<number>;
|
||||
readonly empty: IDrawable;
|
||||
}
|
||||
6
src/graphics/drawables/i-drawable.ts
Normal file
6
src/graphics/drawables/i-drawable.ts
Normal 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;
|
||||
}
|
||||
46
src/graphics/drawables/lights/circle-light.ts
Normal file
46
src/graphics/drawables/lights/circle-light.ts
Normal 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
|
||||
);
|
||||
}
|
||||
}
|
||||
50
src/graphics/drawables/lights/flashlight.ts
Normal file
50
src/graphics/drawables/lights/flashlight.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
3
src/graphics/drawables/lights/i-light.ts
Normal file
3
src/graphics/drawables/lights/i-light.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import { IDrawable } from '../i-drawable';
|
||||
|
||||
export type ILight = IDrawable;
|
||||
13
src/graphics/graphics-library/compiling/check-program.ts
Normal file
13
src/graphics/graphics-library/compiling/check-program.ts
Normal 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)!);
|
||||
}
|
||||
};
|
||||
7
src/graphics/graphics-library/compiling/check-shader.ts
Normal file
7
src/graphics/graphics-library/compiling/check-shader.ts
Normal 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)!);
|
||||
}
|
||||
};
|
||||
48
src/graphics/graphics-library/compiling/create-program.ts
Normal file
48
src/graphics/graphics-library/compiling/create-program.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
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();
|
||||
|
||||
if (!program) {
|
||||
throw new Error('Could not create program');
|
||||
}
|
||||
|
||||
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;
|
||||
};
|
||||
22
src/graphics/graphics-library/compiling/create-shader.ts
Normal file
22
src/graphics/graphics-library/compiling/create-shader.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
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);
|
||||
|
||||
if (!shader) {
|
||||
throw new Error('Could not create shader');
|
||||
}
|
||||
|
||||
gl.shaderSource(shader, source);
|
||||
gl.compileShader(shader);
|
||||
|
||||
return shader;
|
||||
};
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
46
src/graphics/graphics-library/frame-buffer/frame-buffer.ts
Normal file
46
src/graphics/graphics-library/frame-buffer/frame-buffer.ts
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
import { settings } from '../../settings';
|
||||
|
||||
export abstract class FrameBuffer {
|
||||
public renderScale = 1;
|
||||
public enableHighDpiRendering = settings.enableHighDpiRendering;
|
||||
|
||||
protected size = vec2.create();
|
||||
|
||||
// null means the default framebuffer
|
||||
protected frameBuffer: WebGLFramebuffer | null = null;
|
||||
|
||||
constructor(protected gl: WebGL2RenderingContext) {}
|
||||
|
||||
public bindAndClear(colorInput?: WebGLTexture) {
|
||||
this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, this.frameBuffer);
|
||||
|
||||
if (colorInput) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
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
|
||||
}
|
||||
|
||||
const texture = this.gl.createTexture();
|
||||
if (!texture) {
|
||||
throw new Error('Could not create texture');
|
||||
}
|
||||
this.frameTexture = texture;
|
||||
this.configureTexture();
|
||||
|
||||
const frameBuffer = this.gl.createFramebuffer();
|
||||
if (!frameBuffer) {
|
||||
throw new Error('Could not create frame buffer');
|
||||
}
|
||||
this.frameBuffer = frameBuffer;
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
39
src/graphics/graphics-library/helper/enable-extension.ts
Normal file
39
src/graphics/graphics-library/helper/enable-extension.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
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;
|
||||
};
|
||||
|
|
@ -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;
|
||||
};
|
||||
82
src/graphics/graphics-library/helper/load-uniform.ts
Normal file
82
src/graphics/graphics-library/helper/load-uniform.ts
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import { mat3, ReadonlyVec3, vec2, vec3 } from 'gl-matrix';
|
||||
|
||||
const loaderMat3 = mat3.create();
|
||||
|
||||
export const loadUniform = (
|
||||
gl: WebGL2RenderingContext,
|
||||
value: any,
|
||||
type: GLenum,
|
||||
location: WebGLUniformLocation
|
||||
): any => {
|
||||
const converters: Map<
|
||||
GLenum,
|
||||
(gl: WebGL2RenderingContext, value: any, location: WebGLUniformLocation) => void
|
||||
> = new Map();
|
||||
{
|
||||
converters.set(WebGL2RenderingContext.FLOAT, (gl, v, l) => {
|
||||
if (v instanceof Array) {
|
||||
if (v.length == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
gl.uniform1fv(l, new Float32Array(v));
|
||||
} else {
|
||||
gl.uniform1f(l, v);
|
||||
}
|
||||
});
|
||||
|
||||
converters.set(WebGL2RenderingContext.FLOAT_VEC2, (gl, v: vec2 | Array<vec2>, l) => {
|
||||
if (v.length == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (v[0] instanceof Array) {
|
||||
const result = new Float32Array(v.length * 2);
|
||||
|
||||
for (let i = 0; i < v.length; i++) {
|
||||
result[2 * i] = (v[i] as Array<number>).x;
|
||||
result[2 * i + 1] = (v[i] as Array<number>).y;
|
||||
}
|
||||
|
||||
gl.uniform2fv(l, result);
|
||||
} else {
|
||||
gl.uniform2fv(l, v as vec2);
|
||||
}
|
||||
});
|
||||
|
||||
converters.set(
|
||||
WebGL2RenderingContext.FLOAT_VEC3,
|
||||
(gl, v: ReadonlyVec3 | Array<vec3>, l) => {
|
||||
if (v.length == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (v[0] instanceof Array) {
|
||||
const result = new Float32Array(v.length * 3);
|
||||
|
||||
for (let i = 0; i < v.length; i++) {
|
||||
result[3 * i] = (v[i] as Array<number>)[0];
|
||||
result[3 * i + 1] = (v[i] as Array<number>)[1];
|
||||
result[3 * i + 2] = (v[i] as Array<number>)[2];
|
||||
}
|
||||
|
||||
gl.uniform3fv(l, result);
|
||||
} else {
|
||||
gl.uniform3fv(l, v as vec3);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
converters.set(WebGL2RenderingContext.FLOAT_MAT3, (gl, v, l) => {
|
||||
gl.uniformMatrix3fv(l, true, mat3.fromMat2d(loaderMat3, v));
|
||||
});
|
||||
|
||||
converters.set(WebGL2RenderingContext.BOOL, (gl, v, l) => gl.uniform1i(l, v));
|
||||
|
||||
if (!converters.has(type)) {
|
||||
throw new Error(`Unimplemented webgl type: ${type}`);
|
||||
}
|
||||
|
||||
converters.get(type)!(gl, value, location);
|
||||
}
|
||||
};
|
||||
49
src/graphics/graphics-library/helper/stopwatch.ts
Normal file
49
src/graphics/graphics-library/helper/stopwatch.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import { enableExtension } from './enable-extension';
|
||||
|
||||
// https://www.khronos.org/registry/webgl/extensions/EXT_disjoint_timer_query_webgl2/
|
||||
|
||||
export class WebGlStopwatch {
|
||||
private timerExtension: any;
|
||||
private timerQuery?: WebGLQuery;
|
||||
private isReady = true;
|
||||
private resultsInNanoSeconds?: number;
|
||||
|
||||
constructor(private gl: WebGL2RenderingContext) {
|
||||
this.timerExtension = enableExtension(gl, 'EXT_disjoint_timer_query_webgl2');
|
||||
}
|
||||
|
||||
public start() {
|
||||
if (this.isReady) {
|
||||
this.timerQuery = this.gl.createQuery()!;
|
||||
this.gl.beginQuery(this.timerExtension.TIME_ELAPSED_EXT, this.timerQuery);
|
||||
}
|
||||
}
|
||||
|
||||
public stop() {
|
||||
if (this.isReady) {
|
||||
this.gl.endQuery(this.timerExtension.TIME_ELAPSED_EXT);
|
||||
this.isReady = false;
|
||||
}
|
||||
|
||||
const available = this.gl.getQueryParameter(
|
||||
this.timerQuery!,
|
||||
this.gl.QUERY_RESULT_AVAILABLE
|
||||
);
|
||||
const disjoint = this.gl.getParameter(this.timerExtension.GPU_DISJOINT_EXT);
|
||||
|
||||
if (available && !disjoint) {
|
||||
this.resultsInNanoSeconds = this.gl.getQueryParameter(
|
||||
this.timerQuery!,
|
||||
this.gl.QUERY_RESULT
|
||||
);
|
||||
|
||||
//InfoText.modifyRecord('Draw time', `${this.resultsInMilliSeconds.toFixed(2)} ms`);
|
||||
|
||||
this.isReady = true;
|
||||
}
|
||||
}
|
||||
|
||||
public get resultsInMilliSeconds(): number {
|
||||
return this.resultsInNanoSeconds! / 1000 / 1000;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
import Program from './program';
|
||||
|
||||
export class FragmentShaderOnlyProgram extends Program {
|
||||
private vao?: WebGLVertexArrayObject;
|
||||
|
||||
constructor(
|
||||
gl: WebGL2RenderingContext,
|
||||
sources: [string, string],
|
||||
substitutions: { [name: string]: string }
|
||||
) {
|
||||
super(gl, sources, substitutions);
|
||||
}
|
||||
|
||||
public async initialize(): Promise<void> {
|
||||
await super.initialize();
|
||||
this.prepareScreenQuad('vertexPosition');
|
||||
}
|
||||
|
||||
public bind() {
|
||||
super.bind();
|
||||
this.gl.bindVertexArray(this.vao!);
|
||||
}
|
||||
|
||||
public draw() {
|
||||
this.gl.drawArrays(this.gl.TRIANGLE_STRIP, 0, 4);
|
||||
}
|
||||
|
||||
private prepareScreenQuad(attributeName: string) {
|
||||
const positionAttributeLocation = this.gl.getAttribLocation(
|
||||
this.program!,
|
||||
attributeName
|
||||
);
|
||||
|
||||
const positionBuffer = this.gl.createBuffer();
|
||||
|
||||
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, positionBuffer);
|
||||
this.gl.bufferData(
|
||||
this.gl.ARRAY_BUFFER,
|
||||
new Float32Array([-1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0]),
|
||||
this.gl.STATIC_DRAW
|
||||
);
|
||||
const vao = this.gl.createVertexArray();
|
||||
if (!vao) {
|
||||
throw new Error('Could not create vertex array object');
|
||||
}
|
||||
this.vao = vao;
|
||||
|
||||
this.gl.bindVertexArray(this.vao);
|
||||
this.gl.enableVertexAttribArray(positionAttributeLocation);
|
||||
this.gl.vertexAttribPointer(positionAttributeLocation, 2, this.gl.FLOAT, false, 0, 0);
|
||||
}
|
||||
}
|
||||
9
src/graphics/graphics-library/program/i-program.ts
Normal file
9
src/graphics/graphics-library/program/i-program.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
|
||||
export interface IProgram {
|
||||
initialize(): Promise<void>;
|
||||
setDrawingRectangleUV(bottomLeft: vec2, size: vec2): void;
|
||||
bindAndSetUniforms(values: { [name: string]: any }): void;
|
||||
draw(): void;
|
||||
delete(): void;
|
||||
}
|
||||
102
src/graphics/graphics-library/program/program.ts
Normal file
102
src/graphics/graphics-library/program/program.ts
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import { mat2d, vec2 } from 'gl-matrix';
|
||||
import { settings } from '../../settings';
|
||||
import { createProgram } from '../compiling/create-program';
|
||||
import { loadUniform } from '../helper/load-uniform';
|
||||
import { IProgram } from './i-program';
|
||||
|
||||
export default abstract class Program implements IProgram {
|
||||
protected program?: WebGLProgram;
|
||||
|
||||
private programPromise: Promise<WebGLProgram>;
|
||||
private modelTransform = mat2d.identity(mat2d.create());
|
||||
private readonly ndcToUv = mat2d.fromValues(0.5, 0, 0, 0.5, 0.5, 0.5);
|
||||
private uniforms: Array<{
|
||||
name: Array<string>;
|
||||
location: WebGLUniformLocation;
|
||||
type: GLenum;
|
||||
}> = [];
|
||||
|
||||
constructor(
|
||||
protected gl: WebGL2RenderingContext,
|
||||
[vertexShaderSource, fragmentShaderSource]: [string, string],
|
||||
substitutions: { [name: string]: string }
|
||||
) {
|
||||
substitutions = { ...settings.shaderMacros, ...substitutions };
|
||||
|
||||
this.programPromise = createProgram(
|
||||
this.gl,
|
||||
vertexShaderSource,
|
||||
fragmentShaderSource,
|
||||
substitutions
|
||||
);
|
||||
}
|
||||
|
||||
public async initialize(): Promise<void> {
|
||||
this.program = await this.programPromise;
|
||||
this.queryUniforms();
|
||||
}
|
||||
|
||||
public bindAndSetUniforms(values: { [name: string]: any }) {
|
||||
this.bind();
|
||||
this.setUniforms({ modelTransform: this.modelTransform, ...values });
|
||||
}
|
||||
|
||||
public setDrawingRectangleUV(bottomLeft: vec2, size: vec2) {
|
||||
mat2d.invert(this.modelTransform, this.ndcToUv);
|
||||
mat2d.translate(this.modelTransform, this.modelTransform, bottomLeft);
|
||||
mat2d.scale(this.modelTransform, this.modelTransform, size);
|
||||
mat2d.multiply(this.modelTransform, this.modelTransform, this.ndcToUv);
|
||||
}
|
||||
|
||||
public setUniforms(values: { [name: string]: any }) {
|
||||
this.uniforms.forEach(({ name, location, type }) => {
|
||||
const value = name.reduce(
|
||||
(prev, prop) => (prev !== null && prop in prev ? prev[prop] : null),
|
||||
values
|
||||
);
|
||||
|
||||
if (value !== null) {
|
||||
loadUniform(this.gl, value, type, location);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public delete() {
|
||||
this.gl.getAttachedShaders(this.program!)?.forEach((s) => this.gl.deleteShader(s));
|
||||
this.gl.deleteProgram(this.program!);
|
||||
}
|
||||
|
||||
public abstract draw(): void;
|
||||
|
||||
protected bind() {
|
||||
this.gl.useProgram(this.program!);
|
||||
}
|
||||
|
||||
private queryUniforms() {
|
||||
const uniformCount = this.gl.getProgramParameter(
|
||||
this.program!,
|
||||
WebGL2RenderingContext.ACTIVE_UNIFORMS
|
||||
);
|
||||
|
||||
for (let i = 0; i < uniformCount; i++) {
|
||||
const glUniform = this.gl.getActiveUniform(this.program!, i)!;
|
||||
|
||||
this.uniforms.push({
|
||||
name: glUniform.name.split(/\[|\]\.|\]|\./).filter((p) => p !== ''),
|
||||
location: this.gl.getUniformLocation(this.program!, glUniform.name)!,
|
||||
type: glUniform.type,
|
||||
});
|
||||
}
|
||||
|
||||
this.uniforms.map((u1) => {
|
||||
const isSingle =
|
||||
this.uniforms.filter((u2) => u2.name.includes(u1.name[0])).length == 1;
|
||||
|
||||
if (u1.name.includes('0') && isSingle) {
|
||||
u1.name = u1.name.slice(0, -1);
|
||||
}
|
||||
|
||||
return u1;
|
||||
});
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue