Finish documentation

This commit is contained in:
schmelczerandras 2020-09-28 16:26:55 +02:00
parent 49473bf905
commit 31fcfd3d6b
86 changed files with 1383 additions and 8485 deletions

View file

@ -1,13 +1,63 @@
import { Drawable } from './drawable';
/**
* Used for containing the required information to compile drawables into
* shader code.
*
* Each [[Drawable]] must have a static property of this type, called descriptor.
*
* For more information on how to create your own DrawableDescriptor-s, look at the
* code of [[Circle]] or [[InvertedTunnel]].
*/
export interface DrawableDescriptor {
/**
* An object describing the relationship between the object returned by a [[Drawable]]'s
* getObjectToSerialize and the name of the arrays used in the GLSL code.
*/
propertyUniformMapping: { [property: string]: string };
/**
* The name of the uniform int used in the code to refer to the
* number of drawables of this type.
*/
uniformCountMacroName: string;
/**
* Required property for shapes having physical dimensions.
*/
sdf?: {
/**
* The actual GLSL code for observing the drawables represented by this descriptor.
*
* Your code should work with both version 100 and version 300 es
*/
shader: string;
isInverted?: boolean;
/**
* The name of the function defined in the value of `shader`.
* Its signature should look like this:
* ```glsl
* float (in vec2 target, out float colorIndex)
* ```
*/
distanceFunctionName: string;
/**
* By default, drawables are not inverted.
*/
isInverted?: boolean;
};
/**
* Number of possible drawables around each tile.
*
* For each step, a shader will be generated. And at runtime the closes matching
* shader will be used to render a given part of the scene.
*/
shaderCombinationSteps: Array<number>;
/**
* When no shaderCombinationStep matches the current number of drawables exactly,
* the value of `empty` is used to pad out arrays.
*/
readonly empty: Drawable;
}

View file

@ -1,11 +1,36 @@
import { mat2d, vec2 } from 'gl-matrix';
import { DrawableDescriptor } from './drawable-descriptor';
/**
* Base class of every drawable object.
*
* To create your own drawables, you need to subclass from this.
*
* > Although lights are also subclasses of Drawable, you cannot create your own light sources.
*/
export abstract class Drawable {
// This should be overriden by inherited classes
/**
* This should be defined in inherited classes.
*/
public static readonly descriptor: DrawableDescriptor;
/**
* The lower bound of the distance between the target and the object.
*
* It can return 0 by default, the only consequence of this, is a reduced performance.
* Because this object won't benefit from tile-based rendering.
* @param target
*/
public abstract minDistance(target: vec2): number;
/**
* Return the values that should be given to the shaders through uniform inputs.
*
* @param transform2d position-like properties should be transformed by this matrix
* before being returned.
* @param transform1d scalar properties should be transformed by this number
* before being returned.
*/
protected abstract getObjectToSerialize(transform2d: mat2d, transform1d: number): any;
public serializeToUniforms(

View file

@ -2,6 +2,9 @@ import { vec2, vec3 } from 'gl-matrix';
import { DrawableDescriptor } from '../drawable-descriptor';
import { LightDrawable } from './light-drawable';
/**
* @category Drawable
*/
export class CircleLight extends LightDrawable {
public static readonly descriptor: DrawableDescriptor = {
propertyUniformMapping: {

View file

@ -2,6 +2,9 @@ import { mat2d, vec2, vec3 } from 'gl-matrix';
import { DrawableDescriptor } from '../drawable-descriptor';
import { LightDrawable } from './light-drawable';
/**
* @category Drawable
*/
export class Flashlight extends LightDrawable {
public static readonly descriptor: DrawableDescriptor = {
propertyUniformMapping: {

View file

@ -1,6 +1,7 @@
import { mat2d, vec2, vec3 } from 'gl-matrix';
import { Drawable } from '../../main';
/** @internal */
export class LightDrawable extends Drawable {
protected lightnessRatio = 1;

View file

@ -2,6 +2,9 @@ import { mat2d, vec2 } from 'gl-matrix';
import { Drawable } from '../drawable';
import { DrawableDescriptor } from '../drawable-descriptor';
/**
* @category Drawable
*/
export class Circle extends Drawable {
public static descriptor: DrawableDescriptor = {
sdf: {

View file

@ -4,6 +4,9 @@ import { mix } from '../../helper/mix';
import { Drawable } from '../drawable';
import { DrawableDescriptor } from '../drawable-descriptor';
/**
* @category Drawable
*/
export class InvertedTunnel extends Drawable {
public static descriptor: DrawableDescriptor = {
sdf: {

View file

@ -4,6 +4,9 @@ import { mix } from '../../helper/mix';
import { Drawable } from '../drawable';
import { DrawableDescriptor } from '../drawable-descriptor';
/**
* @category Drawable
*/
export class Tunnel extends Drawable {
public static descriptor: DrawableDescriptor = {
sdf: {

View file

@ -1,6 +1,7 @@
import { UniversalRenderingContext } from '../universal-rendering-context';
import { FrameBuffer } from './frame-buffer';
/** @internal */
export class DefaultFrameBuffer extends FrameBuffer {
constructor(gl: UniversalRenderingContext) {
super(gl);

View file

@ -1,9 +1,10 @@
import { vec2 } from 'gl-matrix';
import { UniversalRenderingContext } from '../universal-rendering-context';
/** @internal */
export abstract class FrameBuffer {
public renderScale = 1;
public enableHighDpiRendering = false;
public enableHighDpiRendering!: boolean;
protected size = vec2.create();

View file

@ -2,6 +2,7 @@ import { enableExtension } from '../helper/enable-extension';
import { UniversalRenderingContext } from '../universal-rendering-context';
import { FrameBuffer } from './frame-buffer';
/** @internal */
export class IntermediateFrameBuffer extends FrameBuffer {
private frameTexture: WebGLTexture;
private floatEnabled = false;

View file

@ -1,5 +1,7 @@
/** @internal */
let isEnabled = false;
/** @internal */
export const enableContextLostSimulator = (canvas: HTMLCanvasElement) => {
if (isEnabled) {
return;

View file

@ -1,6 +1,7 @@
import { Insights } from '../../rendering/insights';
import { UniversalRenderingContext } from '../universal-rendering-context';
/** @internal */
export const tryEnableExtension = (
gl: UniversalRenderingContext,
name: string
@ -15,6 +16,7 @@ export const tryEnableExtension = (
return extension;
};
/** @internal */
export const enableExtension = (gl: UniversalRenderingContext, name: string): any => {
const extension = tryEnableExtension(gl, name);

View file

@ -1,8 +1,10 @@
import { mat3, ReadonlyVec3, ReadonlyVec4, vec2, vec3, vec4 } from 'gl-matrix';
import { UniversalRenderingContext } from '../universal-rendering-context';
/** @internal */
const loaderMat3 = mat3.create();
/** @internal */
export const loadUniform = (
gl: UniversalRenderingContext,
value: any,

View file

@ -1,12 +1,14 @@
import { UniversalRenderingContext } from '../universal-rendering-context';
import { enableExtension } from './enable-extension';
/** @internal */
enum StopwatchState {
ready = 'ready',
running = 'running',
waitingForResults = 'waitingForResults',
}
/** @internal */
export class WebGlStopwatch {
private state = StopwatchState.ready;
private resultsInNanoSeconds = 0;

View file

@ -1,6 +1,7 @@
import { vec3, vec4 } from 'gl-matrix';
import { UniversalRenderingContext } from './universal-rendering-context';
/** @internal */
export class PaletteTexture {
private texture: WebGLTexture;

View file

@ -3,6 +3,7 @@ import { Insights } from '../rendering/insights';
import { tryEnableExtension } from './helper/enable-extension';
import { UniversalRenderingContext } from './universal-rendering-context';
/** @internal */
type CompilingProgram = {
program: WebGLProgram;
resolvePromise: ((program: WebGLProgram) => void) | null;
@ -10,8 +11,10 @@ type CompilingProgram = {
fragmentShader: ShaderWithSource;
};
/** @internal */
type ShaderWithSource = WebGLShader & { source: string };
/** @internal */
export class ParallelCompiler {
private extension?: any;
private gl: UniversalRenderingContext;

View file

@ -3,6 +3,7 @@ import { ParallelCompiler } from '../parallel-compiler';
import { UniversalRenderingContext } from '../universal-rendering-context';
import Program from './program';
/** @internal */
export class FragmentShaderOnlyProgram extends Program {
private vao?: WebGLVertexArrayObject;
private vertexArrayExtension: any;

View file

@ -1,5 +1,6 @@
import { vec2 } from 'gl-matrix';
/** @internal */
export interface IProgram {
setDrawingRectangleUV(bottomLeft: vec2, size: vec2): void;
draw(values: { [name: string]: any }): void;

View file

@ -4,6 +4,7 @@ import { ParallelCompiler } from '../parallel-compiler';
import { UniversalRenderingContext } from '../universal-rendering-context';
import { IProgram } from './i-program';
/** @internal */
export default abstract class Program implements IProgram {
protected program?: WebGLProgram;

View file

@ -7,6 +7,7 @@ import { UniversalRenderingContext } from '../universal-rendering-context';
import { FragmentShaderOnlyProgram } from './fragment-shader-only-program';
import { IProgram } from './i-program';
/** @internal */
export class UniformArrayAutoScalingProgram implements IProgram {
private programs: Array<{
program: FragmentShaderOnlyProgram;

View file

@ -1,8 +1,10 @@
import { Insights } from '../rendering/insights';
/** @internal */
export type UniversalRenderingContext = WebGL2RenderingContext &
WebGLRenderingContext & { isWebGL2: boolean };
/** @internal */
export const getUniversalRenderingContext = (
canvas: HTMLCanvasElement,
ignoreWebGL2 = false

View file

@ -3,6 +3,7 @@ import { exponentialDecay } from '../../helper/exponential-decay';
import { mix } from '../../helper/mix';
import { Insights } from './insights';
/** @internal */
const settings = {
targetDeltaTimeInMilliseconds: 20,
deltaTimeErrorInMilliseconds: 3,
@ -30,6 +31,7 @@ const settings = {
qualityStepDecrese: 0.2,
};
/** @internal */
export class FpsAutoscaler {
private timeSinceLastAdjusment = 0;
private exponentialDecayedDeltaTime = settings.targetDeltaTimeInMilliseconds;

View file

@ -1,6 +1,7 @@
import { last } from '../../helper/last';
import { msToString } from '../../helper/ms-to-string';
/** @internal */
export class Insights {
private static insights: any = {};

View file

@ -3,9 +3,10 @@ import { Drawable } from '../../../drawables/drawable';
import { Insights } from '../insights';
import { RenderPass } from './render-pass';
/** @internal */
export class DistanceRenderPass extends RenderPass {
public tileMultiplier = 8;
public isWorldInverted = false;
public tileMultiplier!: number;
public isWorldInverted!: boolean;
private drawables: Array<Drawable> = [];

View file

@ -4,8 +4,9 @@ import { clamp01 } from '../../../helper/clamp';
import { Insights } from '../insights';
import { RenderPass } from './render-pass';
/** @internal */
export class LightsRenderPass extends RenderPass {
public lightCutoffDistance = 400;
public lightCutoffDistance!: number;
private drawables: Array<LightDrawable> = [];
public addDrawable(drawable: LightDrawable) {

View file

@ -4,6 +4,7 @@ import { ParallelCompiler } from '../../graphics-library/parallel-compiler';
import { UniformArrayAutoScalingProgram } from '../../graphics-library/program/uniform-array-autoscaling-program';
import { UniversalRenderingContext } from '../../graphics-library/universal-rendering-context';
/** @internal */
export abstract class RenderPass {
protected program: UniformArrayAutoScalingProgram;

View file

@ -1,10 +1,12 @@
import { vec2 } from 'gl-matrix';
import { Drawable, DrawableDescriptor } from '../../../main';
import { Drawable } from '../../../drawables/drawable';
import { DrawableDescriptor } from '../../../drawables/drawable-descriptor';
import { RuntimeSettings } from '../settings/runtime-settings';
import { StartupSettings } from '../settings/startup-settings';
import { Renderer } from './renderer';
import { RendererImplementation } from './renderer-implementation';
/** @internal */
export class ContextAwareRenderer implements Renderer {
private renderer?: RendererImplementation;
private isRendererReady = false;

View file

@ -16,6 +16,7 @@ import { FpsAutoscaler } from '../fps-autoscaler';
import { Insights } from '../insights';
import { DistanceRenderPass } from '../render-pass/distance-render-pass';
import { LightsRenderPass } from '../render-pass/lights-render-pass';
import { defaultRuntimeSettings } from '../settings/default-runtime-settings';
import { defaultStartupSettings } from '../settings/default-startup-settings';
import { RuntimeSettings } from '../settings/runtime-settings';
import { StartupSettings } from '../settings/startup-settings';
@ -30,6 +31,7 @@ import lightsVertexShader from '../shaders/shading-vs.glsl';
import { UniformsProvider } from '../uniforms-provider';
import { Renderer } from './renderer';
/** @internal */
export class RendererImplementation implements Renderer {
private readonly gl: UniversalRenderingContext;
private stopwatch?: WebGlStopwatch;
@ -38,7 +40,7 @@ export class RendererImplementation implements Renderer {
private distancePass: DistanceRenderPass;
private lightingFrameBuffer: DefaultFrameBuffer;
private lightsPass: LightsRenderPass;
private palette?: PaletteTexture;
private palette!: PaletteTexture;
private autoscaler: FpsAutoscaler;
private applyRuntimeSettings: {
@ -53,7 +55,7 @@ export class RendererImplementation implements Renderer {
backgroundColor: (v) => (this.uniformsProvider.backgroundColor = v),
ambientLight: (v) => (this.uniformsProvider.ambientLight = v),
lightCutoffDistance: (v) => (this.lightsPass.lightCutoffDistance = v),
colorPalette: (v) => this.palette!.setPalette(v),
colorPalette: (v) => this.palette.setPalette(v),
};
setRuntimeSettings(overrides: Partial<RuntimeSettings>): void {
@ -103,6 +105,8 @@ export class RendererImplementation implements Renderer {
};
this.palette = new PaletteTexture(this.gl, settings.paletteSize);
this.setRuntimeSettings(defaultRuntimeSettings);
const promises: Array<Promise<void>> = [];
const compiler = new ParallelCompiler(this.gl);
@ -219,7 +223,7 @@ export class RendererImplementation implements Renderer {
this.lightsPass.render(
this.uniformsProvider.getUniforms(common),
this.distanceFieldFrameBuffer.colorTexture,
this.palette!.colorTexture
this.palette.colorTexture
);
this.gl.disable(this.gl.BLEND);
@ -243,6 +247,6 @@ export class RendererImplementation implements Renderer {
public destroy(): void {
this.distancePass.destroy();
this.lightsPass.destroy();
this.palette!.destroy();
this.palette.destroy();
}
}

View file

@ -2,15 +2,79 @@ import { vec2 } from 'gl-matrix';
import { Drawable } from '../../../drawables/drawable';
import { RuntimeSettings } from '../settings/runtime-settings';
/**
* The main interface through which rendering can be achieved.
*
* Multiple renderers are permitted on a single page.
*/
export interface Renderer {
/**
* Get the actual resolution of the canvas.
*/
readonly canvasSize: vec2;
/**
* Get the viewArea size set by the last `setViewArea`.
*
* By default, `canvasSize` is used for the view area size.
*/
readonly viewAreaSize: vec2;
/**
* Set the camera transformation.
*
* @param topLeft top (!) left. By default, equals to [0, canvasHeight].
* @param size need not be equal to the canvas size, though their aspect ratio
* should be the same to avoid stretching.
*/
setViewArea(topLeft: vec2, size: vec2): void;
/**
* Patch the current runtime settings with new values.
* @param overrides
*/
setRuntimeSettings(overrides: Partial<RuntimeSettings>): void;
/**
* Schedule a drawable to be rendered during the next `renderDrawables` call.
*
* @param drawable Must be a subclass of drawable and its class must contain a
* static descriptor property of type [[DrawableDescriptor]].
*/
addDrawable<T extends Drawable>(drawable: T): void;
/**
* Render every drawable added since the last `renderDrawables` call.
*
* Resizing of framebuffers and the canvas also takes effect
* when calling `renderDrawables`.
*/
renderDrawables(): void;
/**
* Let go of every GPU resource held by the renderer.
*
* It's up to the browser and driver whether these resources are actually freed.
* Nonetheless, when a renderer is no longer needed, this method should be called.
*/
destroy(): void;
/**
* @experimental
*
* Debug information updated on each `renderDrawables` call.
* Its scheme is not yet defined. The main purpose of this is
* human debugging.
*/
readonly insights: any;
setViewArea(topLeft: vec2, size: vec2): void;
setRuntimeSettings(overrides: Partial<RuntimeSettings>): void;
addDrawable(drawable: Drawable): void;
/**
* @experimental
*
* Scale the render scale for both the canvas and the SDF memoization based
* on the current and historical FPS values.
*
* @param deltaTime since the last frame, in milliseconds.
*/
autoscaleQuality(deltaTime: DOMHighResTimeStamp): void;
renderDrawables(): void;
destroy(): void;
}

View file

@ -0,0 +1,15 @@
import { vec3, vec4 } from 'gl-matrix';
import { RuntimeSettings } from './runtime-settings';
/**
* Contains the default values used for [[RuntimeSettings]].
*/
export const defaultRuntimeSettings: RuntimeSettings = {
enableHighDpiRendering: true,
tileMultiplier: 8,
isWorldInverted: false,
lightCutoffDistance: 400,
backgroundColor: vec4.fromValues(1, 1, 1, 1),
colorPalette: [],
ambientLight: vec3.fromValues(0.25, 0.15, 0.25),
};

View file

@ -1,5 +1,8 @@
import { StartupSettings } from './startup-settings';
/**
* Contains the default values used for [[StartupSettings]].
*/
export const defaultStartupSettings: StartupSettings = {
shadowTraceCount: 16,
paletteSize: 256,

View file

@ -1,11 +1,59 @@
import { vec3, vec4 } from 'gl-matrix';
/**
* Interface for a configuration object containing the settings
* that can be changed during runtime.
*
* The default values for RuntimeSettings can be found in [[defaultRuntimeSettings]].
*/
export interface RuntimeSettings {
/**
* When set to `true` rendering will be done on the screen's real resolution.
*/
enableHighDpiRendering: boolean;
/**
* First, the SDF of the scene is evaluated at every single pixel.
* For speeding this process up, the screen is divided up into tiles,
* this way each having to deal with a fewer objects.
*
* For each tile, it is decided which objects are near its close vicinity.
* This comes with some overhead for the CPU, while saving the GPU from loads of
* calculations. The workload can be balanced between the CPU and the GPU by setting
* this number.
*/
tileMultiplier: number;
/**
* By default, every pixel is outside of objects. Flipping this value to `true` will
* result in every pixel being inside a large object. From then it only makes sense to
* draw inverted objects.
*/
isWorldInverted: boolean;
/**
* When lights reach the end of the display, they are slowly faded out. The length
* of this phaseout can be set through this value.
*/
lightCutoffDistance: number;
/**
* The default background color of the scene, can have transparency.
*/
backgroundColor: vec3 | vec4;
/**
* Its length should be less than the one specified in [[StartupSettings]].paletteSize.
*
* The possible colors for the objects. Each color is referenced by its index in the
* palette.
*
* Can have transparency.
*/
colorPalette: Array<vec3 | vec4>;
/**
* A light affecting every pixel (even the ones inside objects).
*/
ambientLight: vec3;
}

View file

@ -1,5 +1,33 @@
/**
* Interface for a configuration object containing the settings
* that need to be given before shader compilation.
*
* The default values for StartupSettings can be found in [[defaultStartupSettings]].
*/
export interface StartupSettings {
/**
* The raytracing algorithm used for shadows requires a step count.
* Sensible values for this are between 8 and 32.
*
* The higher the number, the harder the shadows will get.
* Some ambient occlusion like effects can be visible on lower trace counts.
*/
shadowTraceCount: number;
/**
* Gives the number of possible object colors for the scene.
*
* When using WebGL, only 256 different colors can be used.
* On WebGL2, its value should not be larger than 4096 for
* maintaining compatibility with low-end devices.
*/
paletteSize: number;
/**
* When set to `true`, rendering will fall back to WebGL
* even when WebGL2 is present.
*
* Useful for testing compatibility.
*/
ignoreWebGL2: boolean;
}

View file

@ -1,9 +1,10 @@
import { mat2d, vec2, vec3, vec4 } from 'gl-matrix';
import { UniversalRenderingContext } from '../graphics-library/universal-rendering-context';
/** @internal */
export class UniformsProvider {
public ambientLight = vec3.fromValues(0.25, 0.15, 0.25);
public _backgroundColor = vec4.fromValues(1, 1, 1, 1);
public ambientLight!: vec3;
public _backgroundColor!: vec4;
private scaleWorldLengthToNDC = 1;
private transformWorldToNDC = mat2d.create();

View file

@ -1,3 +1,4 @@
/** @internal */
declare global {
interface Array<T> {
x: number;
@ -10,6 +11,7 @@ declare global {
}
}
/** @internal */
const setIndexAlias = (name: string, index: number, type: any) => {
if (!Object.prototype.hasOwnProperty.call(type.prototype, name)) {
Object.defineProperty(type.prototype, name, {
@ -23,6 +25,7 @@ const setIndexAlias = (name: string, index: number, type: any) => {
}
};
/** @internal */
export const applyArrayPlugins = () => {
setIndexAlias('x', 0, Array);
setIndexAlias('y', 1, Array);

View file

@ -1,4 +1,6 @@
/** @internal */
export const clamp = (value: number, min: number, max: number): number =>
Math.min(max, Math.max(min, value));
/** @internal */
export const clamp01 = (value: number): number => Math.min(1, Math.max(0, value));

View file

@ -1,3 +1,4 @@
/** @internal */
export const exponentialDecay = (
accumulator: number,
nextValue: number,

View file

@ -1,3 +1,4 @@
/** @internal */
export const getCombinations = (values: Array<Array<number>>): Array<Array<number>> => {
if (!values.every((a) => a.length > 0)) {
return [];

View file

@ -1,3 +1,4 @@
/** @internal */
export function last<T>(a: Array<T>): T | null {
return a.length > 0 ? a[a.length - 1] : null;
}

View file

@ -1 +1,2 @@
/** @internal */
export const mix = (from: number, to: number, q: number) => from + (to - from) * q;

View file

@ -1 +1,2 @@
/** @internal */
export const msToString = (value: number) => `${value.toFixed(3)} ms`;

View file

@ -1,3 +1,4 @@
/** @internal */
export const wait = (ms: number): Promise<void> => {
return new Promise<void>((resolve, _) => setTimeout(resolve, ms));
};

View file

@ -13,6 +13,7 @@ import { Renderer } from './graphics/rendering/renderer/renderer';
import { StartupSettings } from './graphics/rendering/settings/startup-settings';
import { applyArrayPlugins } from './helper/array';
/** @internal */
declare global {
interface Array<T> {
x: number;
@ -29,8 +30,8 @@ applyArrayPlugins();
/**
* Compiles a new renderer instance. There can multiple renderers on a single page.
* > Asynchronous behaviour is required for paralell shader compiling.
* > Trying to draw before the returned promise resolves results in no action taken.
* > Asynchronous behaviour is required for parallel shader compiling.
* > Trying to draw before the returned promise resolves, results in no action taken.
* > Settings can be set before promise resolution and they will be applied later.
*
* The descriptors of every to-be-drawn objects are required before creating the renderer,
@ -48,9 +49,7 @@ applyArrayPlugins();
* @param canvas The returned renderer will only be able to draw to this canvas.
* @param descriptors The descriptor of every single object (and light) that
* ever needs to be drawn by this renderer has to be given before compiling.
* @param settingsOverrides Sensible defaults are provided, but these can be overriden.
*
* @category Startup
* @param settingsOverrides Sensible defaults are provided, but these can be overridden.
*/
export async function compile(
canvas: HTMLCanvasElement,