Dot

Task

Write a program that draws a triangle in the center of the screen. The triangle should have an apex at (0.5, 0.75) in normalized device coordinates, and an apex angle of 120 degrees. The height of the triangle should be 0.5 times the height of the screen.
编写一个程序,在屏幕正中央绘制一个三角形。该三角形的顶点位于归一化设备坐标(NDC)的 (0.5, 0.75),顶角为 120 度,且三角形的高度为屏幕高度的 0.5 倍。

Theory

函数介绍

dot 函数用于计算两个向量的点积(数量积),返回一个标量值。

主要用途

  1. 计算夹角余弦值
ini 复制代码
vec2 a = normalize(vector1);
vec2 b = normalize(vector2);
float angle = dot(a, b);  // cos(夹角)
  1. 计算投影长度
ini 复制代码
//投影长度 = dot(a, b) / length(b)
vec2 direction = normalize(dir);
vec2 toPoint = point - origin;
float projectionLength = dot(direction, toPoint);
  1. 判断向量方向关系
  • dot(A, B) = 1:方向完全相同。
  • dot(A, B) = 0:方向互相垂直。
  • dot(A, B) = -1:方向完全相反。

Answer

glsl 复制代码
uniform vec2 iResolution;

#define PI 3.14

void main() {
  vec2 uv = gl_FragCoord.xy / iResolution.xy;

  vec2 ratio = vec2(iResolution.x / iResolution.y, 1.0);
  uv -= 0.5;
  uv *= ratio;
 
  // 顶上的点(0.5, 0.75)
  vec2 p1 = vec2(0, 0.25);
  // 底部点
  vec2 p2 = vec2(0, -0.25);
  // 已知线的方向
  vec2 p1Dir = normalize(p2 - p1);
  // 当前点到顶点的向量
  vec2 dis = uv - p1;
   // 当前点到顶点的方向
  vec2 p2Dir = normalize(dis);
  // 计算夹角
  float t = dot(p1Dir, p2Dir);
  // 剔除大于60° cos(60) == 0.5
  float red = step(0.5, t);
  // 获取当前点在已知线上的投影长度(已知线的长度为0.5)
  float d = dot(p1Dir, dis); 
  red *= (1.0 - step(0.5, d));

  gl_FragColor = vec4(red, 0.0, 0.0, 1.0);
}

效果

练习

Dot

最后

如果你觉得这篇文章有用,记得点赞、关注、收藏,学Shader更轻松!!

相关推荐
米柆3 分钟前
HTML5 audio /video 完整事件监听模板
前端·html·html5
IT_陈寒30 分钟前
Vite热更新失效?你可能也踩了这个坑
前端·人工智能·后端
程序员大阳1 小时前
副队长CSS教程(30)–CSS Grid 实战:实现复杂自适应表单布局
前端·css·自适应·grid·表单
Csvn1 小时前
微前端实现
前端
Chrischaan2 小时前
做 AI 塔罗小程序时,我为什么不让大模型自己抽牌:一次上线复盘
前端
骑着蜗牛撵大象3273 小时前
LangChain 工具调用从声明到闭环:给智能体接上真实的手脚
前端
数据掘金3 小时前
百度统计后台页面数据异常?从手动调用时机开始排查
前端
hunteritself3 小时前
10 层 4K 实时剪辑,国产工作站进入广电制作核心
大数据·前端·人工智能·深度学习·transformer
踩着两条虫3 小时前
我在浏览器里“盖”了一个村:Vue + Three.js 大屏开发踩坑记
前端·vue.js·three.js
mbshqqb3 小时前
TypeScript基础教程之同步生成器
前端·javascript·typescript