Add more improvements

This commit is contained in:
schmelczerandras 2020-09-16 14:45:08 +02:00
parent e1c74a8054
commit bc16bdd62e
29 changed files with 288 additions and 160 deletions

View file

@ -1,5 +1,4 @@
import { mat2d, vec2, vec3 } from 'gl-matrix'; import { mat2d, vec2, vec3 } from 'gl-matrix';
import { settings } from '../../graphics/settings';
import { Drawable } from '../drawable'; import { Drawable } from '../drawable';
import { DrawableDescriptor } from '../drawable-descriptor'; import { DrawableDescriptor } from '../drawable-descriptor';
@ -8,7 +7,7 @@ export class CircleLight extends Drawable {
return { return {
uniformName: 'circleLights', uniformName: 'circleLights',
uniformCountMacroName: 'CIRCLE_LIGHT_COUNT', uniformCountMacroName: 'CIRCLE_LIGHT_COUNT',
shaderCombinationSteps: settings.shaderCombinations.circleLightSteps, shaderCombinationSteps: [0, 1, 2, 4],
empty: new CircleLight(vec2.fromValues(0, 0), 0, vec3.fromValues(0, 0, 0), 0), empty: new CircleLight(vec2.fromValues(0, 0), 0, vec3.fromValues(0, 0, 0), 0),
}; };
} }

View file

@ -1,5 +1,4 @@
import { mat2d, vec2, vec3 } from 'gl-matrix'; import { mat2d, vec2, vec3 } from 'gl-matrix';
import { settings } from '../../graphics/settings';
import { Drawable } from '../drawable'; import { Drawable } from '../drawable';
import { DrawableDescriptor } from '../drawable-descriptor'; import { DrawableDescriptor } from '../drawable-descriptor';
@ -8,7 +7,7 @@ export class Flashlight extends Drawable {
return { return {
uniformName: 'flashlights', uniformName: 'flashlights',
uniformCountMacroName: 'FLASHLIGHT_COUNT', uniformCountMacroName: 'FLASHLIGHT_COUNT',
shaderCombinationSteps: settings.shaderCombinations.flashlightSteps, shaderCombinationSteps: [0, 1, 2, 4],
empty: new Flashlight( empty: new Flashlight(
vec2.fromValues(0, 0), vec2.fromValues(0, 0),
vec2.fromValues(0, 0), vec2.fromValues(0, 0),

View file

@ -13,10 +13,16 @@ export class Circle extends Drawable {
}[CIRCLE_COUNT] circles; }[CIRCLE_COUNT] circles;
void circleMinDistance(inout float minDistance, inout float color) { void circleMinDistance(inout float minDistance, inout float color) {
float circleMinDistance = minDistance;
for (int i = 0; i < CIRCLE_COUNT; i++) { for (int i = 0; i < CIRCLE_COUNT; i++) {
float dist = distance(circles[i].center, position) - circles[i].radius; float dist = distance(circles[i].center, position) - circles[i].radius;
minDistance = min(minDistance, dist); circleMinDistance = min(circleMinDistance, dist);
} }
minDistance = min(minDistance, circleMinDistance);
color = mix(2.0, color, step(
distanceNdcPixelSize + SURFACE_OFFSET,
circleMinDistance
));
} }
`, `,
distanceFunctionName: 'circleMinDistance', distanceFunctionName: 'circleMinDistance',
@ -32,8 +38,8 @@ export class Circle extends Drawable {
super(); super();
} }
public distance(position: vec2): number { public distance(target: vec2): number {
return vec2.dist(this.center, position) - this.radius; return vec2.dist(this.center, target) - this.radius;
} }
protected getObjectToSerialize(transform2d: mat2d, transform1d: number): any { protected getObjectToSerialize(transform2d: mat2d, transform1d: number): any {

View file

@ -0,0 +1,93 @@
import { mat2d, vec2 } from 'gl-matrix';
import { clamp01 } from '../../helper/clamp';
import { mix } from '../../helper/mix';
import { Drawable } from '../drawable';
import { DrawableDescriptor } from '../drawable-descriptor';
export class Tunnel extends Drawable {
public readonly isInverted = false;
public readonly toFromDelta: vec2;
public static get descriptor(): DrawableDescriptor {
return {
sdf: {
shader: `
uniform struct Tunnel {
vec2 from;
vec2 toFromDelta;
float fromRadius;
float toRadius;
float inverted;
}[TUNNEL_COUNT] tunnels;
void tunnelMinDistance(inout float minDistance, inout float color) {
float tunnelMinDistance = minDistance;
for (int i = 0; i < TUNNEL_COUNT; i++) {
Tunnel tunnel = tunnels[i];
vec2 targetFromDelta = position - tunnel.from;
float h = clamp(
dot(targetFromDelta, tunnel.toFromDelta)
/ dot(tunnel.toFromDelta, tunnel.toFromDelta),
0.0, 1.0
);
float lineDistance = -mix(
tunnel.fromRadius, tunnel.toRadius, h
) + tunnel.inverted * distance(
targetFromDelta, tunnel.toFromDelta * h
);
tunnelMinDistance = min(tunnelMinDistance, lineDistance);
}
color = mix(2.0, color, step(
distanceNdcPixelSize + SURFACE_OFFSET,
-tunnelMinDistance
));
minDistance = -tunnelMinDistance;
}
`,
distanceFunctionName: 'tunnelMinDistance',
},
uniformName: 'tunnels',
uniformCountMacroName: 'TUNNEL_COUNT',
shaderCombinationSteps: [0, 1, 2, 8, 32],
empty: new Tunnel(vec2.fromValues(0, 0), vec2.fromValues(0, 0), 0, 0),
};
}
constructor(
public readonly from: vec2,
public readonly to: vec2,
public readonly fromRadius: number,
public readonly toRadius: number
) {
super();
this.toFromDelta = vec2.subtract(vec2.create(), to, from);
}
public distance(target: vec2): number {
const targetFromDelta = vec2.subtract(vec2.create(), target, this.from);
const h = clamp01(
vec2.dot(targetFromDelta, this.toFromDelta) /
vec2.dot(this.toFromDelta, this.toFromDelta)
);
return (
vec2.distance(targetFromDelta, vec2.scale(vec2.create(), this.toFromDelta, h)) -
mix(this.fromRadius, this.toRadius, h)
);
}
protected getObjectToSerialize(transform2d: mat2d, transform1d: number): any {
return {
from: vec2.transformMat2d(vec2.create(), this.from, transform2d),
toFromDelta: vec2.scale(vec2.create(), this.toFromDelta, transform1d),
fromRadius: this.fromRadius * transform1d,
toRadius: this.toRadius * transform1d,
inverted: this.isInverted ? -1 : 1,
};
}
}

View file

@ -3,7 +3,7 @@ import { checkShader } from './check-shader';
export const checkProgram = (gl: WebGL2RenderingContext, program: WebGLProgram) => { export const checkProgram = (gl: WebGL2RenderingContext, program: WebGLProgram) => {
const success = gl.getProgramParameter(program, gl.LINK_STATUS); const success = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!success) { if (!success && !gl.isContextLost()) {
gl.getAttachedShaders(program)?.forEach((s) => { gl.getAttachedShaders(program)?.forEach((s) => {
checkShader(gl, s); checkShader(gl, s);
}); });

View file

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

View file

@ -7,11 +7,8 @@ export const createProgram = (
fragmentShaderSource: string, fragmentShaderSource: string,
substitutions: { [name: string]: string } substitutions: { [name: string]: string }
): WebGLProgram => { ): WebGLProgram => {
const program = gl.createProgram(); // can only return null on lost context
const program = gl.createProgram()!;
if (!program) {
throw new Error('Could not create program');
}
// const extension = tryEnableExtension(gl, 'KHR_parallel_shader_compile'); // const extension = tryEnableExtension(gl, 'KHR_parallel_shader_compile');
@ -43,5 +40,8 @@ export const createProgram = (
checkProgram(gl, program); checkProgram(gl, program);
gl.deleteShader(vertexShader);
gl.deleteShader(fragmentShader);
return program; return program;
}; };

View file

@ -9,11 +9,8 @@ export const createShader = (
return Number.isInteger(value) ? `${value}.0` : value; return Number.isInteger(value) ? `${value}.0` : value;
}); });
const shader = gl.createShader(type); // can only return null on lost context
const shader = gl.createShader(type)!;
if (!shader) {
throw new Error('Could not create shader');
}
gl.shaderSource(shader, source); gl.shaderSource(shader, source);
gl.compileShader(shader); gl.compileShader(shader);

View file

@ -1,8 +1,8 @@
import { FrameBuffer } from './frame-buffer'; import { FrameBuffer } from './frame-buffer';
export class DefaultFrameBuffer extends FrameBuffer { export class DefaultFrameBuffer extends FrameBuffer {
constructor(gl: WebGL2RenderingContext) { constructor(gl: WebGL2RenderingContext, enableHighDpiRendering: boolean) {
super(gl); super(gl, enableHighDpiRendering);
this.frameBuffer = null; this.frameBuffer = null;
this.setSize(); this.setSize();
} }

View file

@ -1,16 +1,17 @@
import { vec2 } from 'gl-matrix'; import { vec2 } from 'gl-matrix';
import { settings } from '../../settings';
export abstract class FrameBuffer { export abstract class FrameBuffer {
public renderScale = 1; public renderScale = 1;
public enableHighDpiRendering = settings.enableHighDpiRendering;
protected size = vec2.create(); protected size = vec2.create();
// null means the default framebuffer // null means the default framebuffer
protected frameBuffer: WebGLFramebuffer | null = null; protected frameBuffer: WebGLFramebuffer | null = null;
constructor(protected gl: WebGL2RenderingContext) {} constructor(
protected gl: WebGL2RenderingContext,
private enableHighDpiRendering: boolean
) {}
public bindAndClear(colorInput?: WebGLTexture) { public bindAndClear(colorInput?: WebGLTexture) {
this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, this.frameBuffer); this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, this.frameBuffer);

View file

@ -5,8 +5,8 @@ export class IntermediateFrameBuffer extends FrameBuffer {
private frameTexture: WebGLTexture; private frameTexture: WebGLTexture;
private floatLinearEnabled = false; private floatLinearEnabled = false;
constructor(gl: WebGL2RenderingContext) { constructor(gl: WebGL2RenderingContext, enableHighDpiRendering: boolean) {
super(gl); super(gl, enableHighDpiRendering);
enableExtension(gl, 'EXT_color_buffer_float'); enableExtension(gl, 'EXT_color_buffer_float');
@ -17,18 +17,12 @@ export class IntermediateFrameBuffer extends FrameBuffer {
// it's okay // it's okay
} }
const texture = this.gl.createTexture(); // can only return null on lost context
if (!texture) { this.frameTexture = this.gl.createTexture()!;
throw new Error('Could not create texture');
}
this.frameTexture = texture;
this.configureTexture(); this.configureTexture();
const frameBuffer = this.gl.createFramebuffer(); // can only return null on lost context
if (!frameBuffer) { this.frameBuffer = this.gl.createFramebuffer()!;
throw new Error('Could not create frame buffer');
}
this.frameBuffer = frameBuffer;
this.configureFrameBuffer(); this.configureFrameBuffer();
this.setSize(); this.setSize();

View file

@ -1,11 +1,13 @@
import { Insights } from '../../rendering/insights';
const extensions: Map<string, any> = new Map(); const extensions: Map<string, any> = new Map();
const printExtensions = () => { const logExtensions = () => {
const values = {}; const values = {};
for (const [k, v] of extensions.entries()) { for (const [k, v] of extensions.entries()) {
values[k] = v !== null; values[k] = v !== null;
} }
//InfoText.modifyRecord('extensions', values); Insights.setValue('extensions', values);
}; };
export const tryEnableExtension = ( export const tryEnableExtension = (
@ -23,7 +25,7 @@ export const tryEnableExtension = (
extensions.set(name, extension); extensions.set(name, extension);
printExtensions(); logExtensions();
return extension; return extension;
}; };

View file

@ -1,3 +1,4 @@
import { Insights } from '../../rendering/insights';
import { enableExtension } from './enable-extension'; import { enableExtension } from './enable-extension';
// https://www.khronos.org/registry/webgl/extensions/EXT_disjoint_timer_query_webgl2/ // https://www.khronos.org/registry/webgl/extensions/EXT_disjoint_timer_query_webgl2/
@ -37,7 +38,7 @@ export class WebGlStopwatch {
this.gl.QUERY_RESULT this.gl.QUERY_RESULT
); );
//InfoText.modifyRecord('Draw time', `${this.resultsInMilliSeconds.toFixed(2)} ms`); Insights.setValue('GPU draw time', `${this.resultsInMilliSeconds.toFixed(2)} ms`);
this.isReady = true; this.isReady = true;
} }

View file

@ -35,11 +35,9 @@ export class FragmentShaderOnlyProgram extends Program {
new Float32Array([-1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0]), new Float32Array([-1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0]),
this.gl.STATIC_DRAW this.gl.STATIC_DRAW
); );
const vao = this.gl.createVertexArray();
if (!vao) { // can only return null on lost context
throw new Error('Could not create vertex array object'); this.vao = this.gl.createVertexArray()!;
}
this.vao = vao;
this.gl.bindVertexArray(this.vao); this.gl.bindVertexArray(this.vao);
this.gl.enableVertexAttribArray(positionAttributeLocation); this.gl.enableVertexAttribArray(positionAttributeLocation);

View file

@ -1,5 +1,4 @@
import { mat2d, vec2 } from 'gl-matrix'; import { mat2d, vec2 } from 'gl-matrix';
import { settings } from '../../settings';
import { createProgram } from '../compiling/create-program'; import { createProgram } from '../compiling/create-program';
import { loadUniform } from '../helper/load-uniform'; import { loadUniform } from '../helper/load-uniform';
import { IProgram } from './i-program'; import { IProgram } from './i-program';
@ -20,7 +19,7 @@ export default abstract class Program implements IProgram {
[vertexShaderSource, fragmentShaderSource]: [string, string], [vertexShaderSource, fragmentShaderSource]: [string, string],
substitutions: { [name: string]: string } substitutions: { [name: string]: string }
) { ) {
substitutions = { ...settings.shaderMacros, ...substitutions }; substitutions = { ...substitutions };
this.program = createProgram( this.program = createProgram(
this.gl, this.gl,

View file

@ -18,7 +18,8 @@ export class UniformArrayAutoScalingProgram implements IProgram {
constructor( constructor(
private gl: WebGL2RenderingContext, private gl: WebGL2RenderingContext,
shaderSources: [string, string], shaderSources: [string, string],
private descriptors: Array<DrawableDescriptor> private descriptors: Array<DrawableDescriptor>,
private substitutions: { [name: string]: any }
) { ) {
for (const combination of getCombinations( for (const combination of getCombinations(
descriptors.map((o) => o.shaderCombinationSteps) descriptors.map((o) => o.shaderCombinationSteps)
@ -75,6 +76,7 @@ export class UniformArrayAutoScalingProgram implements IProgram {
shaderSources: [string, string] shaderSources: [string, string]
): FragmentShaderOnlyProgram { ): FragmentShaderOnlyProgram {
const substitutions = { const substitutions = {
...this.substitutions,
macroDefinitions: this.getMacroDefinitions(combination, descriptors), macroDefinitions: this.getMacroDefinitions(combination, descriptors),
declarations: this.getDeclarations(combination, descriptors), declarations: this.getDeclarations(combination, descriptors),
functionCalls: this.getFunctionCalls(combination, descriptors), functionCalls: this.getFunctionCalls(combination, descriptors),

View file

@ -0,0 +1,21 @@
export class Insights {
private static insights: any = {};
public static setValue(key: string | Array<string>, value: any): void {
if (Array.isArray(key)) {
key.reduce((previousValue, currentKey) => {
if (!Object.prototype.hasOwnProperty.call(previousValue, currentKey)) {
previousValue[currentKey] = {};
}
return previousValue[currentKey];
}, Insights.insights);
} else {
Insights.insights[key] = value;
}
}
public static get values(): any {
return Insights.insights;
}
}

View file

@ -2,13 +2,13 @@ import { vec2 } from 'gl-matrix';
import { Drawable } from '../../drawables/drawable'; import { Drawable } from '../../drawables/drawable';
export interface Renderer { export interface Renderer {
setViewArea(topLeft: vec2, size: vec2): void;
addDrawable(drawable: Drawable): void;
renderDrawables(): void;
autoscaleQuality(deltaTime: DOMHighResTimeStamp): void;
readonly canvasSize: vec2; readonly canvasSize: vec2;
readonly insights: any;
setViewArea(topLeft: vec2, size: vec2): void;
setCursorPosition(position: vec2): void; setCursorPosition(position: vec2): void;
addDrawable(drawable: Drawable): void;
autoscaleQuality(deltaTime: DOMHighResTimeStamp): void;
renderDrawables(): void;
destroy(): void;
} }

View file

@ -3,7 +3,6 @@ import { Drawable } from '../../drawables/drawable';
import { DrawableDescriptor } from '../../drawables/drawable-descriptor'; import { DrawableDescriptor } from '../../drawables/drawable-descriptor';
import { FrameBuffer } from '../graphics-library/frame-buffer/frame-buffer'; import { FrameBuffer } from '../graphics-library/frame-buffer/frame-buffer';
import { UniformArrayAutoScalingProgram } from '../graphics-library/program/uniform-array-autoscaling-program'; import { UniformArrayAutoScalingProgram } from '../graphics-library/program/uniform-array-autoscaling-program';
import { settings } from '../settings';
export class RenderingPass { export class RenderingPass {
private drawables: Array<Drawable> = []; private drawables: Array<Drawable> = [];
@ -13,12 +12,15 @@ export class RenderingPass {
gl: WebGL2RenderingContext, gl: WebGL2RenderingContext,
shaderSources: [string, string], shaderSources: [string, string],
drawableDescriptors: Array<DrawableDescriptor>, drawableDescriptors: Array<DrawableDescriptor>,
private frame: FrameBuffer private frame: FrameBuffer,
substitutions: { [name: string]: any },
private tileMultiplier: number
) { ) {
this.program = new UniformArrayAutoScalingProgram( this.program = new UniformArrayAutoScalingProgram(
gl, gl,
shaderSources, shaderSources,
drawableDescriptors drawableDescriptors,
substitutions
); );
} }
@ -29,7 +31,7 @@ export class RenderingPass {
public render(commonUniforms: any, inputTexture?: WebGLTexture) { public render(commonUniforms: any, inputTexture?: WebGLTexture) {
this.frame.bindAndClear(inputTexture); this.frame.bindAndClear(inputTexture);
const stepsInUV = 1 / settings.tileMultiplier; const stepsInUV = 1 / this.tileMultiplier;
const worldR = const worldR =
0.5 * 0.5 *
@ -41,7 +43,7 @@ export class RenderingPass {
for (let x = -1; x < 1; x += stepsInNDC) { for (let x = -1; x < 1; x += stepsInNDC) {
for (let y = -1; y < 1; y += stepsInNDC) { for (let y = -1; y < 1; y += stepsInNDC) {
const uniforms = { ...commonUniforms, maxMinDistance: 0.0 }; const uniforms = { ...commonUniforms, maxMinDistance: radiusInNDC };
const ndcBottomLeft = vec2.fromValues(x, y); const ndcBottomLeft = vec2.fromValues(x, y);

View file

@ -13,37 +13,6 @@ in vec2 position;
{declarations} {declarations}
/* /*
#if LINE_COUNT > 0
uniform struct {
vec2 from;
vec2 toFromDelta;
float fromRadius;
float toRadius;
}[LINE_COUNT] lines;
void lineMinDistance(inout float minDistance, inout float color) {
float myMinDistance = maxMinDistance;
for (int i = 0; i < LINE_COUNT; i++) {
vec2 targetFromDelta = position - lines[i].from;
vec2 toFromDelta = lines[i].toFromDelta;
float h = clamp(
dot(targetFromDelta, toFromDelta) / dot(toFromDelta, toFromDelta),
0.0, 1.0
);
float lineDistance = -mix(
lines[i].fromRadius, lines[i].toRadius, h
) + distance(
targetFromDelta, toFromDelta * h
);
myMinDistance = min(myMinDistance, lineDistance);
}
color = mix(0.0, color, step(distanceNdcPixelSize + SURFACE_OFFSET, -myMinDistance));
minDistance = -myMinDistance;
}
#endif #endif
#if BLOB_COUNT > 0 #if BLOB_COUNT > 0
uniform struct { uniform struct {
@ -93,7 +62,7 @@ in vec2 position;
out vec2 fragmentColor; out vec2 fragmentColor;
void main() { void main() {
float minDistance = 10.0; //-maxMinDistance; float minDistance = maxMinDistance;
float color = 1.0; float color = 1.0;
{functionCalls} {functionCalls}

View file

@ -3,9 +3,11 @@
precision lowp float; precision lowp float;
#define INFINITY 1000.0 #define INFINITY 1000.0
#define LIGHT_DROP_INSIDE_RATIO 0.3 #define LIGHT_DROP_INSIDE_RATIO 0.5
#define AMBIENT_LIGHT vec3(0.25, 0.15, 0.25) #define AMBIENT_LIGHT vec3(0.25, 0.15, 0.25)
#define SHADOW_HARDNESS 150.0 #define SHADOW_HARDNESS 150.0
#define HARD_SHADOW_TRACE_COUNT {hardShadowTraceCount}
#define SOFT_SHADOW_TRACE_COUNT {softShadowTraceCount}
{macroDefinitions} {macroDefinitions}
@ -18,9 +20,7 @@ in vec2 position;
in vec2 uvCoordinates; in vec2 uvCoordinates;
vec3[3] colors = vec3[]( vec3[3] colors = vec3[](
vec3(0.4, 0.35, 0.6), // cave color {palette}
vec3(0.0, 1.0, 0.0),
vec3(0.0, 0.0, 1.0)
); );
float getDistance(in vec2 target, out vec3 color) { float getDistance(in vec2 target, out vec3 color) {
@ -37,7 +37,7 @@ float softShadowTransparency(float startingDistance, float lightCenterDistance,
float rayLength = startingDistance; float rayLength = startingDistance;
float q = 1.0 / SHADOW_HARDNESS; float q = 1.0 / SHADOW_HARDNESS;
for (int j = 0; j < 128; j++) { for (int j = 0; j < SOFT_SHADOW_TRACE_COUNT; j++) {
float minDistance = getDistance(uvCoordinates + direction * rayLength); float minDistance = getDistance(uvCoordinates + direction * rayLength);
q = min(q, minDistance / rayLength); q = min(q, minDistance / rayLength);
@ -54,7 +54,7 @@ float softShadowTransparency(float startingDistance, float lightCenterDistance,
float hardShadowTransparency(float startingDistance, float lightCenterDistance, vec2 direction) { float hardShadowTransparency(float startingDistance, float lightCenterDistance, vec2 direction) {
float rayLength = startingDistance; float rayLength = startingDistance;
for (int j = 0; j < 32; j++) { for (int j = 0; j < HARD_SHADOW_TRACE_COUNT; j++) {
rayLength += getDistance(uvCoordinates + direction * rayLength); rayLength += getDistance(uvCoordinates + direction * rayLength);
} }

View file

@ -0,0 +1,9 @@
export interface WebGl2RendererSettings {
enableHighDpiRendering: boolean;
enableStopwatch: boolean;
tileMultiplier: number;
shaderMacros: {
softShadowTraceCount: string;
hardShadowTraceCount: string;
};
}

View file

@ -1,19 +1,21 @@
import { vec2 } from 'gl-matrix'; import { vec2, vec3 } from 'gl-matrix';
import { Drawable } from '../../drawables/drawable'; import { Drawable } from '../../drawables/drawable';
import { DrawableDescriptor } from '../../drawables/drawable-descriptor'; import { DrawableDescriptor } from '../../drawables/drawable-descriptor';
import { DefaultFrameBuffer } from '../graphics-library/frame-buffer/default-frame-buffer'; import { DefaultFrameBuffer } from '../graphics-library/frame-buffer/default-frame-buffer';
import { IntermediateFrameBuffer } from '../graphics-library/frame-buffer/intermediate-frame-buffer'; import { IntermediateFrameBuffer } from '../graphics-library/frame-buffer/intermediate-frame-buffer';
import { getWebGl2Context } from '../graphics-library/helper/get-webgl2-context'; import { getWebGl2Context } from '../graphics-library/helper/get-webgl2-context';
import { WebGlStopwatch } from '../graphics-library/helper/stopwatch'; import { WebGlStopwatch } from '../graphics-library/helper/stopwatch';
import distanceFragmentShader from '../shaders/distance-fs.glsl';
import distanceVertexShader from '../shaders/distance-vs.glsl';
import lightsFragmentShader from '../shaders/shading-fs.glsl';
import lightsVertexShader from '../shaders/shading-vs.glsl';
import { FpsAutoscaler } from './fps-autoscaler'; import { FpsAutoscaler } from './fps-autoscaler';
import { Insights } from './insights';
import { Renderer } from './renderer'; import { Renderer } from './renderer';
import { RenderingPass } from './rendering-pass'; import { RenderingPass } from './rendering-pass';
import { RenderingPassName } from './rendering-pass-name'; import { RenderingPassName } from './rendering-pass-name';
import distanceFragmentShader from './shaders/distance-fs.glsl';
import distanceVertexShader from './shaders/distance-vs.glsl';
import lightsFragmentShader from './shaders/shading-fs.glsl';
import lightsVertexShader from './shaders/shading-vs.glsl';
import { UniformsProvider } from './uniforms-provider'; import { UniformsProvider } from './uniforms-provider';
import { WebGl2RendererSettings } from './webgl2-renderer-settings';
export class WebGl2Renderer implements Renderer { export class WebGl2Renderer implements Renderer {
private gl: WebGL2RenderingContext; private gl: WebGL2RenderingContext;
@ -24,24 +26,54 @@ export class WebGl2Renderer implements Renderer {
private passes: { [key in keyof typeof RenderingPassName]: RenderingPass }; private passes: { [key in keyof typeof RenderingPassName]: RenderingPass };
private autoscaler: FpsAutoscaler; private autoscaler: FpsAutoscaler;
constructor(private canvas: HTMLCanvasElement, descriptors: Array<DrawableDescriptor>) { private static defaultSettings: WebGl2RendererSettings = {
enableHighDpiRendering: true,
enableStopwatch: true,
tileMultiplier: 8,
shaderMacros: {
softShadowTraceCount: '128',
hardShadowTraceCount: '32',
},
};
constructor(
private canvas: HTMLCanvasElement,
descriptors: Array<DrawableDescriptor>,
palette: Array<vec3>,
settingsOverrides: Partial<WebGl2RendererSettings>
) {
const settings = { ...WebGl2Renderer.defaultSettings, ...settingsOverrides };
this.gl = getWebGl2Context(canvas); this.gl = getWebGl2Context(canvas);
this.distanceFieldFrameBuffer = new IntermediateFrameBuffer(this.gl); this.distanceFieldFrameBuffer = new IntermediateFrameBuffer(
this.lightingFrameBuffer = new DefaultFrameBuffer(this.gl); this.gl,
settings.enableHighDpiRendering
);
this.lightingFrameBuffer = new DefaultFrameBuffer(
this.gl,
settings.enableHighDpiRendering
);
this.passes = { this.passes = {
[RenderingPassName.distance]: new RenderingPass( [RenderingPassName.distance]: new RenderingPass(
this.gl, this.gl,
[distanceVertexShader, distanceFragmentShader], [distanceVertexShader, distanceFragmentShader],
descriptors.filter(WebGl2Renderer.hasSdf), descriptors.filter(WebGl2Renderer.hasSdf),
this.distanceFieldFrameBuffer this.distanceFieldFrameBuffer,
settings.shaderMacros,
settings.tileMultiplier
), ),
[RenderingPassName.pixel]: new RenderingPass( [RenderingPassName.pixel]: new RenderingPass(
this.gl, this.gl,
[lightsVertexShader, lightsFragmentShader], [lightsVertexShader, lightsFragmentShader],
descriptors.filter((d) => !WebGl2Renderer.hasSdf(d)), descriptors.filter((d) => !WebGl2Renderer.hasSdf(d)),
this.lightingFrameBuffer this.lightingFrameBuffer,
{
palette: this.generatePaletteCode(palette),
...settings.shaderMacros,
},
settings.tileMultiplier
), ),
}; };
@ -55,12 +87,25 @@ export class WebGl2Renderer implements Renderer {
(this.uniformsProvider.softShadowsEnabled = v as boolean), (this.uniformsProvider.softShadowsEnabled = v as boolean),
}); });
if (settings.enableStopwatch) {
try { try {
this.stopwatch = new WebGlStopwatch(this.gl); this.stopwatch = new WebGlStopwatch(this.gl);
} catch { } catch {
// no problem // no problem
} }
} }
}
public get insights(): any {
return Insights.values;
}
public destroy(): void {
// todo
/*const extension = enableExtension(this.gl, 'WEBGL_lose_context');
extension.loseContext();
extension.restoreContext();*/
}
private static hasSdf(descriptor: DrawableDescriptor) { private static hasSdf(descriptor: DrawableDescriptor) {
return Object.prototype.hasOwnProperty.call(descriptor, 'sdf'); return Object.prototype.hasOwnProperty.call(descriptor, 'sdf');
@ -78,6 +123,18 @@ export class WebGl2Renderer implements Renderer {
this.autoscaler.autoscale(deltaTime); this.autoscaler.autoscale(deltaTime);
} }
private generatePaletteCode(palette: Array<vec3>) {
const numberToGlslFloat = (n) => (Number.isInteger(n) ? `${n}.0` : `${n}`);
return palette
.map(
(c) =>
`vec3(${numberToGlslFloat(c[0])}, ${numberToGlslFloat(
c[1]
)}, ${numberToGlslFloat(c[2])})`
)
.join(',\n');
}
public renderDrawables() { public renderDrawables() {
this.stopwatch?.start(); this.stopwatch?.start();

View file

@ -1,5 +1,4 @@
export const settings = { export const settings = {
enableHighDpiRendering: true,
qualityScaling: { qualityScaling: {
targetDeltaTimeInMilliseconds: 20, targetDeltaTimeInMilliseconds: 20,
deltaTimeError: 2, deltaTimeError: 2,
@ -48,11 +47,4 @@ export const settings = {
multiplicativeDecrease: 1.05, multiplicativeDecrease: 1.05,
}, },
}, },
tileMultiplier: 8,
shaderMacros: {},
shaderCombinations: {
circleLightSteps: [0, 1],
circleSteps: [0, 1, 16],
flashlightSteps: [0, 1],
},
}; };

View file

@ -10,40 +10,22 @@ declare global {
} }
} }
export const applyArrayPlugins = () => { const setIndexAlias = (name: string, index: number, type: any) => {
Object.defineProperty(Array.prototype, 'x', { if (!Object.prototype.hasOwnProperty.call(type.prototype, name)) {
Object.defineProperty(type.prototype, name, {
get() { get() {
return this[0]; return this[index];
}, },
set(value) { set(value) {
this[0] = value; this[index] = value;
},
});
Object.defineProperty(Array.prototype, 'y', {
get() {
return this[1];
},
set(value) {
this[1] = value;
},
});
Object.defineProperty(Float32Array.prototype, 'x', {
get() {
return this[0];
},
set(value) {
this[0] = value;
},
});
Object.defineProperty(Float32Array.prototype, 'y', {
get() {
return this[1];
},
set(value) {
this[1] = value;
}, },
}); });
}
};
export const applyArrayPlugins = () => {
setIndexAlias('x', 0, Array);
setIndexAlias('y', 1, Array);
setIndexAlias('x', 0, Float32Array);
setIndexAlias('y', 1, Float32Array);
}; };

View file

@ -1,3 +1,4 @@
import { Insights } from '../graphics/rendering/insights';
import { clamp } from './clamp'; import { clamp } from './clamp';
import { mix } from './mix'; import { mix } from './mix';
@ -54,6 +55,6 @@ export class Autoscaler {
this.setters[key](current); this.setters[key](current);
} }
//InfoText.modifyRecord('quality', result); Insights.setValue('quality', result);
} }
} }

View file

@ -1,20 +1,24 @@
import { glMatrix } from 'gl-matrix'; import { glMatrix, vec3 } from 'gl-matrix';
import { DrawableDescriptor } from './drawables/drawable-descriptor'; import { DrawableDescriptor } from './drawables/drawable-descriptor';
import { Renderer } from './graphics/rendering/renderer'; import { Renderer } from './graphics/rendering/renderer';
import { WebGl2Renderer } from './graphics/rendering/webgl2-renderer'; import { WebGl2Renderer } from './graphics/rendering/webgl2-renderer';
import { WebGl2RendererSettings } from './graphics/rendering/webgl2-renderer-settings';
import { applyArrayPlugins } from './helper/array'; import { applyArrayPlugins } from './helper/array';
export { Drawable } from './drawables/drawable'; export { Drawable } from './drawables/drawable';
export { CircleLight } from './drawables/lights/circle-light'; export { CircleLight } from './drawables/lights/circle-light';
export { Flashlight } from './drawables/lights/flashlight'; export { Flashlight } from './drawables/lights/flashlight';
export { Circle } from './drawables/shapes/circle'; export { Circle } from './drawables/shapes/circle';
export { Tunnel } from './drawables/shapes/tunnel';
export { RenderingPassName } from './graphics/rendering/rendering-pass-name'; export { RenderingPassName } from './graphics/rendering/rendering-pass-name';
export const compile = ( export const compile = (
canvas: HTMLCanvasElement, canvas: HTMLCanvasElement,
descriptors: Array<DrawableDescriptor> descriptors: Array<DrawableDescriptor>,
palette: Array<vec3>,
settings: Partial<WebGl2RendererSettings> = {}
): Renderer => { ): Renderer => {
glMatrix.setMatrixArrayType(Array); glMatrix.setMatrixArrayType(Array);
applyArrayPlugins(); applyArrayPlugins();
return new WebGl2Renderer(canvas, descriptors); return new WebGl2Renderer(canvas, descriptors, palette, settings);
}; };