-
-
Notifications
You must be signed in to change notification settings - Fork 36.6k
Expand file tree
/
Copy pathwebgl_postprocessing_pixel.html
More file actions
420 lines (310 loc) · 15.3 KB
/
Copy pathwebgl_postprocessing_pixel.html
File metadata and controls
420 lines (310 loc) · 15.3 KB
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - post processing - pixelation</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<meta property="og:title" content="three.js webgl - post processing - pixelation">
<meta property="og:type" content="website">
<meta property="og:url" content="https://threejs.org/examples/webgl_postprocessing_pixel.html">
<meta property="og:image" content="https://threejs.org/examples/screenshots/webgl_postprocessing_pixel.jpg">
<link type="text/css" rel="stylesheet" href="main.css">
</head>
<body>
<div id="info">
<a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - Pixelation pass with optional single pixel outlines by
<a href="https://github.com/KodyJKing" target="_blank" rel="noopener">Kody King</a><br /><br />
</div>
<div id="container"></div>
<script type="importmap">
{
"imports": {
"three": "../build/three.module.js",
"three/addons/": "./jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPixelatedPass } from 'three/addons/postprocessing/RenderPixelatedPass.js';
import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
let camera, scene, renderer, composer, controls, crystalMesh, timer;
let gui, params;
init();
function init() {
const aspectRatio = window.innerWidth / window.innerHeight;
camera = new THREE.OrthographicCamera( - aspectRatio, aspectRatio, 1, - 1, 0.1, 10 );
camera.position.y = 2 * Math.tan( Math.PI / 6 );
camera.position.z = 2;
scene = new THREE.Scene();
scene.background = new THREE.Color( 0x151729 );
timer = new THREE.Timer();
timer.connect( document );
renderer = new THREE.WebGLRenderer();
renderer.shadowMap.enabled = true;
//renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setAnimationLoop( animate );
document.body.appendChild( renderer.domElement );
composer = new EffectComposer( renderer );
const renderPixelatedPass = new RenderPixelatedPass( 6, scene, camera );
composer.addPass( renderPixelatedPass );
const outputPass = new OutputPass();
composer.addPass( outputPass );
window.addEventListener( 'resize', onWindowResize );
controls = new OrbitControls( camera, renderer.domElement );
controls.maxZoom = 2;
// gui
gui = new GUI();
params = { pixelSize: 6, normalEdgeStrength: .3, depthEdgeStrength: .4, snapping: true, pixelAlignedPanning: true, pixelAlignedObjects: true, rotationSnap: 15, cameraRotationSnap: 9, cameraZoomSnap: 0.1 };
gui.add( params, 'pixelSize' ).min( 1 ).max( 16 ).step( 1 )
.onChange( () => {
renderPixelatedPass.setPixelSize( params.pixelSize );
} );
gui.add( renderPixelatedPass, 'normalEdgeStrength' ).min( 0 ).max( 2 ).step( .05 );
gui.add( renderPixelatedPass, 'depthEdgeStrength' ).min( 0 ).max( 1 ).step( .05 );
const snappingControl = gui.add( params, 'snapping' ).name( 'Enable Pixel Snapping' );
const snappingFolder = gui.addFolder( 'Snapping' ).close();
snappingControl.onChange( enabled => snappingFolder.controllers.forEach( c => c.enable( enabled ) ) );
snappingFolder.add( params, 'pixelAlignedPanning' );
snappingFolder.add( params, 'pixelAlignedObjects' );
snappingFolder.add( params, 'rotationSnap' ).min( 0 ).max( 90 ).step( 1 ).name( 'rotationSnap (deg, 0 = off)' );
snappingFolder.add( params, 'cameraRotationSnap' ).min( 0 ).max( 90 ).step( 1 ).name( 'cameraRotationSnap (deg, 0 = off)' );
snappingFolder.add( params, 'cameraZoomSnap' ).min( 0 ).max( 1 ).step( .05 ).name( 'cameraZoomSnap (0 = off)' );
// textures
const loader = new THREE.TextureLoader();
const texChecker = pixelTexture( loader.load( 'textures/checker.png' ) );
const texChecker2 = pixelTexture( loader.load( 'textures/checker.png' ) );
texChecker.repeat.set( 3, 3 );
texChecker2.repeat.set( 1.5, 1.5 );
// meshes
const boxMaterial = new THREE.MeshPhongMaterial( { map: texChecker2 } );
function addBox( boxSideLength, x, z, rotation ) {
const mesh = new THREE.Mesh( new THREE.BoxGeometry( boxSideLength, boxSideLength, boxSideLength ), boxMaterial );
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.rotation.y = rotation;
mesh.position.y = boxSideLength / 2;
mesh.position.set( x, boxSideLength / 2 + .0001, z );
scene.add( mesh );
return mesh;
}
addBox( .4, 0, 0, Math.PI / 4 );
addBox( .5, - .5, - .5, Math.PI / 4 );
const planeSideLength = 2;
const planeMesh = new THREE.Mesh(
new THREE.PlaneGeometry( planeSideLength, planeSideLength ),
new THREE.MeshPhongMaterial( { map: texChecker } )
);
planeMesh.receiveShadow = true;
planeMesh.rotation.x = - Math.PI / 2;
scene.add( planeMesh );
const radius = .2;
const geometry = new THREE.IcosahedronGeometry( radius );
crystalMesh = new THREE.Mesh(
geometry,
new THREE.MeshPhongMaterial( {
color: 0x68b7e9,
emissive: 0x4f7e8b,
shininess: 10,
specular: 0xffffff
} )
);
crystalMesh.receiveShadow = true;
crystalMesh.castShadow = true;
scene.add( crystalMesh );
// lights
scene.add( new THREE.AmbientLight( 0x757f8e, 3 ) );
const directionalLight = new THREE.DirectionalLight( 0xfffecd, 1.5 );
directionalLight.position.set( 100, 100, 100 );
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.set( 2048, 2048 );
scene.add( directionalLight );
const spotLight = new THREE.SpotLight( 0xffc100, 10, 10, Math.PI / 16, .02, 2 );
spotLight.position.set( 2, 2, 0 );
const target = spotLight.target;
scene.add( target );
target.position.set( 0, 0, 0 );
spotLight.castShadow = true;
scene.add( spotLight );
}
function onWindowResize() {
const aspectRatio = window.innerWidth / window.innerHeight;
camera.left = - aspectRatio;
camera.right = aspectRatio;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
composer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
timer.update();
const t = timer.getElapsed();
// Quantize the pulsing glow to a few discrete brightness levels to match the pixelated aesthetic
const brightnessLevels = 6;
crystalMesh.material.emissiveIntensity =
Math.round( ( Math.sin( t * 3 ) * .5 + .5 ) * ( brightnessLevels - 1 ) ) / ( brightnessLevels - 1 );
crystalMesh.position.y = .7 + Math.sin( t * 2 ) * .05;
crystalMesh.rotation.y = stopGoEased( t, 6, 8 ) * 2 * Math.PI;
const rendererSize = renderer.getSize( new THREE.Vector2() );
const aspectRatio = rendererSize.x / rendererSize.y;
const pixelsPerScreenWidth = Math.floor( rendererSize.x / params[ 'pixelSize' ] );
const pixelsPerScreenHeight = Math.floor( rendererSize.y / params[ 'pixelSize' ] );
// The top-level 'snapping' checkbox gates every individual snapping effect at once
const snapping = params[ 'snapping' ];
// Remember the camera's true (unsnapped) transform so OrbitControls interaction is unaffected by snapping
const cameraPosition = camera.position.clone();
const cameraQuaternion = camera.quaternion.clone();
const cameraZoom = camera.zoom;
// Snap the camera's rotation and scale first, so the translation snap below derives its pixel grid
// and screen-space basis from the already-snapped orientation and zoom
if ( snapping && ( params[ 'cameraRotationSnap' ] > 0 || params[ 'cameraZoomSnap' ] > 0 ) ) {
pixelAlignCamera( camera, controls.target, params[ 'cameraRotationSnap' ], params[ 'cameraZoomSnap' ] );
}
if ( snapping && params[ 'pixelAlignedPanning' ] ) {
pixelAlignFrustum( camera, aspectRatio, pixelsPerScreenWidth, pixelsPerScreenHeight );
} else if ( camera.left != - aspectRatio || camera.top != 1.0 ) {
// Reset the Camera Frustum if it has been modified
camera.left = - aspectRatio;
camera.right = aspectRatio;
camera.top = 1.0;
camera.bottom = - 1.0;
camera.updateProjectionMatrix();
}
// Remember the crystal's true (unsnapped) transform so its bulk movement is unaffected by snapping.
// We snapshot the euler rotation (not the quaternion) because that's what drives the spin: restoring
// the quaternion would let three.js re-derive a gimbal-equivalent euler and corrupt the y rotation.
const crystalPosition = crystalMesh.position.clone();
const crystalRotation = crystalMesh.rotation.clone();
if ( snapping && params[ 'pixelAlignedObjects' ] ) {
// Snap the moving objects to the screen-space pixel grid so they don't shimmer when pixelated
const worldScreenWidth = ( ( camera.right - camera.left ) / camera.zoom );
const worldScreenHeight = ( ( camera.top - camera.bottom ) / camera.zoom );
pixelAlignObject( crystalMesh, camera, worldScreenWidth / pixelsPerScreenWidth,
worldScreenHeight / pixelsPerScreenHeight );
}
if ( snapping && params[ 'rotationSnap' ] > 0 ) {
// Snap the moving objects' rotation to the nearest camera-relative euler increment
snapObjectRotation( crystalMesh, camera, params[ 'rotationSnap' ] );
}
composer.render();
// Restore the true transforms after rendering so the next frame's motion builds on the real trajectory
crystalMesh.position.copy( crystalPosition );
crystalMesh.rotation.copy( crystalRotation );
camera.position.copy( cameraPosition );
camera.quaternion.copy( cameraQuaternion );
camera.zoom = cameraZoom;
camera.updateProjectionMatrix();
}
// Helper functions
function pixelTexture( texture ) {
texture.minFilter = THREE.NearestFilter;
texture.magFilter = THREE.NearestFilter;
texture.generateMipmaps = false;
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
function easeInOutCubic( x ) {
return x ** 2 * 3 - x ** 3 * 2;
}
function linearStep( x, edge0, edge1 ) {
const w = edge1 - edge0;
const m = 1 / w;
const y0 = - m * edge0;
return THREE.MathUtils.clamp( y0 + m * x, 0, 1 );
}
function stopGoEased( x, downtime, period ) {
const cycle = ( x / period ) | 0;
const tween = x - cycle * period;
const linStep = easeInOutCubic( linearStep( tween, downtime, period ) );
return cycle + linStep;
}
function pixelAlignCamera( camera, target, rotationIncrementDegrees, zoomIncrement ) {
// Snap the camera's orbit to the nearest increment of azimuth/polar angle around the target. Working
// in spherical coordinates (rather than snapping the euler angles) keeps the orbit translation locked
// onto the target and guarantees a roll-free orientation, since we re-aim with lookAt and world up.
if ( rotationIncrementDegrees > 0 ) {
const increment = THREE.MathUtils.degToRad( rotationIncrementDegrees );
const offset = new THREE.Vector3().subVectors( camera.position, target );
const spherical = new THREE.Spherical().setFromVector3( offset );
spherical.theta = Math.round( spherical.theta / increment ) * increment;
spherical.phi = Math.round( spherical.phi / increment ) * increment;
spherical.makeSafe();
offset.setFromSpherical( spherical );
camera.position.copy( target ).add( offset );
camera.up.set( 0.0, 1.0, 0.0 );
camera.lookAt( target );
}
// Snap the camera's zoom to the nearest increment so the pixel grid stays a stable size while scaling
if ( zoomIncrement > 0 ) {
camera.zoom = Math.max( zoomIncrement, Math.round( camera.zoom / zoomIncrement ) * zoomIncrement );
camera.updateProjectionMatrix();
}
}
function pixelAlignFrustum( camera, aspectRatio, pixelsPerScreenWidth, pixelsPerScreenHeight ) {
// 0. Get Pixel Grid Units
const worldScreenWidth = ( ( camera.right - camera.left ) / camera.zoom );
const worldScreenHeight = ( ( camera.top - camera.bottom ) / camera.zoom );
const pixelWidth = worldScreenWidth / pixelsPerScreenWidth;
const pixelHeight = worldScreenHeight / pixelsPerScreenHeight;
// 1. Project the current camera position along its local rotation bases
const camPos = new THREE.Vector3(); camera.getWorldPosition( camPos );
const camRot = new THREE.Quaternion(); camera.getWorldQuaternion( camRot );
const camRight = new THREE.Vector3( 1.0, 0.0, 0.0 ).applyQuaternion( camRot );
const camUp = new THREE.Vector3( 0.0, 1.0, 0.0 ).applyQuaternion( camRot );
const camPosRight = camPos.dot( camRight );
const camPosUp = camPos.dot( camUp );
// 2. Find how far along its position is along these bases in pixel units
const camPosRightPx = camPosRight / pixelWidth;
const camPosUpPx = camPosUp / pixelHeight;
// 3. Find the fractional pixel units and convert to world units
const fractX = camPosRightPx - Math.round( camPosRightPx );
const fractY = camPosUpPx - Math.round( camPosUpPx );
// 4. Add fractional world units to the left/right top/bottom to align with the pixel grid
camera.left = - aspectRatio - ( fractX * pixelWidth );
camera.right = aspectRatio - ( fractX * pixelWidth );
camera.top = 1.0 - ( fractY * pixelHeight );
camera.bottom = - 1.0 - ( fractY * pixelHeight );
camera.updateProjectionMatrix();
}
function pixelAlignObject( object, camera, pixelWidth, pixelHeight ) {
// 1. Build the camera's orthonormal screen-space basis
const camRot = new THREE.Quaternion(); camera.getWorldQuaternion( camRot );
const camRight = new THREE.Vector3( 1.0, 0.0, 0.0 ).applyQuaternion( camRot );
const camUp = new THREE.Vector3( 0.0, 1.0, 0.0 ).applyQuaternion( camRot );
const camForward = new THREE.Vector3( 0.0, 0.0, - 1.0 ).applyQuaternion( camRot );
// 2. Decompose the object's world position onto that basis
const pos = object.position;
const posRight = pos.dot( camRight );
const posUp = pos.dot( camUp );
const posForward = pos.dot( camForward );
// 3. Snap the screen-space (right/up) components to the pixel grid, leaving depth untouched
const snappedRight = Math.round( posRight / pixelWidth ) * pixelWidth;
const snappedUp = Math.round( posUp / pixelHeight ) * pixelHeight;
// 4. Recompose the world position from the snapped basis components
pos.set( 0, 0, 0 );
pos.addScaledVector( camRight, snappedRight );
pos.addScaledVector( camUp, snappedUp );
pos.addScaledVector( camForward, posForward );
}
function snapObjectRotation( object, camera, incrementDegrees ) {
const increment = THREE.MathUtils.degToRad( incrementDegrees );
// 1. Express the object's rotation relative to the camera
const camRot = new THREE.Quaternion(); camera.getWorldQuaternion( camRot );
const relative = camRot.clone().invert().multiply( object.quaternion );
// 2. Snap each euler axis (in camera space) to the nearest increment
const euler = new THREE.Euler().setFromQuaternion( relative );
euler.x = Math.round( euler.x / increment ) * increment;
euler.y = Math.round( euler.y / increment ) * increment;
euler.z = Math.round( euler.z / increment ) * increment;
// 3. Convert back to a world-space rotation
relative.setFromEuler( euler );
object.quaternion.copy( camRot.multiply( relative ) );
}
</script>
</body>
</html>