2024-08-18 21:15:57 +08:00

64 lines
1.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { gl_Colors_template } from "./render-utils";
class ShaderMaker {
/**
*
* @param {'VERTEX_SHADER' | 'FRAGMENT_SHADER'} type
* @param {string} source
*/
constructor(type, source) {
this.type = type;
this.source = source;
}
/**
* @param {WebGL2RenderingContext} gl
* @return {WebGLShader}
*/
make(gl) {
const shader = gl.createShader(gl[this.type]);
gl.shaderSource(shader, this.source);
gl.compileShader(shader);
const ok = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (!ok) {
console.log('创建类型为 ' + type + ' 的着色器失败!');
}
return shader;
}
}
const colorsLength = gl_Colors_template.length << 1;
const vertexShader = new ShaderMaker('VERTEX_SHADER', `#version 300 es
in uvec4 pos;
out vec4 v_color;
uniform vec2 scale;
uniform vec2 offset;
uniform vec4 colors[${colorsLength}];
uniform vec2 shifts[7]; // 基础八位图偏移量为了性能pos 只传入整数,需要的坐标负数由该值提供
uniform vec2 widthShifts[8]; // 用于构造线宽的偏移
void main() {
v_color = colors[pos.z];
vec2 shift = shifts[pos.y];
vec2 widthShift = widthShifts[pos.w];
gl_Position = vec4(
float(pos.x) * scale.x + offset.x + float(widthShift.x) + shift.y,
float(shift.x) * scale.y + offset.y + float(widthShift.y),
1, 1
);
}`);
const fragmentShader = new ShaderMaker('FRAGMENT_SHADER', `#version 300 es
precision mediump float;
in vec4 v_color;
out vec4 outColor;
void main() {
outColor = v_color;
}`);
export {
vertexShader,
fragmentShader
}