-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
247 lines (216 loc) · 9.15 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
const vertexShaderSource = `
attribute vec4 aVertexPosition;
attribute vec2 aTextureCoord;
varying vec2 vTextureCoord;
void main() {
gl_Position = aVertexPosition;
vTextureCoord = aTextureCoord;
}
`;
const fragmentShaderSource = `
precision mediump float;
varying vec2 vTextureCoord;
uniform float uRotation;
uniform float uBlendFalloff;
uniform float uBlendOffset;
uniform float uScale;
uniform vec2 uResolution;
uniform sampler2D uSampler;
const float FULL_ROTATION = 6.28318530718;
const vec2 CELL_CENTER = vec2(0.5, 0.5);
float generateRandomVector(vec2 p) {
p = fract(p * vec2(443.897, 441.423));
p += dot(p, p + 19.19);
return fract(p.x * p.y);
}
vec2 rotateUV(vec2 uv, float angle, vec2 center) {
vec2 delta = uv - center;
float s = sin(angle);
float c = cos(angle);
delta = vec2(delta.x * c - delta.y * s, delta.x * s + delta.y * c);
return delta + center;
}
void main() {
// Scaling adjustment for webpage rendering quirks
vec2 pixelCoord = vTextureCoord * uResolution;
vec2 centeredPixel = pixelCoord - 0.5 * uResolution;
vec2 squareCoord = centeredPixel / min(uResolution.x, uResolution.y);
vec2 uv = squareCoord * uScale * 4.0;
// Directly compute the nearest grid corner and center via rounding.
vec2 nearestCorner = floor(uv + 0.5);
vec2 nearestCenter = floor(uv - CELL_CENTER + 0.5) + CELL_CENTER;
// Generate deterministic random for UV patch rotations
float random1 = generateRandomVector(nearestCorner) + 1.0;
float random2 = generateRandomVector(nearestCenter - CELL_CENTER) + 1.0;
// Calculate distances to corner and center points
float minDistCell = dot(uv - nearestCorner, uv - nearestCorner);
float minDistOffset = dot(uv - nearestCenter, uv - nearestCenter) * uBlendOffset;
// Apply different rotations around corner and center points
vec2 rotatedUV1 = rotateUV(uv, uRotation * FULL_ROTATION * random1, nearestCorner);
vec2 rotatedUV2 = rotateUV(uv, uRotation * FULL_ROTATION * random2, nearestCenter);
// Create smooth blend between corner and center samples
float blendFactor = clamp((minDistOffset - minDistCell) * uBlendFalloff, 0.0, 1.0);
vec4 color1 = texture2D(uSampler,fract(rotatedUV1));
vec4 color2 = texture2D(uSampler, fract(rotatedUV2));
// Final blend between corner and center rotated samples
gl_FragColor = mix(color2, color1, blendFactor);
}
`;
function initShaderProgram(gl, vsSource, fsSource) {
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
console.error('Shader program failed to link: ' + gl.getProgramInfoLog(shaderProgram));
return null;
}
return shaderProgram;
}
function loadShader(gl, type, source) {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.error('Shader failed to compile: ' + gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
return null;
}
return shader;
}
function main() {
const canvas = document.querySelector("#glCanvas");
const gl = canvas.getContext("webgl");
if (!gl) {
alert("Unable to initialize WebGL");
return;
}
// Only update the canvas size when the window is resized.
function resizeCanvasToDisplaySize(canvas) {
const width = canvas.clientWidth * window.devicePixelRatio;
const height = canvas.clientHeight * window.devicePixelRatio;
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
}
}
// Initial resize.
resizeCanvasToDisplaySize(canvas);
// Update canvas size on window resize.
window.addEventListener('resize', () => {
resizeCanvasToDisplaySize(canvas);
drawScene();
});
const shaderProgram = initShaderProgram(gl, vertexShaderSource, fragmentShaderSource);
let useTexture = false;
const programInfo = {
program: shaderProgram,
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
textureCoord: gl.getAttribLocation(shaderProgram, 'aTextureCoord'),
},
uniformLocations: {
rotation: gl.getUniformLocation(shaderProgram, 'uRotation'),
blendFalloff: gl.getUniformLocation(shaderProgram, 'uBlendFalloff'),
blendOffset: gl.getUniformLocation(shaderProgram, 'uBlendOffset'),
scale: gl.getUniformLocation(shaderProgram, 'uScale'),
resolution: gl.getUniformLocation(shaderProgram, 'uResolution'),
sampler: gl.getUniformLocation(shaderProgram, 'uSampler')
},
};
const positions = new Float32Array([
-1.0, 1.0,
1.0, 1.0,
-1.0, -1.0,
1.0, -1.0,
]);
const textureCoordinates = new Float32Array([
0.0, 1.0,
1.0, 1.0,
0.0, 0.0,
1.0, 0.0,
]);
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);
const texCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, textureCoordinates, gl.STATIC_DRAW);
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(
gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0,
gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([0, 0, 255, 255])
);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
function loadImageTexture(imagePath) {
const image = new Image();
image.onload = () => {
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
useTexture = true;
drawScene();
};
image.src = imagePath;
}
// Load default image texture.
loadImageTexture('examples/lava.png');
['rotation', 'blendFalloff', 'blendOffset', 'scale'].forEach(id => {
const element = document.getElementById(id);
const valueDisplay = element.nextElementSibling;
element.addEventListener('input', () => {
valueDisplay.textContent = element.value;
drawScene();
});
});
document.getElementById('imageInput').addEventListener('change', (e) => {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (e) => {
const image = new Image();
image.onload = () => {
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
useTexture = true;
drawScene();
};
image.src = e.target.result;
};
reader.readAsDataURL(file);
}
});
document.querySelectorAll('.example-image').forEach(img => {
img.addEventListener('click', () => {
console.log(img.src);
loadImageTexture(img.src);
});
});
function drawScene() {
// Do not recalculate canvas size on every draw.
gl.viewport(0, 0, canvas.width, canvas.height);
gl.useProgram(programInfo.program);
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.vertexAttribPointer(programInfo.attribLocations.vertexPosition, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);
gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
gl.vertexAttribPointer(programInfo.attribLocations.textureCoord, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(programInfo.attribLocations.textureCoord);
gl.uniform1f(programInfo.uniformLocations.rotation, parseFloat(document.getElementById('rotation').value));
gl.uniform1f(programInfo.uniformLocations.blendFalloff, parseFloat(document.getElementById('blendFalloff').value));
gl.uniform1f(programInfo.uniformLocations.blendOffset, parseFloat(document.getElementById('blendOffset').value));
gl.uniform1f(programInfo.uniformLocations.scale, parseFloat(document.getElementById('scale').value));
gl.uniform2f(programInfo.uniformLocations.resolution, canvas.width, canvas.height);
gl.uniform1i(programInfo.uniformLocations.useTexture, useTexture);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.uniform1i(programInfo.uniformLocations.sampler, 0);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
}
}
window.onload = main;