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

@ -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';
export interface Renderer {
setViewArea(topLeft: vec2, size: vec2): void;
addDrawable(drawable: Drawable): void;
renderDrawables(): void;
autoscaleQuality(deltaTime: DOMHighResTimeStamp): void;
readonly canvasSize: vec2;
readonly insights: any;
setViewArea(topLeft: vec2, size: 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 { FrameBuffer } from '../graphics-library/frame-buffer/frame-buffer';
import { UniformArrayAutoScalingProgram } from '../graphics-library/program/uniform-array-autoscaling-program';
import { settings } from '../settings';
export class RenderingPass {
private drawables: Array<Drawable> = [];
@ -13,12 +12,15 @@ export class RenderingPass {
gl: WebGL2RenderingContext,
shaderSources: [string, string],
drawableDescriptors: Array<DrawableDescriptor>,
private frame: FrameBuffer
private frame: FrameBuffer,
substitutions: { [name: string]: any },
private tileMultiplier: number
) {
this.program = new UniformArrayAutoScalingProgram(
gl,
shaderSources,
drawableDescriptors
drawableDescriptors,
substitutions
);
}
@ -29,7 +31,7 @@ export class RenderingPass {
public render(commonUniforms: any, inputTexture?: WebGLTexture) {
this.frame.bindAndClear(inputTexture);
const stepsInUV = 1 / settings.tileMultiplier;
const stepsInUV = 1 / this.tileMultiplier;
const worldR =
0.5 *
@ -41,7 +43,7 @@ export class RenderingPass {
for (let x = -1; x < 1; x += 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);

View file

@ -0,0 +1,72 @@
#version 300 es
precision lowp float;
#define SURFACE_OFFSET 0.001
uniform float maxMinDistance;
uniform float distanceNdcPixelSize;
in vec2 position;
{macroDefinitions}
{declarations}
/*
#endif
#if BLOB_COUNT > 0
uniform struct {
vec2 headCenter;
vec2 leftFootCenter;
vec2 rightFootCenter;
float headRadius;
float footRadius;
float k;
}[BLOB_COUNT] blobs;
float smoothMin(float a, float b)
{
const float k = 2.0;
a = pow(a, k);
b = pow(b, k);
return pow((a * b) / (a + b), 1.0 / k);
}
float circleMinDistance(vec2 circleCenter, float radius) {
return distance(position, circleCenter) - radius;
}
void blobMinDistance(inout float minDistance, inout float color) {
for (int i = 0; i < BLOB_COUNT; i++) {
float headDistance = circleMinDistance(blobs[i].headCenter, blobs[i].headRadius);
float leftFootDistance = circleMinDistance(blobs[i].leftFootCenter, blobs[i].footRadius);
float rightFootDistance = circleMinDistance(blobs[i].rightFootCenter, blobs[i].footRadius);
float res = min(
smoothMin(headDistance, leftFootDistance),
smoothMin(headDistance, rightFootDistance)
);
res = min(100.0, headDistance);
res = min(res, leftFootDistance);
res = min(res, rightFootDistance);
//color = mix(2.0, color, step(distanceUvPixelSize + SURFACE_OFFSET, res));
minDistance = min(minDistance, res);
color = mix(2.0, color, step(distanceNdcPixelSize + SURFACE_OFFSET, res));
}
}
#endif
*/
out vec2 fragmentColor;
void main() {
float minDistance = maxMinDistance;
float color = 1.0;
{functionCalls}
// minDistance / 2.0: NDC to UV scale
fragmentColor = vec2(minDistance / 2.0, color);
}

View file

@ -0,0 +1,15 @@
#version 300 es
precision lowp float;
uniform mat3 modelTransform;
uniform vec2 squareToAspectRatio;
in vec4 vertexPosition;
out vec2 position;
void main() {
vec3 vertexPosition2D = vec3(vertexPosition.xy, 1.0) * modelTransform;
gl_Position = vec4(vertexPosition2D.xy, 0.0, 1.0);
position = vertexPosition2D.xy * squareToAspectRatio;
}

View file

@ -0,0 +1,175 @@
#version 300 es
precision lowp float;
#define INFINITY 1000.0
#define LIGHT_DROP_INSIDE_RATIO 0.5
#define AMBIENT_LIGHT vec3(0.25, 0.15, 0.25)
#define SHADOW_HARDNESS 150.0
#define HARD_SHADOW_TRACE_COUNT {hardShadowTraceCount}
#define SOFT_SHADOW_TRACE_COUNT {softShadowTraceCount}
{macroDefinitions}
uniform bool softShadowsEnabled;
uniform vec2 squareToAspectRatioTimes2;
uniform float shadingNdcPixelSize;
uniform sampler2D distanceTexture;
in vec2 position;
in vec2 uvCoordinates;
vec3[3] colors = vec3[](
{palette}
);
float getDistance(in vec2 target, out vec3 color) {
vec4 values = texture(distanceTexture, target);
color = colors[int(values[1])];
return values[0];
}
float getDistance(in vec2 target) {
return texture(distanceTexture, target)[0];
}
float softShadowTransparency(float startingDistance, float lightCenterDistance, vec2 direction) {
float rayLength = startingDistance;
float q = 1.0 / SHADOW_HARDNESS;
for (int j = 0; j < SOFT_SHADOW_TRACE_COUNT; j++) {
float minDistance = getDistance(uvCoordinates + direction * rayLength);
q = min(q, minDistance / rayLength);
rayLength += minDistance / 2.5;
if (rayLength >= lightCenterDistance) {
return q * SHADOW_HARDNESS;
}
}
return 0.0;
}
float hardShadowTransparency(float startingDistance, float lightCenterDistance, vec2 direction) {
float rayLength = startingDistance;
for (int j = 0; j < HARD_SHADOW_TRACE_COUNT; j++) {
rayLength += getDistance(uvCoordinates + direction * rayLength);
}
return step(lightCenterDistance, rayLength);
}
float shadowTransparency(float startingDistance, float lightCenterDistance, vec2 direction) {
return softShadowsEnabled ?
softShadowTransparency(startingDistance, lightCenterDistance, direction) :
hardShadowTransparency(startingDistance, lightCenterDistance, direction);
}
#if CIRCLE_LIGHT_COUNT > 0
uniform struct CircleLight {
vec2 center;
float lightDrop;
vec3 value;
}[CIRCLE_LIGHT_COUNT] circleLights;
in vec2[CIRCLE_LIGHT_COUNT] circleLightDirections;
vec3 colorInPosition(CircleLight light, out float lightCenterDistance) {
lightCenterDistance = distance(light.center, position);
return light.value / pow(
lightCenterDistance / light.lightDrop + 1.0, 2.0
);
}
vec3 colorInPositionInside(CircleLight light) {
float lightCenterDistance = distance(light.center, position);
return light.value / pow(
lightCenterDistance / (light.lightDrop * LIGHT_DROP_INSIDE_RATIO) + 1.0, 2.0
);
}
#endif
#if FLASHLIGHT_COUNT > 0
uniform struct Flashlight {
vec2 center;
vec2 direction;
float lightDrop;
vec3 value;
}[FLASHLIGHT_COUNT] flashlights;
in vec2[FLASHLIGHT_COUNT] flashlightDirections;
float intensityInDirection(vec2 lightDirection, vec2 targetDirection) {
return smoothstep(0.0, 1.0, 10.0 * max(0.0, dot(targetDirection, lightDirection) - 0.9));
}
vec3 colorInPosition(Flashlight light, vec2 positionDirection, out float lightCenterDistance) {
lightCenterDistance = distance(light.center, position);
return intensityInDirection(light.direction, positionDirection) * light.value / pow(
lightCenterDistance / light.lightDrop + 1.0, 2.0
);
}
vec3 colorInPositionInside(Flashlight light, vec2 positionDirection) {
float lightCenterDistance = distance(light.center, position);
return intensityInDirection(light.direction, positionDirection) * light.value / pow(
lightCenterDistance / (light.lightDrop * LIGHT_DROP_INSIDE_RATIO) + 1.0, 2.0
);
}
#endif
out vec4 fragmentColor;
void main() {
vec3 lighting = AMBIENT_LIGHT;
vec3 colorAtPosition;
float startingDistance = getDistance(uvCoordinates, colorAtPosition);
if (startingDistance < 0.0) {
#if CIRCLE_LIGHT_COUNT > 0
for (int i = 0; i < CIRCLE_LIGHT_COUNT; i++) {
lighting += colorInPositionInside(circleLights[i]);
}
#endif
#if FLASHLIGHT_COUNT > 0
for (int i = 0; i < FLASHLIGHT_COUNT; i++) {
lighting += colorInPositionInside(flashlights[i], normalize(flashlightDirections[i]));
}
#endif
} else {
colorAtPosition = vec3(1.0);
#if CIRCLE_LIGHT_COUNT > 0
for (int i = 0; i < CIRCLE_LIGHT_COUNT; i++) {
vec2 direction = normalize(circleLightDirections[i]) / squareToAspectRatioTimes2;
float lightCenterDistance;
vec3 lightColorAtPosition = colorInPosition(circleLights[i], lightCenterDistance);
lighting += lightColorAtPosition * shadowTransparency(startingDistance, lightCenterDistance, direction);
}
#endif
#if FLASHLIGHT_COUNT > 0
for (int i = 0; i < FLASHLIGHT_COUNT; i++) {
vec2 originalDirection = normalize(flashlightDirections[i]);
vec2 direction = originalDirection / squareToAspectRatioTimes2;
float lightCenterDistance;
vec3 lightColorAtPosition = colorInPosition(flashlights[i], originalDirection, lightCenterDistance);
if (length(lightColorAtPosition) < 0.01) {
continue;
}
lighting += lightColorAtPosition * shadowTransparency(startingDistance, lightCenterDistance, direction);
}
#endif
}
fragmentColor = vec4(colorAtPosition * lighting, 1.0);
}

View file

@ -0,0 +1,58 @@
#version 300 es
precision lowp float;
{macroDefinitions}
uniform mat3 modelTransform;
in vec4 vertexPosition;
out vec2 position;
out vec2 uvCoordinates;
uniform vec2 squareToAspectRatio;
#if CIRCLE_LIGHT_COUNT > 0
uniform struct CircleLight {
vec2 center;
float lightDrop;
vec3 value;
}[CIRCLE_LIGHT_COUNT] circleLights;
out vec2[CIRCLE_LIGHT_COUNT] circleLightDirections;
#endif
#if FLASHLIGHT_COUNT > 0
uniform struct Flashlight {
vec2 center;
vec2 direction;
float lightDrop;
vec3 value;
}[FLASHLIGHT_COUNT] flashlights;
out vec2[FLASHLIGHT_COUNT] flashlightDirections;
#endif
void main() {
vec3 vertexPosition2D = vec3(vertexPosition.xy, 1.0) * modelTransform;
gl_Position = vec4(vertexPosition2D.xy, 0.0, 1.0);
position = vertexPosition2D.xy * squareToAspectRatio;
uvCoordinates = (vertexPosition2D * mat3(
0.5, 0.0, 0.5,
0.0, 0.5, 0.5,
0.0, 0.0, 1.0
)).xy;
#if CIRCLE_LIGHT_COUNT > 0
for (int i = 0; i < CIRCLE_LIGHT_COUNT; i++) {
circleLightDirections[i] = circleLights[i].center - position;
}
#endif
#if FLASHLIGHT_COUNT > 0
for (int i = 0; i < FLASHLIGHT_COUNT; i++) {
flashlightDirections[i] = flashlights[i].center - position;
}
#endif
}

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 { DrawableDescriptor } from '../../drawables/drawable-descriptor';
import { DefaultFrameBuffer } from '../graphics-library/frame-buffer/default-frame-buffer';
import { IntermediateFrameBuffer } from '../graphics-library/frame-buffer/intermediate-frame-buffer';
import { getWebGl2Context } from '../graphics-library/helper/get-webgl2-context';
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 { Insights } from './insights';
import { Renderer } from './renderer';
import { RenderingPass } from './rendering-pass';
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 { WebGl2RendererSettings } from './webgl2-renderer-settings';
export class WebGl2Renderer implements Renderer {
private gl: WebGL2RenderingContext;
@ -24,24 +26,54 @@ export class WebGl2Renderer implements Renderer {
private passes: { [key in keyof typeof RenderingPassName]: RenderingPass };
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.distanceFieldFrameBuffer = new IntermediateFrameBuffer(this.gl);
this.lightingFrameBuffer = new DefaultFrameBuffer(this.gl);
this.distanceFieldFrameBuffer = new IntermediateFrameBuffer(
this.gl,
settings.enableHighDpiRendering
);
this.lightingFrameBuffer = new DefaultFrameBuffer(
this.gl,
settings.enableHighDpiRendering
);
this.passes = {
[RenderingPassName.distance]: new RenderingPass(
this.gl,
[distanceVertexShader, distanceFragmentShader],
descriptors.filter(WebGl2Renderer.hasSdf),
this.distanceFieldFrameBuffer
this.distanceFieldFrameBuffer,
settings.shaderMacros,
settings.tileMultiplier
),
[RenderingPassName.pixel]: new RenderingPass(
this.gl,
[lightsVertexShader, lightsFragmentShader],
descriptors.filter((d) => !WebGl2Renderer.hasSdf(d)),
this.lightingFrameBuffer
this.lightingFrameBuffer,
{
palette: this.generatePaletteCode(palette),
...settings.shaderMacros,
},
settings.tileMultiplier
),
};
@ -55,13 +87,26 @@ export class WebGl2Renderer implements Renderer {
(this.uniformsProvider.softShadowsEnabled = v as boolean),
});
try {
this.stopwatch = new WebGlStopwatch(this.gl);
} catch {
// no problem
if (settings.enableStopwatch) {
try {
this.stopwatch = new WebGlStopwatch(this.gl);
} catch {
// 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) {
return Object.prototype.hasOwnProperty.call(descriptor, 'sdf');
}
@ -78,6 +123,18 @@ export class WebGl2Renderer implements Renderer {
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() {
this.stopwatch?.start();