babylonjs shader学习之copy shadertoy案例

news2024/11/28 10:42:34

shadertoy案例:

准备

const onSceneReady = (scene: Scene) => {
  const light = new HemisphericLight('light', new Vector3(0, 1, 0), scene);
  light.intensity = 0.7;

  Effect.ShadersStore['planeMatVertexShader'] = `
    precision highp float;

    attribute vec3 position;
    attribute vec3 normal;
    attribute vec2 uv;

    varying vec3 vPosition;
    varying vec2 vUV;
    varying vec3 vNormal;

    uniform mat4 worldViewProjection;

    void main(){
      gl_Position =worldViewProjection * vec4(position, 1.0);
      vPosition = position;
      vUV = uv;
      vNormal = normal;
    }
  `;
  Effect.ShadersStore['planeMatFragmentShader'] = `

    precision highp float;

  `

  const plane = MeshBuilder.CreateGround('plane', { width: 10, height: 5 }, scene);
  const shaderMat = new ShaderMaterial('shaderMat', scene, 'planeMat', {
    attributes: ['position', 'normal', 'uv'],
    uniforms: ['world', 'worldView', 'worldViewProjection', 'view', 'projection']
  });
  plane.material = shaderMat;

  // 获取渲染画布宽高
  const { width, height } = scene.getEngine().getRenderingCanvas()!;

  shaderMat.onBindObservable.add(() => {
    shaderMat.setVector2('iResolution', new Vector2(width, height));
    shaderMat.setFloat('iTime', time);
  });
    
  let time = 0;
  scene.registerBeforeRender(() => {
    time += 0.005;
  });

}
复制片元着色器
Effect.ShadersStore['planeMatFragmentShader'] = `

  precision highp float;


  //#define FAST_DESCENT
  //#define BLACK_AND_WHITE

  uniform float iTime;
  uniform vec2 iResolution;
  varying vec2 vUV;

  
  #ifdef FAST_DESCENT
  const vec3 cameraDir = normalize(vec3(-2.0, -1.0, -4.0));
  const float cameraDist = 5.0;
  const float speed = 3.0;
  const float zoom = 2.5;

  const vec3 windowColorA = vec3(0.0, 0.0, 1.5);
  const vec3 windowColorB = vec3(0.5, 1.5, 2.0);

  const float fogOffset = 2.5;
  const float fogDensity = 0.6;
  const vec3 fogColor = vec3(0.25, 0.0, 0.3);

  const float lightHeight = 0.5;
  const float lightSpeed = 0.2;
  const vec3 lightColorA = vec3(0.6, 0.3, 0.1);
  const vec3 lightColorB = vec3(0.8, 0.6, 0.4);

  const vec3 signColorA = vec3(0.0, 0.0, 1.5);
  const vec3 signColorB = vec3(3.0, 3.0, 3.0);
  #else

  const vec3 cameraDir = normalize(vec3(-2.0, -1.0, -2.0));
  const float cameraDist = 9.0;
  const float speed = 1.0;
  const float zoom = 3.5;

  const vec3 windowColorA = vec3(0.0, 0.0, 1.5);
  const vec3 windowColorB = vec3(0.5, 1.5, 2.0);

  const float fogOffset = 7.0;
  const float fogDensity = 0.7;
  const vec3 fogColor = vec3(0.25, 0.0, 0.3);

  const float lightHeight = 0.0;
  const float lightSpeed = 0.15;
  const vec3 lightColorA = vec3(0.6, 0.3, 0.1);
  const vec3 lightColorB = vec3(0.8, 0.6, 0.4);

  const vec3 signColorA = vec3(0.0, 0.0, 1.5);
  const vec3 signColorB = vec3(3.0, 3.0, 3.0);
  #endif

  const float tau = 6.283185;


  float hash1(float p) {
      vec3 p3 = fract(p * vec3(5.3983, 5.4427, 6.9371));
      p3 += dot(p3, p3.yzx + 19.19);
      return fract((p3.x + p3.y) * p3.z);
  }

  float hash1(vec2 p2) {
      p2 = fract(p2 * vec2(5.3983, 5.4427));
      p2 += dot(p2.yx, p2.xy + vec2(21.5351, 14.3137));
      return fract(p2.x * p2.y * 95.4337);
  }

  float hash1(vec2 p2, float p) {
      vec3 p3 = fract(vec3(5.3983 * p2.x, 5.4427 * p2.y, 6.9371 * p));
      p3 += dot(p3, p3.yzx + 19.19);
      return fract((p3.x + p3.y) * p3.z);
  }

  vec2 hash2(vec2 p2, float p) {
      vec3 p3 = fract(vec3(5.3983 * p2.x, 5.4427 * p2.y, 6.9371 * p));
      p3 += dot(p3, p3.yzx + 19.19);
      return fract((p3.xx + p3.yz) * p3.zy);
  }

  vec3 hash3(vec2 p2) {
      vec3 p3 = fract(vec3(p2.xyx) * vec3(5.3983, 5.4427, 6.9371));
      p3 += dot(p3, p3.yxz + 19.19);
      return fract((p3.xxy + p3.yzz) * p3.zyx);
  }

  vec4 hash4(vec2 p2) {
      vec4 p4 = fract(p2.xyxy * vec4(5.3983, 5.4427, 6.9371, 7.1283));
      p4 += dot(p4, p4.yxwz + 19.19);
      return fract((p4.xxxy + p4.yyzz + p4.zwww) * p4.wzyx);
  }

  float noise(vec2 p) {
      vec2 i = floor(p);
      vec2 f = fract(p);
      vec2 u = f * f * (3.0 - 2.0 * f);
      return mix(mix(hash1(i + vec2(0.0, 0.0)),
                    hash1(i + vec2(1.0, 0.0)), u.x),
                mix(hash1(i + vec2(0.0, 1.0)),
                    hash1(i + vec2(1.0, 1.0)), u.x), u.y);
  }

  vec4 castRay(vec3 eye, vec3 ray, vec2 center) {
      vec2 block = floor(eye.xy);
      vec3 ri = 1.0 / ray;
      vec3 rs = sign(ray);
      vec3 side = 0.5 + 0.5 * rs;
      vec2 ris = ri.xy * rs.xy;
      vec2 dis = (block - eye.xy + 0.5 + rs.xy * 0.5) * ri.xy;

      for (int i = 0; i < 16; ++i) {
          float d = dot(block - center, cameraDir.xy);
          float height = 3.0 * hash1(block) - 1.0 + 1.5 * d - 0.1 * d * d;

          vec2 lo0 = vec2(block);
          vec2 loX = vec2(0.45, 0.45);
          vec2 hi0 = vec2(block + 0.55);
          vec2 hiX = vec2(0.45, 0.45);

          float dist = 500.0;
          float face = 0.0;

          {
              vec4 signHash = hash4(block);
              vec2 center = vec2(0.2, -0.4) + vec2(0.6, -0.8) * signHash.xy;
              float width = 0.06 + 0.1 * signHash.w;

              vec3 lo = vec3(center.x - width, 0.55, -100.0);
              vec3 hi = vec3(center.x + width, 0.99, center.y + width + height);

              float s = step(0.5, signHash.z);
              lo = vec3(block, 0.0) + mix(lo, lo.yxz, s);
              hi = vec3(block, 0.0) + mix(hi, hi.yxz, s);

              vec3 wall = mix(hi, lo, side);
              vec3 t = (wall - eye) * ri;

              vec3 dim = step(t.zxy, t) * step(t.yzx, t);
              float maxT = dot(dim, t);
              float maxFace = dim.x - dim.y;

              vec3 p = eye + maxT * ray;
              dim += step(lo, p) * step(p, hi);

              if (dim.x * dim.y * dim.z > 0.5) {
                  dist = maxT;
                  face = maxFace;
              }
          }

          for (int j = 0; j < 5; ++j) {
              float top = height - 0.4 * float(j);
              vec3 lo = vec3(lo0 + loX * hash2(block, float(j)), -100.0);
              vec3 hi = vec3(hi0 + hiX * hash2(block, float(j) + 0.5), top);

              vec3 wall = mix(hi, lo, side);
              vec3 t = (wall - eye) * ri;

              vec3 dim = step(t.zxy, t) * step(t.yzx, t);
              float maxT = dot(dim, t);
              float maxFace = dim.x - dim.y;

              vec3 p = eye + maxT * ray;
              dim += step(lo, p) * step(p, hi);

              if (dim.x * dim.y * dim.z > 0.5 && maxT < dist) {
                  dist = maxT;
                  face = maxFace;
              }
          }

          if (dist < 400.0) {
              return vec4(dist, height, face, 1.0);
          }

          float t = eye.z * ri.z;
          vec3 p = eye - t * ray;
          vec2 g = p.xy - block;

          vec2 dim = step(dis.xy, dis.yx);
          dis += dim * ris;
          block += dim * rs.xy;
      }

      return vec4(100.0, 0.0, 0.0, 1.0);
  }

  vec3 window(float z, vec2 pos, vec2 id) {
      float windowSize = 0.03 + 0.12 * hash1(id + 0.1);
      float windowProb = 0.3 + 0.8 * hash1(id + 0.2);
      float depth = z / windowSize;
      float level = floor(depth);
      vec3 colorA = mix(windowColorA, windowColorB, hash3(id));
      vec3 colorB = mix(windowColorA, windowColorB, hash3(id + 0.1));
      vec3 color = mix(colorA, colorB, hash1(id, level));
      color *= 0.3 + 0.7 * smoothstep(0.1, 0.5, noise(20.0 * pos + 100.0 * hash1(level)));
      color *= smoothstep(windowProb - 0.2, windowProb + 0.2, hash1(id, level + 0.1));
      return color * (0.5 - 0.5 * cos(tau * depth));
  }

  vec3 addLight(vec3 eye, vec3 ray, float res, float time, float height) {
      vec2 q = eye.xy + ((height - eye.z) / ray.z) * ray.xy;

      float row = floor(q.x + 0.5);
      time += hash1(row);
      float col = floor(0.125 * q.y - time);

      float pos = 0.4 + 0.4 * cos(time + tau * hash1(vec2(row, col)));
      vec3 lightPos = vec3(row, 8.0 * (col + time + pos), height);
      vec3 lightDir = vec3(0.0, 1.0, 0.0);

      // http://geomalgorithms.com/a07-_distance.html
      vec3 w = eye - lightPos;
      float a = dot(ray, ray);
      float b = dot(ray, lightDir);
      float c = dot(lightDir, lightDir);
      float d = dot(ray, w);
      float e = dot(lightDir, w);
      float D = a * c - b * b;
      float s = (b*e - c*d) / D;
      float t = (a*e - b*d) / D;

      t = max(t, 0.0);
      float dist = distance(eye + s * ray, lightPos + t * lightDir);

      float mask = smoothstep(res + 0.1, res, s);
      float light = min(1.0 / pow(200.0 * dist * dist / t + 20.0 * t * t, 0.8), 2.0);
      float fog = exp(-fogDensity * max(s - fogOffset, 0.0));
      vec3 color = mix(lightColorA, lightColorB, hash3(vec2(row, col)));
      return mask * light * fog * color;
  }

  vec3 addSign(vec3 color, vec3 pos, float side, vec2 id) {
      vec4 signHash = hash4(id);
      float s = step(0.5, signHash.z);
      if ((s - 0.5) * side < 0.1)
          return color;

      vec2 center = vec2(0.2, -0.4) + vec2(0.6, -0.8) * signHash.xy;
      vec2 p = mix(pos.xz, pos.yz, s);
      float halfWidth = 0.04 + 0.06 * signHash.w;

      float charCount = floor(1.0 + 8.0 * hash1(id + 0.5));
      if (center.y - p.y > 2.0 * halfWidth * (charCount + 1.0)) {
          center.y -= 2.0 * halfWidth * (charCount + 1.5 + 5.0 * hash1(id + 0.6));
          charCount = floor(2.0 + 12.0 * hash1(id + 0.7));
          id += 0.05;
      }

      vec3 signColor = mix(signColorA, signColorB, hash3(id + 0.5));
      vec3 outlineColor = mix(signColorA, signColorB, hash3(id + 0.6));
      float flash = 6.0 - 24.0 * hash1(id + 0.8);
      flash *= step(3.0, flash);
      flash = smoothstep(0.1, 0.5, 0.5 + 0.5 * cos(flash * iTime));

      vec2 halfSize = vec2(halfWidth, halfWidth * charCount);
      center.y -= halfSize.y;
      float outline = length(max(abs(p - center) - halfSize, 0.0)) / halfWidth;
      color *= smoothstep(0.1, 0.4, outline);

      vec2 charPos = 0.5 * (p - center + halfSize) / halfWidth;
      vec2 charId = id + 0.05 + 0.1 * floor(charPos);
      float flicker = hash1(charId);
      flicker = step(0.93, flicker);
      flicker = 1.0 - flicker * step(0.96, hash1(charId, iTime));

      float char = -3.5 + 8.0 * noise(id + 6.0 * charPos);
      charPos = fract(charPos);
      char *= smoothstep(0.0, 0.4, charPos.x) * smoothstep(1.0, 0.6, charPos.x);
      char *= smoothstep(0.0, 0.4, charPos.y) * smoothstep(1.0, 0.6, charPos.y);
      color = mix(color, signColor, flash * flicker * step(outline, 0.01) * clamp(char, 0.0, 1.0));

      outline = smoothstep(0.0, 0.2, outline) * smoothstep(0.5, 0.3, outline);
      return mix(color, outlineColor, flash * outline);
  }

  void main() {
      vec2 center = -speed * iTime * cameraDir.xy;
      vec3 eye = vec3(center, 0.0) - cameraDist * cameraDir;

      vec3 forward = normalize(cameraDir);
      vec3 right = normalize(cross(forward, vec3(0.0, 0.0, 1.0)));
      vec3 up = cross(right, forward);
      // vec2 xy = 2.0 * gl_FragCoord.xy - iResolution.xy;
      vec2 xy = vUV;
      xy.x *= iResolution.x / iResolution.y;
      xy -= 0.5;

      vec3 ray = normalize(xy.x * right + xy.y * up + zoom * forward * 0.4 );

      vec4 res = castRay(eye, ray, center);
      vec3 p = eye + res.x * ray;

      vec2 block = floor(p.xy);
    vec3 color = window(p.z - res.y, p.xy, block);

      color = addSign(color, vec3(p.xy - block, p.z - res.y), res.z, block);
      color = mix(vec3(0.0), color, abs(res.z));

      float fog = exp(-fogDensity * max(res.x - fogOffset, 0.0));
      color = mix(fogColor, color, fog);

      float time = lightSpeed * iTime;
      color += addLight(eye.xyz, ray.xyz, res.x, time, lightHeight - 0.6);
      color += addLight(eye.yxz, ray.yxz, res.x, time, lightHeight - 0.4);
      color += addLight(vec3(-eye.xy, eye.z), vec3(-ray.xy, ray.z), res.x, time, lightHeight - 0.2);
      color += addLight(vec3(-eye.yx, eye.z), vec3(-ray.yx, ray.z), res.x, time, lightHeight);

  #ifdef BLACK_AND_WHITE
      float c = clamp(dot(vec3(0.4, 0.3, 0.4), color), 0.0, 1.0);
      c = 1.0 - pow(1.0 - pow(c, 2.0), 4.0);
      color = vec3(c);
  #endif
      
      gl_FragColor = vec4(color, 1.0);
  }
修改
  1. 在片元着色器顶部添加精度
    1.   precision highp float;

  2. 添加uniform

    1. uniform float iTime;

    2. uniform vec2 iResolution;

  3. 添加varying

    1. varying vec2 vUV;

  4. 修改main函数

    1. 将mainImage改成main

    2. 去掉参数 out vec4 fragColor, in vec2 fragCoord

    3. 修改变量fragColor成gl_FragColor、修改fragCoord成gl_FragCoord

  5. 修改uv获取

    
    // 将下面代码注释,并替换
    //vec2 xy = 2.0 * fragCoord - iResolution.xy;
      vec2 xy = vUV;
      xy.x *= iResolution.x / iResolution.y;
      xy -= 0.5;
预览
 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2219006.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

SpringMVC一个拦截器和文件上传下载的完整程序代码示例以及IDEA2024部署报错 找不到此 Web 模块的 out\artifacts\..问题

一、SpringMVC一个拦截器和文件上传下载的完整程序代码示例 本文章是一个 SpringMVC拦 截器和文件上传下载的完整程序代码示例&#xff0c;使用的开发工具是 IntelliJ IDEA 2024.1.6 (Ultimate Edition)&#xff0c; 开发环境是 OpenJDK-21 java version 21.0.2。Tomcatt版本为…

Flux.concat 使用说明书

public static <T> Flux<T> concat(Iterable<? extends Publisher<? extends T>> sources)Concatenate all sources provided in an Iterable, forwarding elements emitted by the sources downstream. 连接可迭代集合中提供的所有源&#xff0c;将…

【web】JDBC

项目连接数据库 右侧导航栏找到databsae 如果没有驱动&#xff0c;先下载驱动 填写数据库用户名密码 勾选对应的表即可 JDBC代码流程 1,配置信息 2,加载驱动 从MySQL Connector/J 5.1版本开始&#xff0c;推荐使用com.mysql.cj.jdbc.Driver这个新的驱动类。 3,链接数据库…

【MR开发】在Pico设备上接入MRTK3(三)——在Unity中运行MRTK示例

在前面的文档中&#xff0c;介绍了如何在Unity工程中配置号MRTK和Pico SDK 【MR开发】在Pico设备上接入MRTK3&#xff08;一&#xff09;在Unity中导入MRTK3依赖【MR开发】在Pico设备上接入MRTK3&#xff08;二&#xff09;在Unity中配置Pico SDK 本文将介绍如何运行一个简单…

SQL进阶技巧:如何找出开会时间有重叠的会议室?| 时间区间重叠问题

目录 0 场景描述 1 数据准备 2 问题分析 方法1:利用 lateral view posexplode()函数将表展开成时间明细表 方法2:利用数学区间讨论思想求解 3 小结 0 场景描述 有7个会议室,每个会议室每天都有人开会,某一天的开会时间如下: 查询出开会时间有重叠的是哪几个会议室?…

Agentic RAG(基于智能体的检索增强生成)是检索增强生成(Retrieval-Augmented Generation,RAG)技术的一种高级形式

Agentic RAG&#xff08;基于智能体的检索增强生成&#xff09;是检索增强生成&#xff08;Retrieval-Augmented Generation&#xff0c;RAG&#xff09;技术的一种高级形式&#xff0c;它通过引入人工智能代理&#xff08;Agent&#xff09;的概念&#xff0c;为语言模型赋予了…

C#从零开始学习(用unity探索C#)(unity Lab1)

初次使用Unity 本章所有的代码都放在 https://github.com/hikinazimi/head-first-Csharp Unity的下载与安装 从 unity官网下载Unity Hub Unity的使用 安装后,注册账号,下载unity版本,然后创建3d项目 设置窗口界面布局 3D对象的创建 点击对象,然后点击Move Guzmo,就可以拖动…

018_FEA_Structure_Static_in_Matlab三维结构静力学分析

刹车变形分析 本示例展示了如何使用 MATLAB 软件进行刹车变形分析。 这个例子是Matlab官方PDE工具箱的第一个例子&#xff0c;所需要的数据文件都由Matlab提供&#xff0c;包括CAD模型文件。 步骤 1: 导入 CAD 模型 导入 CAD 模型&#xff0c;这里使用的是一个带有孔的支架模…

HTTP cookie 与 session

一种关于登录的场景演示 - B 站登录和未登录 问题&#xff1a;B 站是如何认识我这个登录用户的&#xff1f;问题&#xff1a;HTTP 是无状态&#xff0c;无连接的&#xff0c;怎么能够记住我&#xff1f; 一、引入 HTTP Cookie 定义 HTTP Cookie&#xff08;也称为 Web Cooki…

【最新华为OD机试E卷-支持在线评测】VLAN资源池(100分)多语言题解-(Python/C/JavaScript/Java/Cpp)

🍭 大家好这里是春秋招笔试突围 ,一枚热爱算法的程序员 💻 ACM金牌🏅️团队 | 大厂实习经历 | 多年算法竞赛经历 ✨ 本系列打算持续跟新华为OD-E/D卷的多语言AC题解 🧩 大部分包含 Python / C / Javascript / Java / Cpp 多语言代码 👏 感谢大家的订阅➕ 和 喜欢�…

R语言复杂抽样调查数据统计描述和分析

gtsummary包中tbl_svysummary提供了统计描述&#xff1b;tableone包中的svyCreateTableOne提供了统计比较&#xff1b;原始描述和比较可以是有table1包。 #测试数据 library(survey) setwd("F://") data(Titanic) sur_des<-survey::svydesign(~1, data as.data.…

Leetcode—1117. H2O 生成【中等】(多线程)

2024每日刷题&#xff08;182&#xff09; Leetcode—1117. H2O 生成 C实现代码 class H2O { public:H2O() {sem_init(&hydrogenSem, 0, 1);sem_init(&oxygenSem, 0, 0);}~H2O() {sem_destroy(&hydrogenSem);sem_destroy(&oxygenSem);}void hydrogen(functio…

重学SpringBoot3-Spring WebFlux简介

更多SpringBoot3内容请关注我的专栏&#xff1a;《SpringBoot3》 期待您的点赞&#x1f44d;收藏⭐评论✍ 重学SpringBoot3-Spring WebFlux简介 1. 什么是 WebFlux&#xff1f;2. WebFlux 与 Spring MVC 的区别3. WebFlux 的用处3.1 非阻塞 I/O 操作3.2 响应式编程模型3.3 更高…

机械视觉光源选型

光源是机器视觉系统的重要组成部分&#xff0c;直接影响到图像的质量&#xff0c;进而影响到系统的性 能。在一定程度上&#xff0c;光源的设计与选择是机器视觉系统成败的关键。光源最重要的功能就 是使被观察的图像特征与被忽略的图像特征之间产生最大的对比度&#xff0c;…

RISC-V笔记——RVWMO基本体

1. 前言 RISC-V使用的内存模型是RVWMO(RISC-V Weak Memory Ordering)&#xff0c;它是Release Consistency的扩展&#xff0c;因此&#xff0c;RVWMO的基本特性类似于RC模型。 2. RC模型 Release consistency(RC)的提出是基于一个观察&#xff1a;将所有同步操作用FENCE围在一…

基于x86_64汇编语言简单教程1: 环境预备与尝试

目录 前言 环境配置 基本硬件与操作系统要求 WSL VSCode基本配置(For Windows) 安装基本的依赖 为您的VSCode安装插件&#xff1a; 学习要求 入门 先试试味道 前言 笔者最近正在梭哈使用NASM汇编器的x86 32位汇编&#xff0c;笔者这里记录一下一个晚上的成果。 环境…

【含开题报告+文档+PPT+源码】贫困儿童一对一扶贫帮扶系统设计与实现

开题报告 根据《中华人民共和国慈善法》第五十八条规定&#xff0c;慈善组织确定慈善受益人&#xff0c;应当坚持公开、公平、公正的原则&#xff0c;不得指定慈善组织管理人员的利害关系人作为受益人[2]。以上所列举的平台基本没有做到公开、公平、公正的原则&#xff0c;例如…

一起搭WPF架构之livechart的MVVM使用介绍

一起搭WPF架构之livechart使用介绍 前言ModelViewModelView界面设计界面后端 效果总结 前言 简单的架构搭建已经快接近尾声了&#xff0c;考虑设计使用图表的形式将SQLite数据库中的数据展示出来。前期已经介绍了livechart的安装&#xff0c;今天就详细介绍一下livechart的使用…

应用层协议 序列化

自定义应用层协议 例子&#xff1a;网络版本计算器 序列化反序列化 序列化&#xff1a;将消息&#xff0c;昵称&#xff0c;日期整合成消息-昵称-日期 反序列化&#xff1a;消息-昵称-日期->消息&#xff0c;昵称&#xff0c;日期 在序列化中&#xff0c;定义一个结构体…

Python案例小练习——小计算器

文章目录 前言一、代码展示二、运行展示 前言 这是用python实现一个简单的计器。 一、代码展示 def calculate(num1, op, num2):if op "":return float(num1) float(num2)elif op "-":return float(num1) - float(num2)elif op "*":return…