threepipe
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

shadertoy-player.md 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. ---
  2. prev:
  3. text: 'Setting Background Color and Images'
  4. link: './scene-background'
  5. next: false
  6. aside: false
  7. ---
  8. # ShaderToy Shaders in Three.js
  9. <iframe src="https://threepipe.org/examples/shadertoy-player/" style="width:100%;height:600px;border:none;"></iframe>
  10. This tutorial shows how to use shaders from ShaderToy in a Three.js scene by using them as custom screen shaders. You'll learn how to run ShaderToy shaders in a Three.js context, pass uniforms, and create interactive controls.
  11. ## Overview
  12. ShaderToy is a popular online shader editor that uses a specific format for fragment shaders. To use these shaders in Three.js, we need to:
  13. 1. Set up the proper uniforms that ShaderToy expects
  14. 2. Create a custom material that wraps the ShaderToy shader
  15. 3. Use it as a screen shader in threepipe
  16. 4. Handle mouse input and time updates
  17. ## Step 1: Setting Up the Basic Structure
  18. First, import the necessary modules from threepipe:
  19. ```typescript
  20. import {
  21. ExtendedShaderMaterial,
  22. glsl,
  23. GLSL3,
  24. LoadingScreenPlugin,
  25. MaterialExtension,
  26. ThreeViewer,
  27. Vector2,
  28. Vector3,
  29. Vector4,
  30. } from 'threepipe'
  31. import {TweakpaneUiPlugin} from '@threepipe/plugin-tweakpane'
  32. ```
  33. ## Step 2: Define ShaderToy Uniforms
  34. ShaderToy shaders expect specific uniforms. Create these to match the ShaderToy specification:
  35. ```typescript
  36. const uniforms = {
  37. iResolution: {value: new Vector3()}, // viewport resolution
  38. iTime: {value: 0}, // shader playback time
  39. iFrame: {value: 0}, // current frame number
  40. iMouse: {value: new Vector4()}, // mouse pixel coords
  41. iTimeDelta: {value: 0}, // render time delta
  42. iDate: {value: new Vector4()}, // current date
  43. iFrameRate: {value: 0}, // frame rate
  44. iChannel0: {value: null}, // texture channels
  45. iChannel1: {value: null},
  46. iChannel2: {value: null},
  47. iChannel3: {value: null},
  48. // Additional uniforms for channel sizes
  49. iChannel0Size: {value: new Vector2()},
  50. iChannel1Size: {value: new Vector2()},
  51. iChannel2Size: {value: new Vector2()},
  52. iChannel3Size: {value: new Vector2()},
  53. // Custom uniforms for shader parameters
  54. customFloat: {value: 0.5}, // Sample float parameter
  55. customColor: {value: new Vector3(1.0, 0.5, 0.2)}, // Sample color parameter
  56. customIntensity: {value: 1.0}, // Sample intensity parameter
  57. }
  58. ```
  59. ### Adding Custom Parameters
  60. You can extend the uniforms object with any custom parameters your shader needs. These will be available in your fragment shader and can be controlled through the UI. Common types include:
  61. - **Float values**: For controlling intensity, speed, scale, etc.
  62. - **Vector3 colors**: For color parameters
  63. - **Vector2/Vector3/Vector4**: For vectors
  64. - **Boolean flags**: For enabling/disabling effects (passed as floats: 0.0 or 1.0)
  65. ## Step 3: Create the Shader Material
  66. The fragment shader needs to be adapted to work with Three.js. Here's the wrapper that makes ShaderToy shaders compatible:
  67. ```glsl
  68. precision highp int;
  69. precision highp sampler2D;
  70. uniform vec3 iResolution;
  71. uniform float iTime;
  72. uniform vec4 iMouse;
  73. uniform vec4 iDate;
  74. uniform float iTimeDelta;
  75. uniform int iFrame;
  76. uniform float iFrameRate;
  77. // Channel uniforms
  78. uniform vec2 iChannel0Size;
  79. uniform vec2 iChannel1Size;
  80. uniform vec2 iChannel2Size;
  81. uniform vec2 iChannel3Size;
  82. in vec2 vUv;
  83. layout(location = 0) out vec4 glFragColor;
  84. void main() {
  85. // Set up channel resolutions
  86. vec3 iChannelResolution[4];
  87. iChannelResolution[0] = vec3(iChannel0Size, 1.0);
  88. iChannelResolution[1] = vec3(iChannel1Size, 1.0);
  89. iChannelResolution[2] = vec3(iChannel2Size, 1.0);
  90. iChannelResolution[3] = vec3(iChannel3Size, 1.0);
  91. // Call the ShaderToy main function
  92. mainImage(glFragColor, gl_FragCoord.xy);
  93. // Apply screen shader processing
  94. vec4 diffuseColor = glFragColor;
  95. #glMarker
  96. glFragColor = diffuseColor;
  97. // Ensure alpha is 1.0 for screen shaders
  98. glFragColor.a = 1.0;
  99. }
  100. ```
  101. The shader calls the `mainImage` function, which is where your ShaderToy code will go. This function should be defined in your ShaderToy code and will receive the `fragColor` and `fragCoord` parameters.
  102. Since this is not defined in the shader itself, it will not compile without a material extension that injects the `mainImage` function.
  103. ::: note `glMarker`
  104. The `#glMarker` directive is a placeholder for the `ScreenPass` in threepipe that indicates where the screen shader extensions should be added. These include extensions by plugins like `TonemapPlugin`, `VignettePlugin`, etc.
  105. You can remove it if you don't need these extensions.
  106. `diffuseColor` is the final color output of the shader, which will be modified by the screen shader extensions.
  107. Checkout the [Screen Pass guide](./../guide/screen-pass) for more information on how screen shaders work in threepipe.
  108. :::
  109. ## Step 4: Create the Material Extension
  110. Use a `MaterialExtension` to inject your ShaderToy code:
  111. ```typescript
  112. const toyExtension: MaterialExtension = {
  113. parsFragmentSnippet: `
  114. unfiform float customFloat;
  115. uniform vec3 customColor;
  116. uniform float customIntensity;
  117. void mainImage(out vec4 fragColor, in vec2 fragCoord) {
  118. vec2 uv = fragCoord / iResolution.xy;
  119. fragColor = vec4(uv * customIntensity, 0, 1);
  120. }
  121. `,
  122. isCompatible: () => true,
  123. computeCacheKey: Math.random().toString(),
  124. }
  125. ```
  126. Here, `parsFragmentSnippet` is added to the material's fragment shader just before the main function.
  127. You can replace it with your ShaderToy code with any custom uniforms you need.
  128. Checkout the [Material Extension guide](./../guide/material-extension) for more information.
  129. This has a default shader, but you can dynamically change the `parsFragmentSnippet` to load different ShaderToy shaders at runtime.
  130. ```typescript
  131. const response = await fetch('https://asset-samples.threepipe.org/shaders/tunnel-cylinders.glsl')
  132. const shaderText = await response.text()
  133. toyExtension.parsFragmentSnippet = v
  134. toyExtension.computeCacheKey = Math.random().toString()
  135. material.setDirty()
  136. ```
  137. ## Step 5: Set Up the Material and Viewer
  138. Create the [`ExtendedShaderMaterial`](https://threepipe.org/docs/classes/ExtendedShaderMaterial.html) and configure the viewer:
  139. ```typescript
  140. const material = new ExtendedShaderMaterial({
  141. uniforms: uniforms,
  142. defines: {
  143. IS_SCREEN: '1',
  144. IS_LINEAR_OUTPUT: '1',
  145. },
  146. glslVersion: GLSL3,
  147. vertexShader: toyVert,
  148. fragmentShader: toyFrag,
  149. transparent: true,
  150. depthTest: false,
  151. depthWrite: false,
  152. premultipliedAlpha: false,
  153. })
  154. material.registerMaterialExtensions([toyExtension])
  155. const viewer = new ThreeViewer({
  156. canvas: document.getElementById('mcanvas'),
  157. msaa: false,
  158. rgbm: false,
  159. tonemap: false,
  160. screenShader: material, // Use as screen shader/material
  161. renderScale: 2,
  162. })
  163. ```
  164. The material is set as the `screenShader` in the viewer configuration, which sets it as material in the `ScreenPass`. Check out the [Screen Pass guide](./../guide/screen-pass) for more details on how custom screen shaders/materials work in threepipe.
  165. ::: note `ExtendedShaderMaterial`
  166. [`ExtendedShaderMaterial`](https://threepipe.org/docs/classes/ExtendedShaderMaterial.html) is a custom material that allows dynamic shader code injection and supports the `MaterialExtension` system.
  167. It extends the standard `ShaderMaterial` to provide additional features like automatic uniform management, shader code injection, compatibility with the threepipe material extension system, and automatic texture encoding and size support.
  168. It is used here to apply the ShaderToy shader as a screen shader in the viewer.
  169. :::
  170. ## Step 6: Handle Time and Frame Updates
  171. Update the uniforms each frame to animate the shader:
  172. ```typescript
  173. viewer.addEventListener('preFrame', (ev) => {
  174. if (!params.running && !params.stepFrame) return
  175. // Update time uniforms
  176. uniforms.iTimeDelta.value = (ev.deltaTime || 0) / 1000.0
  177. params.time += uniforms.iTimeDelta.value
  178. uniforms.iTime.value = params.time
  179. uniforms.iFrame.value = params.frame++
  180. // Update date
  181. const date = new Date()
  182. uniforms.iDate.value.set(
  183. date.getFullYear(),
  184. date.getMonth(),
  185. date.getDate(),
  186. date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds()
  187. )
  188. // Update resolution
  189. const bufferSize = [
  190. viewer.renderManager.renderSize.width * viewer.renderManager.renderScale,
  191. viewer.renderManager.renderSize.height * viewer.renderManager.renderScale
  192. ]
  193. uniforms.iResolution.value.set(bufferSize[0], bufferSize[1], 1)
  194. material.uniformsNeedUpdate = true
  195. viewer.setDirty()
  196. })
  197. ```
  198. ## Step 7: Handle Mouse Input
  199. Implement mouse tracking to match ShaderToy's mouse behavior:
  200. ```typescript
  201. const mouse = {
  202. position: new Vector2(),
  203. clickPosition: new Vector2(),
  204. isDown: false,
  205. isClick: false,
  206. }
  207. function getMouseFromEvent(canvas, e) {
  208. const rect = canvas.getBoundingClientRect()
  209. const x = e.clientX - rect.left
  210. const y = e.clientY - rect.top
  211. if (x < 0 || y < 0 || x > rect.width || y > rect.height) return null
  212. return mouse.position.set(x / rect.width, 1.0 - y / rect.height)
  213. }
  214. // Update mouse uniform in preFrame event
  215. uniforms.iMouse.value.set(
  216. mouse.position.x * bufferSize[0],
  217. mouse.position.y * bufferSize[1],
  218. mouse.clickPosition.x * (mouse.isDown ? 1 : -1) * bufferSize[0],
  219. mouse.clickPosition.y * (mouse.isClick ? 1 : -1) * bufferSize[1]
  220. )
  221. ```
  222. Checkout the example code for the full boilderplate for mouse handling, including adding event listeners for `mousedown`, `mouseup`, and `mousemove` to update the `mouse` object.
  223. ## Step 8: Add Interactive Controls
  224. Create a UI to control the shader, including custom uniform parameters:
  225. ```typescript
  226. // Define parameters object to store UI-controlled values
  227. const params = {
  228. resolution: new Vector2(1280, 720),
  229. time: 0,
  230. frame: 0,
  231. running: true,
  232. stepFrame: false,
  233. // Custom parameters
  234. customFloat: 0.5,
  235. customColor: new Color(),
  236. customIntensity: 1.0,
  237. }
  238. const ui = {
  239. label: 'Shader Controls',
  240. type: 'folder',
  241. expanded: true,
  242. value: params,
  243. children: [{
  244. type: 'button',
  245. label: () => params.running ? 'Pause' : 'Play',
  246. onClick: () => {
  247. params.running = !params.running
  248. },
  249. }, {
  250. type: 'button',
  251. label: 'Reset',
  252. onClick: () => {
  253. params.frame = 0
  254. params.time = 0
  255. },
  256. }, {
  257. type: 'folder',
  258. label: 'Custom Parameters',
  259. expanded: true,
  260. children: [{
  261. type: 'slider',
  262. path: 'customFloat',
  263. label: 'Sample Float',
  264. bounds: [0, 1],
  265. stepSize: 0.01,
  266. onChange: () => {
  267. uniforms.customFloat.value = params.customFloat
  268. material.uniformsNeedUpdate = true
  269. viewer.setDirty()
  270. },
  271. }, {
  272. type: 'color',
  273. path: 'customColor',
  274. label: 'Sample Color',
  275. onChange: () => {
  276. uniforms.customColor.value.set(
  277. params.customColor.r,
  278. params.customColor.g,
  279. params.customColor.b
  280. )
  281. material.uniformsNeedUpdate = true
  282. viewer.setDirty()
  283. },
  284. }, {
  285. type: 'slider',
  286. path: 'customIntensity',
  287. label: 'Intensity',
  288. bounds: [0, 3],
  289. stepSize: 0.1,
  290. onChange: () => {
  291. uniforms.customIntensity.value = params.customIntensity
  292. material.uniformsNeedUpdate = true
  293. viewer.setDirty()
  294. },
  295. }],
  296. }, {
  297. type: 'button',
  298. label: 'Edit Shader',
  299. onClick: () => setupShaderEditor(toyExtension.parsFragmentSnippet, setShader),
  300. }],
  301. }
  302. const uiPlugin = viewer.addPluginSync(new TweakpaneUiPlugin(true))
  303. uiPlugin.appendChild(ui)
  304. ```
  305. ### UI Control Types
  306. The TweakpaneUiPlugin supports various control types for different uniform parameters:
  307. - **slider**: For numeric values with min/max bounds
  308. - **color**: For RGB color values (automatically converts to Vector3)
  309. - **button**: For triggering actions
  310. - **checkbox**: For boolean values
  311. - **folder**: For grouping related controls
  312. - **vec**: For Vector2/Vector3/Vector4 values (like resolution)
  313. ### Connecting UI to Uniforms
  314. Each UI control should have an `onChange` callback that:
  315. 1. Updates the corresponding uniform value
  316. 2. Sets `material.uniformsNeedUpdate = true`
  317. 3. Calls `viewer.setDirty()` to trigger a re-render
  318. ## Step 9: Dynamic Shader Loading
  319. Implement a function to update the shader dynamically:
  320. ```typescript
  321. const setShader = (shaderCode) => {
  322. toyExtension.parsFragmentSnippet = shaderCode
  323. toyExtension.computeCacheKey = Math.random().toString()
  324. material.setDirty()
  325. viewer.setDirty()
  326. }
  327. // Load a shader from URL
  328. const response = await fetch('path/to/shader.glsl')
  329. const shaderText = await response.text()
  330. setShader(shaderText)
  331. ```
  332. ## Texture Channels
  333. Textures can be set in the uniforms for the shader channels, or can be added to the UI config to configure dynamically:
  334. ```typescript
  335. uniforms.iChannel0.value = await viewer.load('path/to/texture0.png')
  336. // ...
  337. // sample to add to the UI
  338. const uiConfig = {
  339. type: 'image',
  340. property: [uniforms.iChannel0, 'value'],
  341. label: 'iChannel0',
  342. onChange: ()=>{
  343. material.uniformsNeedUpdate = true
  344. material.setDirty()
  345. }
  346. }
  347. ui.appendChild(uiConfig)
  348. ```
  349. ## ShaderToy post-processing
  350. Since the material is added as the `screenShader`, it is rendered in `ScreenPass` after other passes like `RenderPass`, etc.
  351. Output of these can be used to in the shader toy shader to blend the 3d scene with a custom shadertoy effect.
  352. This can be done by defining and accessing the `tDiffuse` and `tTransparent` uniforms in the material and shader code.
  353. Check out the [ScreenPass.glsl](https://github.com/repalash/threepipe/blob/master/src/postprocessing/ScreenPass.glsl) for a sample of how to access these textures in the shader code, as well as interfacing with the gbuffer.
  354. Check the [Screen Pass guide](./../guide/screen-pass) for more details and an example.
  355. ## Key Points
  356. 1. **Screen Shader Usage**: The material is used as a `screenShader` in the viewer configuration, which applies it as a post-processing effect.
  357. 2. **Uniform Management**: All ShaderToy uniforms must be properly updated each frame for the shader to work correctly.
  358. 3. **Coordinate Systems**: Pay attention to coordinate system differences between ShaderToy and Three.js, especially for mouse coordinates.
  359. 4. **Performance**: Screen shaders run on every pixel, so complex shaders can impact performance significantly.
  360. 5. **Material Extensions**: Using MaterialExtension allows dynamic shader code injection without recreating the entire material.
  361. This setup provides a complete ShaderToy player that can run most ShaderToy shaders with proper time, mouse, and resolution handling, plus interactive controls for experimentation.
  362. Check out the [live example](https://threepipe.org/examples/shadertoy-player/) to see it in action along with the source code on [GitHub](https://github.com/repalash/threepipe/tree/master/examples/shadertoy-player/script.ts).