1
0

webgpu_postprocessing_retro.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - retro</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="example.css">
  8. </head>
  9. <body>
  10. <div id="info">
  11. <a href="https://threejs.org/" target="_blank" rel="noopener" class="logo-link"></a>
  12. <div class="title-wrapper">
  13. <a href="https://threejs.org/" target="_blank" rel="noopener">three.js</a><span>Retro</span>
  14. </div>
  15. <small>
  16. Retro post-processing effects, with scene based on <a href="https://threejs-journey.com/lessons/coffee-smoke-shader" target="_blank" rel="noopener">Three.js Journey</a> lesson.<br />
  17. Perlin noise texture from <a href="http://kitfox.com/projects/perlinNoiseMaker/" target="_blank" rel="noopener">Perlin Noise Maker</a>.
  18. </small>
  19. </div>
  20. <script type="importmap">
  21. {
  22. "imports": {
  23. "three": "../build/three.webgpu.js",
  24. "three/webgpu": "../build/three.webgpu.js",
  25. "three/tsl": "../build/three.tsl.js",
  26. "three/addons/": "./jsm/"
  27. }
  28. }
  29. </script>
  30. <script type="module">
  31. import * as THREE from 'three/webgpu';
  32. import { pass, mix, mul, oneMinus, positionLocal, smoothstep, texture, time, rotateUV, Fn, uv, vec2, vec3, vec4, uniform, posterize, floor, float, sin, fract, dot, step, color, normalWorld, length, atan, replaceDefaultUV, screenSize } from 'three/tsl';
  33. import { retroPass } from 'three/addons/tsl/display/RetroPassNode.js';
  34. import { bayerDither } from 'three/addons/tsl/math/Bayer.js';
  35. import { scanlines, vignette, colorBleeding, barrelUV } from 'three/addons/tsl/display/CRT.js';
  36. import { circle } from 'three/addons/tsl/display/Shape.js';
  37. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  38. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  39. import { HDRLoader } from 'three/addons/loaders/HDRLoader.js';
  40. import { Inspector } from 'three/addons/inspector/Inspector.js';
  41. let camera, scene, renderer, renderPipeline, controls;
  42. let environment;
  43. let currentModel;
  44. init();
  45. async function init() {
  46. camera = new THREE.PerspectiveCamera( 25, window.innerWidth / window.innerHeight, 0.1, 100 );
  47. camera.position.set( 8, 5, 20 );
  48. scene = new THREE.Scene();
  49. // PS1-style background: gradient sky with simple stars
  50. const ps1Background = Fn( () => {
  51. // Flip Y coordinate for correct orientation
  52. const flippedY = normalWorld.y.negate();
  53. const skyUV = flippedY.mul( 0.5 ).add( 0.5 );
  54. // Simple gradient sky (dark blue at top to purple/orange at horizon)
  55. const topColor = color( 0x000033 ); // dark blue night sky
  56. const midColor = color( 0x330066 ); // purple
  57. const horizonColor = color( 0x663322 ); // warm orange/brown horizon
  58. // Two-step gradient (inverted - top is dark, horizon is warm)
  59. const skyGradient = mix(
  60. horizonColor,
  61. mix( midColor, topColor, skyUV.smoothstep( 0.4, 0.9 ) ),
  62. skyUV.smoothstep( 0.0, 0.4 )
  63. );
  64. // PS1-style "stars" using spherical coordinates
  65. const longitude = atan( normalWorld.x, normalWorld.z );
  66. const latitude = flippedY.asin(); // Use flipped Y for latitude too
  67. // More stars with smaller scale
  68. const starScale = float( 50.0 );
  69. const starUV = vec2( longitude.mul( starScale ), latitude.mul( starScale ) );
  70. const starCell = floor( starUV );
  71. // Hash for randomness
  72. const cellHash = fract( sin( dot( starCell, vec2( 12.9898, 78.233 ) ) ).mul( 43758.5453 ) );
  73. // Position within cell (0-1)
  74. const cellUV = fract( starUV );
  75. const toCenter = cellUV.sub( 0.5 );
  76. // Gemini-style star: bright center with soft glow + cross flare
  77. const distToCenter = length( toCenter );
  78. // Core (small bright center)
  79. const core = smoothstep( float( 0.08 ), float( 0.0 ), distToCenter );
  80. // Soft glow around
  81. const glow = smoothstep( float( 0.25 ), float( 0.0 ), distToCenter ).mul( 0.4 );
  82. // Cross/diamond flare effect
  83. const crossX = smoothstep( float( 0.15 ), float( 0.0 ), toCenter.x.abs() ).mul( smoothstep( float( 0.4 ), float( 0.0 ), toCenter.y.abs() ) );
  84. const crossY = smoothstep( float( 0.15 ), float( 0.0 ), toCenter.y.abs() ).mul( smoothstep( float( 0.4 ), float( 0.0 ), toCenter.x.abs() ) );
  85. const cross = crossX.add( crossY ).mul( 0.3 );
  86. // Combine star shape
  87. const starShape = core.add( glow ).add( cross );
  88. // More stars (lower threshold = more stars)
  89. const isStar = step( 0.85, cellHash );
  90. // Show stars from horizon up
  91. const aboveHorizon = smoothstep( float( - 0.2 ), float( 0.1 ), flippedY );
  92. // Star brightness varies + twinkle color
  93. const starIntensity = isStar.mul( aboveHorizon ).mul( starShape ).mul( cellHash.mul( 0.6 ).add( 0.4 ) );
  94. // Slight color variation (white to light blue)
  95. const starColor = mix( vec3( 1.0, 1.0, 0.95 ), vec3( 0.8, 0.9, 1.0 ), cellHash );
  96. // Combine sky and stars
  97. const finalColor = mix( skyGradient, starColor, starIntensity.clamp( 0.0, 1.0 ) );
  98. return finalColor;
  99. } )();
  100. scene.backgroundNode = ps1Background;
  101. // Loaders
  102. const gltfLoader = new GLTFLoader();
  103. const textureLoader = new THREE.TextureLoader();
  104. // Model
  105. const models = {
  106. 'Coffee Mug': 'models/gltf/coffeeMug.glb',
  107. 'Damaged Helmet': 'models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf',
  108. };
  109. function loadModel( name ) {
  110. function loadEnvironment() {
  111. if ( environment ) return;
  112. environment = new HDRLoader()
  113. .setPath( 'textures/equirectangular/' )
  114. .load( 'venice_sunset_1k.hdr', ( texture ) => {
  115. texture.mapping = THREE.EquirectangularReflectionMapping;
  116. scene.environment = texture;
  117. // re-invalidate retro pass textures
  118. retro.dispose();
  119. } );
  120. }
  121. if ( currentModel ) {
  122. scene.remove( currentModel );
  123. currentModel.traverse( ( child ) => {
  124. if ( child.isMesh ) {
  125. child.geometry.dispose();
  126. child.material.dispose();
  127. }
  128. } );
  129. }
  130. gltfLoader.load( models[ name ], ( gltf ) => {
  131. currentModel = gltf.scene;
  132. currentModel.position.set( 0, 0, 0 );
  133. smoke.visible = false;
  134. if ( name === 'Damaged Helmet' ) {
  135. loadEnvironment();
  136. currentModel.scale.setScalar( 3 );
  137. currentModel.position.y = 1;
  138. } else if ( name === 'Coffee Mug' ) {
  139. smoke.visible = true;
  140. }
  141. scene.add( currentModel );
  142. } );
  143. }
  144. loadModel( 'Coffee Mug' );
  145. // lighting
  146. const ambientLight = new THREE.AmbientLight( 0x404040, 2 );
  147. scene.add( ambientLight );
  148. const directionalLight = new THREE.DirectionalLight( 0xffffff, 3 );
  149. directionalLight.position.set( 5, 10, 5 );
  150. scene.add( directionalLight );
  151. const pointLight = new THREE.PointLight( 0xff6600, 5, 20 );
  152. pointLight.position.set( - 3, 3, 2 );
  153. scene.add( pointLight );
  154. // geometry
  155. const smokeGeometry = new THREE.PlaneGeometry( 1, 1, 16, 64 );
  156. smokeGeometry.translate( 0, 0.5, 0 );
  157. smokeGeometry.scale( 1.5, 6, 1.5 );
  158. // texture
  159. const noiseTexture = textureLoader.load( './textures/noises/perlin/128x128.png' );
  160. noiseTexture.wrapS = THREE.RepeatWrapping;
  161. noiseTexture.wrapT = THREE.RepeatWrapping;
  162. // material
  163. const smokeMaterial = new THREE.MeshBasicNodeMaterial( { transparent: true, side: THREE.DoubleSide, depthWrite: false } );
  164. // position
  165. smokeMaterial.positionNode = Fn( () => {
  166. // twist
  167. const twistNoiseUv = vec2( 0.5, uv().y.mul( 0.2 ).sub( time.mul( 0.005 ) ).mod( 1 ) );
  168. const twist = texture( noiseTexture, twistNoiseUv ).r.mul( 10 );
  169. positionLocal.xz.assign( rotateUV( positionLocal.xz, twist, vec2( 0 ) ) );
  170. // wind
  171. const windOffset = vec2(
  172. texture( noiseTexture, vec2( 0.25, time.mul( 0.01 ) ).mod( 1 ) ).r.sub( 0.5 ),
  173. texture( noiseTexture, vec2( 0.75, time.mul( 0.01 ) ).mod( 1 ) ).r.sub( 0.5 ),
  174. ).mul( uv().y.pow( 2 ).mul( 10 ) );
  175. positionLocal.addAssign( windOffset );
  176. return positionLocal;
  177. } )();
  178. // color
  179. smokeMaterial.colorNode = Fn( () => {
  180. // alpha
  181. const alphaNoiseUv = uv().mul( vec2( 0.5, 0.3 ) ).add( vec2( 0, time.mul( 0.03 ).negate() ) );
  182. const alpha = mul(
  183. // pattern
  184. texture( noiseTexture, alphaNoiseUv ).r.smoothstep( 0.4, 1 ),
  185. // edges fade
  186. smoothstep( 0, 0.1, uv().x ),
  187. smoothstep( 0, 0.1, oneMinus( uv().x ) ),
  188. smoothstep( 0, 0.1, uv().y ),
  189. smoothstep( 0, 0.1, oneMinus( uv().y ) )
  190. );
  191. // color
  192. const finalColor = mix( vec3( 0.6, 0.3, 0.2 ), vec3( 1, 1, 1 ), alpha.pow( 3 ) );
  193. return vec4( finalColor, alpha );
  194. } )();
  195. // mesh
  196. const smoke = new THREE.Mesh( smokeGeometry, smokeMaterial );
  197. smoke.position.y = 1.83;
  198. scene.add( smoke );
  199. // renderer
  200. renderer = new THREE.WebGPURenderer( { antialias: true } );
  201. renderer.setPixelRatio( window.devicePixelRatio );
  202. renderer.setSize( window.innerWidth, window.innerHeight );
  203. renderer.setAnimationLoop( animate );
  204. renderer.inspector = new Inspector();
  205. document.body.appendChild( renderer.domElement );
  206. // uniforms
  207. // PS1-style: 15-bit color (32 levels per channel)
  208. const colorDepthSteps = uniform( 32 );
  209. // CRT effect parameters (subtle for PS1 look)
  210. const scanlineIntensity = uniform( 0.3 ); // subtle scanlines
  211. const scanlineDensity = uniform( 1 ); // 0.1-1: normalized scanline density (1 = full screen resolution)
  212. const scanlineSpeed = uniform( 0.0 ); // no scanline movement
  213. const vignetteIntensity = uniform( 0.3 ); // subtle vignette
  214. const bleeding = uniform( 0.001 ); // minimal bleeding
  215. const curvature = uniform( 0.02 ); // subtle curve
  216. const affineDistortion = uniform( 0 ); // no affine distortion
  217. // render pipeline
  218. renderPipeline = new THREE.RenderPipeline( renderer );
  219. // retro pipeline
  220. const distortedUV = barrelUV( curvature );
  221. const distortedDelta = circle( curvature.add( .1 ).mul( 10 ), 1 ).mul( curvature ).mul( .05 );
  222. const retro = retroPass( scene, camera, { affineDistortion } );
  223. let retroPipeline = retro;
  224. retroPipeline = replaceDefaultUV( distortedUV, retroPipeline );
  225. retroPipeline = colorBleeding( retroPipeline, bleeding.add( distortedDelta ) );
  226. retroPipeline = bayerDither( retroPipeline, colorDepthSteps );
  227. retroPipeline = posterize( retroPipeline, colorDepthSteps );
  228. retroPipeline = vignette( retroPipeline, vignetteIntensity, 0.6 );
  229. retroPipeline = scanlines( retroPipeline, scanlineIntensity, screenSize.y.mul( scanlineDensity ), scanlineSpeed );
  230. renderPipeline.outputNode = retroPipeline;
  231. // default pass (no post-processing)
  232. const defaultPass = pass( scene, camera );
  233. // controls
  234. controls = new OrbitControls( camera, renderer.domElement );
  235. controls.enableDamping = true;
  236. controls.minDistance = 0.1;
  237. controls.maxDistance = 50;
  238. controls.target.y = 1;
  239. // gui
  240. const gui = renderer.inspector.createParameters( 'Settings' );
  241. gui.add( { model: 'Coffee Mug' }, 'model', Object.keys( models ) ).name( 'Model' ).onChange( loadModel );
  242. gui.add( { enabled: true }, 'enabled' ).onChange( v => {
  243. renderPipeline.outputNode = v ? retroPipeline : defaultPass;
  244. renderPipeline.needsUpdate = true;
  245. } ).name( 'Retro Pipeline' );
  246. gui.add( curvature, 'value', 0, 0.2, 0.01 ).name( 'Curvature' );
  247. gui.add( colorDepthSteps, 'value', 4, 32, 1 ).name( 'Color Depth' );
  248. gui.add( scanlineIntensity, 'value', 0, 1, 0.01 ).name( 'Scanlines' );
  249. gui.add( scanlineDensity, 'value', 0.02, 1, 0.01 ).name( 'Scanline Density' );
  250. gui.add( scanlineSpeed, 'value', 0, .1, 0.01 ).name( 'Scanline Speed' );
  251. gui.add( vignetteIntensity, 'value', 0, 1, 0.01 ).name( 'Vignette' );
  252. gui.add( bleeding, 'value', 0, 0.005, 0.001 ).name( 'Color Bleeding' );
  253. gui.add( affineDistortion, 'value', 0, 1 ).name( 'Affine Distortion' );
  254. gui.add( retro, 'filterTextures' ).name( 'Filter Textures' ).onChange( () => {
  255. retro.dispose();
  256. } );
  257. window.addEventListener( 'resize', onWindowResize );
  258. }
  259. function onWindowResize() {
  260. camera.aspect = window.innerWidth / window.innerHeight;
  261. camera.updateProjectionMatrix();
  262. renderer.setSize( window.innerWidth, window.innerHeight );
  263. }
  264. async function animate() {
  265. controls.update();
  266. renderPipeline.render();
  267. }
  268. </script>
  269. </body>
  270. </html>
粤ICP备19079148号