Refactor rendering

This commit is contained in:
schmelczerandras 2020-07-30 13:28:10 +02:00
commit c892ca2d01
37 changed files with 505 additions and 423 deletions

View file

@ -1,5 +1,5 @@
import { Command } from '../command';
import { IRenderer } from '../../drawing/rendering/i-renderer';
import { IRenderer } from '../../drawing/i-renderer';
export class BeforeRenderCommand extends Command {
public constructor(public readonly renderer?: IRenderer) {

View file

@ -1,5 +1,5 @@
import { Command } from '../command';
import { IRenderer } from '../../drawing/rendering/i-renderer';
import { IRenderer } from '../../drawing/i-renderer';
export class RenderCommand extends Command {
public constructor(public readonly renderer?: IRenderer) {

View file

@ -0,0 +1,5 @@
export interface IDrawableDescriptor {
uniformName: string;
countMacroName: string;
shaderCombinationSteps: Array<number>;
}

View file

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

View file

@ -0,0 +1,49 @@
import { ILight } from './i-light';
import { vec2, vec3 } from 'gl-matrix';
import { settings } from '../../settings';
import { IDrawableDescriptor } from '../i-drawable-descriptor';
export class CircleLight implements ILight {
public static descriptor: IDrawableDescriptor = {
uniformName: 'lights',
countMacroName: 'lightCount',
shaderCombinationSteps: settings.shaderCombinations.circleLightSteps,
};
constructor(
public center: vec2,
public radius: number,
public color: vec3,
public lightness: number
) {}
distance(target: vec2): number {
return 0;
}
minimumDistance(target: vec2): number {
return 0;
}
serializeToUniforms(uniforms: any): void {
const listName = CircleLight.descriptor.uniformName;
if (!uniforms.hasOwnProperty(listName)) {
uniforms[listName] = [];
}
uniforms[listName].push({
center: this.center,
radius: this.radius,
value: this.value,
});
}
get value(): vec3 {
return vec3.scale(
vec3.create(),
vec3.normalize(this.color, this.color),
this.lightness
);
}
}

View file

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

View file

@ -0,0 +1,36 @@
import { ILight } from './i-light';
import { vec2, vec3 } from 'gl-matrix';
export class PointLight implements ILight {
public static uniformName = 'lights';
constructor(
public center: vec2,
public color: vec3,
public lightness: number
) {}
distance(target: vec2): number {
throw new Error('Method not implemented.');
}
minimumDistance(target: vec2): number {
throw new Error('Method not implemented.');
}
serializeToUniforms(uniforms: any): void {
const listName = PointLight.uniformName;
if (!uniforms.hasOwnProperty(listName)) {
uniforms[listName] = [];
}
uniforms[listName].push({
center: this.center,
radius: 0,
value: this.value,
});
}
get value(): vec3 {
return vec3.scale(vec3.create(), this.color, this.lightness);
}
}

View file

@ -0,0 +1,27 @@
import { vec2 } from 'gl-matrix';
import { IPrimitive } from './i-primitive';
export class Circle implements IPrimitive {
public constructor(public center = vec2.create(), public radius = 0) {}
public serializeToUniforms(uniforms: any): void {
throw new Error('Method not implemented.');
}
public distance(target: vec2): number {
return vec2.distance(this.center, target) - this.radius;
}
public minimumDistance(target: vec2): number {
return vec2.distance(this.center, target) - this.radius;
}
public isInside(target: vec2): boolean {
return this.distance(target) < 0;
}
public areIntersecting(other: Circle): boolean {
const distance = vec2.distance(this.center, other.center);
return distance < this.radius + other.radius;
}
}

View file

@ -0,0 +1,3 @@
import { IDrawable } from '../i-drawable';
export interface IPrimitive extends IDrawable {}

View file

@ -0,0 +1,18 @@
import { vec2 } from 'gl-matrix';
export class Rectangle {
public constructor(
public topLeft: vec2 = vec2.create(),
public size: vec2 = vec2.create()
) {}
public isInside(position: vec2): boolean {
const translated = vec2.subtract(vec2.create(), position, this.topLeft);
return (
0 <= translated.x &&
translated.x < this.size.x &&
0 <= translated.y &&
translated.y < this.size.y
);
}
}

View file

@ -0,0 +1,67 @@
import { vec2 } from 'gl-matrix';
import { clamp01 } from '../../../helper/clamp';
import { mix } from '../../../helper/mix';
import { Circle } from './circle';
import { IPrimitive } from './i-primitive';
import { IDrawableDescriptor } from '../i-drawable-descriptor';
import { settings } from '../../settings';
export class TunnelShape implements IPrimitive {
public static descriptor: IDrawableDescriptor = {
uniformName: 'lines',
countMacroName: 'lineCount',
shaderCombinationSteps: settings.shaderCombinations.lineSteps,
};
public readonly toFromDelta: vec2;
private toFromDeltaLength: number;
private boundingCircle: Circle;
constructor(
public readonly from: vec2,
public readonly to: vec2,
public readonly fromRadius: number,
public readonly toRadius: number
) {
this.toFromDelta = vec2.subtract(vec2.create(), to, from);
this.toFromDeltaLength = vec2.length(this.toFromDelta);
this.boundingCircle = new Circle(
vec2.fromValues(from.x / 2 + to.x / 2, from.y / 2 + to.y / 2),
Math.max(fromRadius, toRadius) + vec2.distance(from, to)
);
}
serializeToUniforms(uniforms: any): void {
if (!uniforms.hasOwnProperty(TunnelShape.descriptor.uniformName)) {
uniforms[TunnelShape.descriptor.uniformName] = [];
}
uniforms[TunnelShape.descriptor.uniformName].push({
from: this.from,
toFromDelta: this.toFromDelta,
fromRadius: this.fromRadius,
toRadius: this.toRadius,
});
}
public distance(target: vec2): number {
const targetFromDelta = vec2.subtract(vec2.create(), target, this.from);
const h = clamp01(
vec2.dot(targetFromDelta, this.toFromDelta) /
this.toFromDeltaLength /
this.toFromDeltaLength
);
return (
vec2.distance(
targetFromDelta,
vec2.scale(vec2.create(), this.toFromDelta, h)
) - mix(this.fromRadius, this.toRadius, h)
);
}
public minimumDistance(target: vec2): number {
return this.boundingCircle.distance(target);
}
}

View file

@ -1,15 +1,16 @@
import { settings } from '../../settings';
export const createShader = (
gl: WebGL2RenderingContext,
type: GLenum,
source: string,
substitutions: { [name: string]: string }
): WebGLShader => {
const allSubstitutions = { ...settings.shaderMacros, ...substitutions };
source = source.replace(/{(.+)}/gm, (_, name: string): string => {
const value = substitutions[name];
if (Number.isInteger(value)) {
return `${value}.0`;
}
return value;
const value = allSubstitutions[name];
return Number.isInteger(value) ? `${value}.0` : value;
});
const shader = gl.createShader(type);

View file

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

View file

@ -5,11 +5,10 @@ export class FragmentShaderOnlyProgram extends Program {
constructor(
gl: WebGL2RenderingContext,
vertexShaderSource: string,
fragmentShaderSource: string,
shaderSources: [string, string],
substitutions: { [name: string]: string }
) {
super(gl, vertexShaderSource, fragmentShaderSource, substitutions);
super(gl, shaderSources, substitutions);
this.prepareScreenQuad('vertexPosition');
}

View file

@ -1,8 +1,8 @@
import { vec2 } from 'gl-matrix';
export interface IProgram {
bindAndSetUniforms(values: { [name: string]: any }): void;
setDrawingRectangle(topLeft: vec2, size: vec2): void;
bindAndSetUniforms(values: { [name: string]: any }): void;
draw(): void;
delete(): void;
}

View file

@ -17,8 +17,7 @@ export abstract class Program implements IProgram {
constructor(
protected gl: WebGL2RenderingContext,
vertexShaderSource: string,
fragmentShaderSource: string,
[vertexShaderSource, fragmentShaderSource]: [string, string],
substitutions: { [name: string]: string }
) {
this.createProgram(vertexShaderSource, fragmentShaderSource, substitutions);

View file

@ -1,11 +1,14 @@
import { vec2 } from 'gl-matrix';
import { FragmentShaderOnlyProgram } from './fragment-shader-only-program';
import { IProgram } from './i-program';
import { last } from '../../../helper/last';
import { getCombinations } from '../../../helper/get-combinations';
import { IDrawableDescriptor } from '../../drawables/i-drawable-descriptor';
export class UniformArrayAutoScalingProgram implements IProgram {
private programs: Array<{
program: FragmentShaderOnlyProgram;
value: number;
values: Array<number>;
}> = [];
private current: FragmentShaderOnlyProgram;
@ -14,45 +17,33 @@ export class UniformArrayAutoScalingProgram implements IProgram {
constructor(
private gl: WebGL2RenderingContext,
private vertexShaderSource: string,
private fragmentShaderSource: string,
private substitutions: { [name: string]: any },
private options: {
getValueFromUniforms: (values: { [name: string]: any }) => number;
uniformArraySizeName: string;
enablingMacro: string;
startingValue: number;
steps: number;
maximumValue: number;
}
shaderSources: [string, string],
private options: Array<IDrawableDescriptor>
) {
for (
let i = options.startingValue;
i < options.maximumValue;
i += options.steps
) {
this.createProgram(i);
const names = options.map((o) => o.countMacroName);
for (let combination of getCombinations(
options.map((o) => o.shaderCombinationSteps)
)) {
this.createProgram(names, combination, shaderSources);
}
}
public bindAndSetUniforms(values: { [name: string]: any }): void {
let value = this.options.getValueFromUniforms(values);
value = Math.min(this.options.maximumValue, value);
const closest = this.programs.find(
(p) => value < p.value && value + this.options.steps >= p.value
public bindAndSetUniforms(uniforms: { [name: string]: any }): void {
let values = this.options.map((o) =>
uniforms[o.uniformName] ? uniforms[o.uniformName].length : 0
);
if (closest) {
this.current = closest.program;
} else {
this.current = this.createProgram(value + this.options.steps);
}
const closest = this.programs.find((p) =>
p.values.every((v, i) => v > values[i])
);
this.current = closest ? closest.program : last(this.programs).program;
this.current.setDrawingRectangle(
this.drawingRectangleTopLeft,
this.drawingRectangleSize
);
this.current.bindAndSetUniforms(values);
this.current.bindAndSetUniforms(uniforms);
}
public setDrawingRectangle(topLeft: vec2, size: vec2) {
@ -68,21 +59,23 @@ export class UniformArrayAutoScalingProgram implements IProgram {
this.programs.forEach((p) => p.program.delete());
}
private createProgram(arraySize: number): FragmentShaderOnlyProgram {
private createProgram(
names: Array<string>,
combination: Array<number>,
shaderSources: [string, string]
): FragmentShaderOnlyProgram {
const substitutions = {};
names.forEach((v, i) => (substitutions[v] = combination[i].toString()));
const program = new FragmentShaderOnlyProgram(
this.gl,
this.vertexShaderSource,
this.fragmentShaderSource,
{
[this.options.uniformArraySizeName]: Math.floor(arraySize).toString(),
[this.options.enablingMacro]: arraySize > 0 ? '1' : '0',
...this.substitutions,
}
shaderSources,
substitutions
);
this.programs.push({
program,
value: arraySize,
values: combination,
});
return program;

View file

@ -0,0 +1,16 @@
import { vec2 } from 'gl-matrix';
import { IPrimitive } from './drawables/primitives/i-primitive';
import { ILight } from './drawables/lights/i-light';
export interface IRenderer {
startFrame(deltaTime: DOMHighResTimeStamp): void;
finishFrame(): void;
drawPrimitive(primitive: IPrimitive): void;
drawLight(light: ILight): void;
drawInfoText(text: string): void;
setCameraPosition(position: vec2): void;
setCursorPosition(position: vec2): void;
setInViewArea(size: number): vec2;
}

View file

@ -1,3 +0,0 @@
export interface ILight {
serializeToUniforms(uniforms: any): void;
}

View file

@ -0,0 +1,54 @@
import { Autoscaler } from '../../helper/autoscaler';
import { settings } from '../settings';
import { exponentialDecay } from '../../helper/exponential-decay';
import { InfoText } from '../../objects/types/info-text';
import { FrameBuffer } from '../graphics-library/frame-buffer/frame-buffer';
import { toPercent } from '../../helper/to-percent';
export class FpsAutoscaler extends Autoscaler {
private timeSinceLastAdjusment = 0;
private exponentialDecayedDeltaTime = 0.0;
constructor(private frameBuffers: Array<FrameBuffer>) {
super(
frameBuffers.map((f) => (v) => (f.renderScale = v)),
settings.qualityScaling.scaleTargets,
settings.qualityScaling.startingTargetIndex,
settings.qualityScaling.scalingOptions
);
}
public autoscale(lastDeltaTime: DOMHighResTimeStamp) {
this.timeSinceLastAdjusment += lastDeltaTime;
if (
this.timeSinceLastAdjusment >=
settings.qualityScaling.adjusmentRateInMilliseconds
) {
this.timeSinceLastAdjusment = 0;
this.exponentialDecayedDeltaTime = exponentialDecay(
this.exponentialDecayedDeltaTime,
lastDeltaTime,
settings.qualityScaling.deltaTimeResponsiveness
);
if (
this.exponentialDecayedDeltaTime <=
settings.qualityScaling.targetDeltaTimeInMilliseconds -
settings.qualityScaling.deltaTimeError
) {
this.increase();
} else if (
this.exponentialDecayedDeltaTime >
settings.qualityScaling.targetDeltaTimeInMilliseconds +
settings.qualityScaling.deltaTimeError
) {
this.decrease();
}
}
InfoText.modifyRecord(
'quality',
this.frameBuffers.map((f) => toPercent(f.renderScale)).join(', ')
);
}
}

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