feat: 点光源重构

This commit is contained in:
AncTe committed 2024-04-30 12:27:20 +08:00
1 parent 8dba57e222
commit 6417d9218b
15 files changed
+3218 -84

No files matched your search

+6
View File
@@ -82,6 +82,8 @@ export class BgmController
if (!this.disable) {
this.setTransitionAnimate(id, 1, when);
if (this.now) this.setTransitionAnimate(this.now, 0);
} else {
this.playing = false;
}
if (!noStack) {
@@ -134,6 +136,8 @@ export class BgmController
if (!this.disable) {
if (transition) this.setTransitionAnimate(this.now, 1);
else this.get(this.now).play();
} else {
this.playing = false;
}
}
@@ -171,6 +175,8 @@ export class BgmController
this.redoStack = [];
}
this.now = id;
} else {
this.playing = false;
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+298
View File
@@ -0,0 +1,298 @@
import { ensureArray, tip } from '@/plugin/utils';
import { sleep } from 'mutate-animate';
import { logger } from '../common/logger';
const { gl, gl2 } = checkSupport();
function checkSupport() {
const canvas = document.createElement('canvas');
const canvas2 = document.createElement('canvas');
const gl = canvas.getContext('webgl');
const gl2 = canvas2.getContext('webgl2');
if (!gl) {
sleep(3000).then(() => {
tip(
'warning',
`您的浏览器不支持WebGL,大部分特效将会无法显示,建议使用新版浏览器`
);
});
}
if (!gl2) {
sleep(3000).then(() => {
tip(
'warning',
`您的浏览器不支持WebGL2,一部分特效将会无法显示,建议使用新版浏览器`
);
});
}
return { gl: !!gl, gl2: !!gl2 };
}
export function isWebGLSupported() {
return gl;
}
export function isWebGL2Supported() {
return gl2;
}
export type WebGLColorArray = [number, number, number, number];
interface WebGLShaderInfo {
vertex: WebGLShader;
fragment: WebGLShader;
}
type UniformBinderNum = 1 | 2 | 3 | 4;
type UniformBinderType = 'f' | 'i';
type UniformFunc<
N extends UniformBinderNum,
T extends UniformBinderType,
V extends 'v' | ''
> = `uniform${N}${T}${V}`;
type UniformBinderValue<N extends UniformBinderNum> = N extends 1
? number
: N extends 2
? [number, number]
: N extends 3
? [number, number, number]
: [number, number, number, number];
interface UniformBinder<
N extends UniformBinderNum,
T extends UniformBinderType,
V extends 'v' | ''
> {
value: UniformBinderValue<N>;
set(value: UniformBinderValue<N>): void;
get(): UniformBinderValue<N>;
}
abstract class WebGLBase {
abstract canvas: HTMLCanvasElement;
abstract gl: WebGLRenderingContext | WebGL2RenderingContext;
background: WebGLColorArray = [0, 0, 0, 0];
vsSource: string = '';
fsSource: string = '';
program: WebGLProgram | null = null;
shader: WebGLShaderInfo | null = null;
resetCanvas() {
this.gl.clearColor(...this.background);
this.gl.clear(this.gl.COLOR_BUFFER_BIT);
}
setSize(width: number, height: number) {
this.canvas.width = width;
this.canvas.height = height;
}
compile() {
const gl = this.gl;
gl.deleteProgram(this.program);
gl.deleteShader(this.shader?.vertex ?? null);
gl.deleteShader(this.shader?.fragment ?? null);
this.program = this.createProgram();
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.useProgram(this.program);
}
vs(vs: string) {
this.vsSource = vs;
}
fs(fs: string) {
this.fsSource = fs;
}
/**
* 创建一个全局变量绑定器,用于操作全局变量
* @param uniform 全局变量的变量名
* @param num 变量的元素数量,float和int视为1,vec2 vec3 vec4分别视为 2 3 4
* @param type 数据类型,可以填'f',表示浮点型,或者填'i',表示整型
* @param vector 是否为向量,可以填'v',表示是向量,或者填'',表示不是向量
* @returns 一个uniform绑定器,用于操作全局变量uniform
*/
createUniformBinder<
N extends UniformBinderNum,
T extends UniformBinderType,
V extends 'v' | ''
>(uniform: string, num: N, type: T, vector: V): UniformBinder<N, T, V> {
if (!this.program) {
throw new Error(
`Uniform binder should be use when the program initialized.`
);
}
const suffix = `${num}${type}${vector ? 'v' : ''}`;
const func = `uniform${suffix}` as UniformFunc<N, T, V>;
const value = (
num === 1 ? 0 : Array(num).fill(0)
) as UniformBinderValue<N>;
const loc = this.gl.getUniformLocation(this.program, uniform);
const gl = this.gl;
return {
value,
set(value) {
this.value = value;
let v;
if (vector === 'v') {
let _v = ensureArray(value);
if (type === 'f') {
v = new Float32Array(_v);
} else {
v = new Int32Array(_v);
}
} else {
v = ensureArray(value);
}
// 对uniform赋值
if (vector === 'v') {
// @ts-ignore
gl[func](loc, v);
} else {
// @ts-ignore
gl[func](loc, ...v);
}
},
get() {
return this.value;
}
};
}
protected createProgram() {
const gl = this.gl;
const vs = this.loadShader(gl.VERTEX_SHADER, this.vsSource);
const fs = this.loadShader(gl.FRAGMENT_SHADER, this.fsSource);
this.shader = {
vertex: vs,
fragment: fs
};
const program = gl.createProgram()!;
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
logger.error(
9,
`Cannot initialize shader program. Error info: ${gl.getProgramInfoLog(
program
)}`
);
}
return program;
}
protected loadShader(type: number, source: string) {
const gl = this.gl;
const shader = gl.createShader(type)!;
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
throw new Error(
`Cannot compile ${
type === gl.VERTEX_SHADER ? 'vertex' : 'fragment'
} shader. Error info: ${gl.getShaderInfoLog(shader)}`
);
}
return shader;
}
}
export class WebGLCanvas extends WebGLBase {
canvas: HTMLCanvasElement;
gl: WebGLRenderingContext;
constructor(canvas?: HTMLCanvasElement) {
super();
this.canvas = canvas ?? document.createElement('canvas');
this.gl = this.canvas.getContext('webgl')!;
}
}
export class WebGL2Canvas extends WebGLBase {
canvas: HTMLCanvasElement;
gl: WebGL2RenderingContext;
constructor(canvas?: HTMLCanvasElement) {
super();
this.canvas = canvas ?? document.createElement('canvas');
this.gl = this.canvas.getContext('webgl2')!;
}
vs(vs: string): void {
if (!vs.startsWith('#version 300 es')) {
this.vsSource = `#version 300 es\n` + vs;
} else {
this.vsSource = vs;
}
}
fs(fs: string): void {
if (!fs.startsWith('#version 300 es')) {
this.fsSource = `#version 300 es\n` + fs;
} else {
this.vsSource = fs;
}
}
}
export function loadShader(
gl: WebGLRenderingContext,
type: number,
source: string
) {
const shader = gl.createShader(type)!;
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
logger.error(
10,
`Cannot compile ${
type === gl.VERTEX_SHADER ? 'vertex' : 'fragment'
} shader. Error info: ${gl.getShaderInfoLog(shader)}`
);
}
return shader;
}
export function createProgram(
gl: WebGLRenderingContext,
vsSource: string,
fsSource: string
) {
const vs = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fs = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
const program = gl.createProgram()!;
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
logger.error(
9,
`Cannot initialize shader program. Error info: ${gl.getProgramInfoLog(
program
)}`
);
}
return program;
}
+2
View File
@@ -59,6 +59,7 @@ import { MCGenerator } from './main/layout';
import { ResourceController } from './loader/controller';
import { logger } from './common/logger';
import { Danmaku } from './main/custom/danmaku';
import * as Shadow from './fx/shadow';
// ----- 类注册
Mota.register('class', 'AudioPlayer', AudioPlayer);
@@ -131,6 +132,7 @@ Mota.register('module', 'UIComponents', {
Keyboard: KeyboardPanel
});
Mota.register('module', 'MCGenerator', MCGenerator);
Mota.register('module', 'Shadow', Shadow);
main.renderLoaded = true;
Mota.require('var', 'hook').emit('renderLoaded');
+1 -1
View File
@@ -160,7 +160,7 @@ export class Danmaku extends EventEmitter<DanmakuEvent> {
this.posted = false;
this.posting = false;
logger.error(
3,
1,
`Unexpected error when posting danmaku. Error info: ${e}`
);
return Promise.reject();
+1
View File
@@ -53,6 +53,7 @@ export {};
}
core.updateStatusBar(true, true);
}
Mota.require('module', 'Shadow').Shadow.update(true);
console.log(`Floor hot reload: ${data}`);
}
+29 -29
View File
@@ -15,35 +15,35 @@ import { setCanvasFilterByFloorId } from '../fx/gameCanvas';
export function init() {
// 勇士身上的光源
Mota.rewrite(core.control, 'drawHero', 'add', () => {
if (core.getFlag('__heroOpacity__') !== 0) {
getAllLights().forEach(v => {
if (!v.followHero) return;
v._offset ??= { x: v.x, y: v.y };
v.x = core.status.heroCenter.px + v._offset.x;
v.y = core.status.heroCenter.py + v._offset.y;
refreshLight();
});
}
});
// 更新地形数据
Mota.rewrite(core.maps, 'removeBlock', 'add', success => {
if (success && main.replayChecking) updateShadow(true);
return success;
});
Mota.rewrite(core.maps, 'setBlock', 'add', () => {
if (main.replayChecking) updateShadow(true);
});
Mota.rewrite(core.events, 'changingFloor', 'add', (_, floorId) => {
if (!main.replayChecking) {
updateShadow();
setCanvasFilterByFloorId(floorId);
}
});
// 初始化画布信息
Mota.rewrite(core.ui, 'deleteAllCanvas', 'add', () => {
if (main.mode === 'play' && !main.replayChecking) initShadowCanvas();
});
// Mota.rewrite(core.control, 'drawHero', 'add', () => {
// if (core.getFlag('__heroOpacity__') !== 0) {
// getAllLights().forEach(v => {
// if (!v.followHero) return;
// v._offset ??= { x: v.x, y: v.y };
// v.x = core.status.heroCenter.px + v._offset.x;
// v.y = core.status.heroCenter.py + v._offset.y;
// refreshLight();
// });
// }
// });
// // 更新地形数据
// Mota.rewrite(core.maps, 'removeBlock', 'add', success => {
// if (success && main.replayChecking) updateShadow(true);
// return success;
// });
// Mota.rewrite(core.maps, 'setBlock', 'add', () => {
// if (main.replayChecking) updateShadow(true);
// });
// Mota.rewrite(core.events, 'changingFloor', 'add', (_, floorId) => {
// if (!main.replayChecking) {
// updateShadow();
// setCanvasFilterByFloorId(floorId);
// }
// });
// // 初始化画布信息
// Mota.rewrite(core.ui, 'deleteAllCanvas', 'add', () => {
// if (main.mode === 'play' && !main.replayChecking) initShadowCanvas();
// });
}
const shadowInfo: Partial<Record<FloorIds, Light[]>> = {
+2
View File
@@ -131,6 +131,7 @@ function showCursor() {
* 设置光标位置
*/
function setCursor(ele: HTMLSpanElement, i: number) {
if (!ele) return;
const style = getComputedStyle(ele);
cursor.style.top = `${
parseFloat(style.height) * (i + 0.5) -
@@ -297,6 +298,7 @@ async function setButtonAnimate() {
buttons.forEach(
v =>
v &&
(v.style.transition =
'transform 0.3s ease-out, color 0.3s ease-out')
);