Advertisement
Guest User

Untitled

a guest
Nov 11th, 2024
311
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.38 KB | None | 0 0
  1. Creating a WebGL visualization that renders realistic clouds using fragment shaders and signed distance fields (SDF) involves several steps. Below is a simple example to get you started. This code will create a basic setup where we use noise functions to simulate cloud formations with SDFs.
  2.  
  3. First, ensure you have a canvas element in your HTML:
  4.  
  5. ```html
  6. <!DOCTYPE html>
  7. <html lang="en">
  8. <head>
  9. <meta charset="UTF-8">
  10. <title>WebGL Clouds</title>
  11. <style>
  12. body { margin: 0; overflow: hidden; }
  13. canvas { display: block; }
  14. </style>
  15. </head>
  16. <body>
  17. <canvas id="webgl-canvas"></canvas>
  18.  
  19. <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
  20. <script src="clouds.js"></script>
  21. </body>
  22. </html>
  23. ```
  24.  
  25. Next, create a JavaScript file named `clouds.js` and add the following code:
  26.  
  27. ```javascript
  28. const canvas = document.getElementById('webgl-canvas');
  29. const width = window.innerWidth;
  30. const height = window.innerHeight;
  31.  
  32. // Initialize WebGL context
  33. const gl = canvas.getContext('webgl', { antialias: true });
  34. if (!gl) {
  35. console.error("WebGL is not supported in your browser.");
  36. }
  37.  
  38. // Create shaders and program
  39. function createShader(type, source) {
  40. const shader = gl.createShader(type);
  41. gl.shaderSource(shader, source);
  42. gl.compileShader(shader);
  43. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  44. console.error(gl.getShaderInfoLog(shader));
  45. return null;
  46. }
  47. return shader;
  48. }
  49.  
  50. const vertexShaderSource = `
  51. attribute vec4 a_position;
  52.  
  53. void main() {
  54. gl_Position = a_position;
  55. }
  56. `;
  57.  
  58. const fragmentShaderSource = `
  59. precision mediump float;
  60.  
  61. uniform float u_time;
  62. uniform vec2 u_resolution;
  63.  
  64. float rand(vec2 co){
  65. return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
  66. }
  67.  
  68. float noise(vec2 p){
  69. vec2 ip = floor(p);
  70. vec2 u = fract(p);
  71.  
  72. float res = mix(mix(rand(ip), rand(ip + vec2(1.,0.)), smoothstep(0.,1.,u.x)),
  73. mix(rand(ip + vec2(0.,1.)), rand(ip + vec2(1.,1.)), smoothstep(0.,1.,u.x)),
  74. smoothstep(0.,1.,u.y));
  75.  
  76. return res;
  77. }
  78.  
  79. float fbm(in vec2 p) {
  80. float value = 0.;
  81. float amplitude = .5;
  82. for (int i = 0; i < 6; i++) {
  83. value += amplitude * noise(p);
  84. p *= 2.;
  85. amplitude *= .5;
  86. }
  87. return value;
  88. }
  89.  
  90. float cloudSDF(vec3 pos) {
  91. vec2 uv = pos.xy + fbm(pos.xz + u_time * 0.1) - 0.5;
  92. float d = length(uv) - 0.3;
  93.  
  94. // Adding some variation for more realistic clouds
  95. d += (fbm(pos.zx + u_time * 0.2) - 0.5) * 0.05;
  96. return d;
  97. }
  98.  
  99. void main() {
  100. vec2 uv = gl_FragCoord.xy / u_resolution;
  101. float cloudiness = smoothstep(0.4, 1., cloudSDF(vec3(uv * 8., 0.)));
  102.  
  103. gl_FragColor = vec4(vec3(cloudiness), 1.);
  104. }
  105. `;
  106.  
  107. const vertexShader = createShader(gl.VERTEX_SHADER, vertexShaderSource);
  108. const fragmentShader = createShader(gl.FRAGMENT_SHADER, fragmentShaderSource);
  109.  
  110. const program = gl.createProgram();
  111. gl.attachShader(program, vertexShader);
  112. gl.attachShader(program, fragmentShader);
  113. gl.linkProgram(program);
  114.  
  115. if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
  116. console.error("Could not initialize shaders");
  117. }
  118.  
  119. // Set up the canvas
  120. gl.viewport(0, 0, width, height);
  121. gl.clearColor(1, 1, 1, 1);
  122. gl.enable(gl.DEPTH_TEST);
  123.  
  124. // Create buffers for position
  125. const positionBuffer = gl.createBuffer();
  126. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  127.  
  128. const positions = [
  129. -1, -1,
  130. 1, -1,
  131. -1, 1,
  132. -1, 1,
  133. 1, -1,
  134. 1, 1
  135. ];
  136.  
  137. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
  138.  
  139. // Attributes and uniforms
  140. const positionLocation = gl.getAttribLocation(program, "a_position");
  141. const timeLocation = gl.getUniformLocation(program, "u_time");
  142. const resolutionLocation = gl.getUniformLocation(program, "u_resolution");
  143.  
  144. gl.useProgram(program);
  145. gl.enableVertexAttribArray(positionLocation);
  146. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  147.  
  148. // Render loop
  149. let then = 0;
  150.  
  151. function render(now) {
  152. now *= 0.001; // convert to seconds
  153. const deltaTime = now - then;
  154. then = now;
  155.  
  156. gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  157.  
  158. gl.uniform1f(timeLocation, now);
  159. gl.uniform2f(resolutionLocation, width, height);
  160.  
  161. gl.drawArrays(gl.TRIANGLES, 0, 6);
  162.  
  163. requestAnimationFrame(render);
  164. }
  165.  
  166. requestAnimationFrame(render);
  167. ```
  168.  
  169. ### Explanation:
  170.  
  171. - **Vertex Shader**: The vertex shader is very simple; it just passes the position of each vertex to the fragment shader. This setup uses a full-screen quad.
  172.  
  173. - **Fragment Shader**: The fragment shader does all the heavy lifting:
  174. - `rand`: A simple random function using trigonometric functions.
  175. - `noise`: Generates noise using the Perlin noise algorithm.
  176. - `fbm` (Fractional Brownian Motion): Combines multiple layers of noise at different frequencies to create a more complex and realistic texture.
  177. - `cloudSDF`: Computes a signed distance field for clouds, where positive values represent cloud space and negative values represent clear sky.
  178.  
  179. - **Render Loop**: The render loop updates the time uniform every frame and renders the scene using the quad defined in the vertex buffer.
  180.  
  181. This code provides a basic starting point. You can further enhance it by adding more complex noise functions, lighting effects, or even integrating wind animation for dynamic cloud movement.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement