百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

46 行 Python 代码,做一个会旋转的三维甜甜圈!

off999 2024-10-02 18:46 25 浏览 0 评论

摘要:在三维渲染技术中,符号距离函数很难理解,而本文作者仅用 46 行 Python 代码就展示了这项技术。

接:https://vgel.me/posts/donut/

声明:本文为 CSDN 翻译,未经允许禁止转载。

作者 | Theia Vogel
译者 | 弯月 责编 | 郑丽媛
出品 | CSDN(ID:CSDNnews)

符号距离函数(Signed Distance Function,简称 SDF)是一种很酷的三维渲染技术——但不幸的是,这种技术很难理解。

该技术通常都通过 GLSL 编写的 shader 示例来展示,但大多数程序员并不熟悉 GLSL。从本质上来说,SDF 的编写思路非常简单。在本文中,我将编写一个程序来展示这项技术:一段只有 46 行 Python 代码的程序,使用 RayMarching 算法做出了一个甜甜圈动图。

当然,你也可以用其他自己喜欢的语言来编写这段代码,即便没有图形 API 的帮助,我们仅凭 ASCII 码也可以实现这样的动图。所以,一起来试试看吧!最终,我们将获得一个用 ASCII 码制作的、不停旋转的、美味的甜甜圈。只要掌握了这种渲染技术,你就可以制作各种动图。


准备工作


首先,我们用 Python 来渲染每一帧 ASCII。此外,我们还将添加一个循环来实现动画效果:

import timedef sample(x: int, y: int) -> str:# draw an alternating checkboard patternif (x + y + int(time.time())) % 2:return '#'else:return ' 'while True:# loop over each position and sample a characterframe_chars = []for y in range(20):for x in range(80):frame_chars.append(sample(x, y))frame_chars.append('\n')# print out a control sequence to clear the terminal, then the frame# (I haven't tested this on windows, but I believe it should work there,# please get in touch if it doesn't)print('\033[2J' + ''.join(frame_chars))# cap at 30fpstime.sleep(1/30)

以上代码为我们呈现了一个 80x20 的棋盘格,每秒交替一次:

这只是基础,下面我们来增加一些视觉效果——下一个任务很简单:决定屏幕上的每个字符显示什么。


画圆圈


首先,从最简单的工作着手。我们根据 x 坐标和 y 坐标绘制一个圆,虽然这还不是 3D 动画。我们可以通过几种不同的方式来画圆圈,此处我们采用的方法是:针对屏幕上的每个字符,决定应该显示什么,也就是说我们需要逐个字符处理。对于每个字符的坐标 (x, y),我们的基本算法如下:

1. 计算 (x, y) 到屏幕中心的距离:√((x-0)^2 + (y-0)^2),即 √(x^2+y^2)。

2. 减去圆半径。如果该点在圆的内部或边缘,则得到的值 ≤ 0,否则值 > 0。

3. 验证得到的值与 0 的关系,如果该点在圆的内部或边缘,则返回 #,否则返回空格。

此外,我们还需要将 x 和 y 分别映射到 -1..1 和 (-.5)..(.5) 上,这样结果就不会受分辨率的影响了,还可以保证正确的纵横比(2 * 20/ 80 = 0.5,因为 y 仅包含 20 个字符,而 x 包含 80 个字符,终端字符的高度大约是宽度的两倍)——这样可以防止我们画的圆圈看起来像一个压扁的豆子。

import math, timedef circle(x: float, y: float) -> float:# since the range of x is -1..1, the circle's radius will be 40%,# meaning the circle's diameter is 40% of the screenradius = 0.4# calculate the distance from the center of the screen and subtract the# radius, so d will be < 0 inside the circle, 0 on the edge, and > 0 outsidereturn math.sqrt(x**2 + y**2) - radiusdef sample(x: float, y: float) -> str:# return a '#' if we're inside the circle, and ' ' otherwiseif circle(x, y) <= 0:return '#'else:return ' 'while True:frame_chars = []for y in range(20):for x in range(80):# remap to -1..1 range (for x)...remapped_x = x / 80 * 2 - 1# ...and corrected for aspect ratio range (for y)remapped_y = (y / 20 * 2 - 1) * (2 * 20/80)frame_chars.append(sample(remapped_x, remapped_y))frame_chars.append('\n')print('\033[2J' + ''.join(frame_chars))time.sleep(1/30)

我们成功地画出了一个圆!这个例子中并没有使用 time.time(),所以这个圆不会动,不过我们稍后会添加动画。


二维的甜甜圈


一个圆只是二维甜甜圈的一半,而另一半是中间的那个洞洞,也就是另一个圆。下面,我们在这个圆的中心加上一个洞,让它变成甜甜圈。实现方法有好几种,不过最好的方式是用一个半径和半径之外的厚度来定义:

import math, timedef donut_2d(x: float, y: float) -> float:# same radius as before, though the donut will appear larger as# half the thickness is outside this radiusradius = 0.4# how thick the donut will bethickness = 0.3# take the abs of the circle calculation from before, subtracting# `thickness / 2`. `abs(...)` will be 0 on the edge of the circle, and# increase as you move away. therefore, `abs(...) - thickness / 2` will# be ≤ 0 only `thickness / 2` units away from the circle's edge on either# side, giving a donut with a total width of `thickness`return abs(math.sqrt(x**2 + y**2) - radius) - thickness / 2def sample(x: float, y: float) -> str:if donut_2d(x, y) <= 0:return '#'else:return ' 'while True:frame_chars = []for y in range(20):for x in range(80):remapped_x = x / 80 * 2 - 1remapped_y = (y / 20 * 2 - 1) * (2 * 20/80)frame_chars.append(sample(remapped_x, remapped_y))frame_chars.append('\n')print('\033[2J' + ''.join(frame_chars))time.sleep(1/30)

这种表示方法(半径 + 厚度)能呈现很好的艺术效果,因为半径和厚度是相对独立的参数,二者可以单独变更,几乎不需要互相参照。

这样代码也很好写,我们只需要稍微调整计算距离的方式:之前我们计算的是到圆心的距离,现在我们计算到圆边线的距离。边距 - 厚度/2,如果结果 ≤ 0,说明点到圆边线的距离 ≤ 厚度/2,这样就得到一个给定厚度的圆环,其圆心位于给定半径的圆的边线上。

另外一点好处是,代码的改动非常小:只需更新符号距离函数,而渲染循环的其余部分都不需要修改。也就是说,无论我们使用哪个 SDF,渲染循环都可以保持不变,我们只需要针对每个像素采样其距离即可。


三维模型


下面,我们来画三维模型。首先,我们来做一个简单的练习:渲染一个球体,它的 SDF 与圆几乎相同,只不过我们需要再加一个坐标轴 Z。

def sphere(x: float, y: float, z: float) -> float:radius = 0.4return math.sqrt(x**2 + y**2 + z**2) - radius

此处,X 是水平轴,Y 是纵向轴,而 Z 表示深度。

我们还需要重用同一个 frame_chars 循环。唯一需要修改的函数是 sample,我们需要处理第三个维度。从根本上来说, sample 函数需要接受一个二维点(x, y),并以这个二维点为基础,在三维空间中采样。换句话说,我们需要“计算”出正确的 Z,以确保渲染正确的字符。我们可以偷懒采用 z = 0,这样渲染出来的就是三维世界中的一个二维切片,即对象在平面 z=0 上的截面。

但为了渲染出更立体的三维视图,我们需要模拟现实世界。想象一只眼睛,它(近似)是一个二维平面,如何看到远处的物体呢?

太阳光有可能直接照射到眼睛所在的平面上,也有可能经过一个或多个物体反射后到达眼睛。我们可以按照同样的方式来渲染三维视图:每次调用 sample(x, y) 时,从一个模拟的光源射出无数光线,其中至少有一条光线经过物体反射后,穿过点 (x, y , camera_z)。但这种方法的速度会有点慢,某条光线照射到特定点的几率微乎其微,因此大部分工作都是无用功。要是这样写代码的话,用最强大的虚拟机也运行不完,所以我们来走一条捷径。

对于函数 sample(x, y),我们只关心穿过 (x, y, camera_z) 的光线,所以根本没必要在意其他光线。我们可以反向模拟光线:从 (x, y, camera_z) 出发,每走一步首先计算 SDF,获取光线从当前点到场景中任意一点(方向任意)的距离。

如果距离小于某个阈值,则意味着光线击中了场景中的点。反之,我们可以安全地将光线向前“移动”相应的距离,因为我们知道场景中有的点至少位于这段距离之外(实际情况可能更复杂,设想一下光线可能与场景足够接近,但永远不会进入场景:当光线接近场景时SDF 的计算结果会非常小,所以光线只能更加缓慢地前进,但最终在足够多的次数之后,光线会越过场景中的点,然后加快前进速度)。我们将前进的最大步数限制为 30,如果届时光线没有击中任何场景中的点,则返回背景字符。综上所述,下面就是这个三维函数的定义:

def sample(x: float, y: float) -> str:# start `z` far back from the scene, which is centered at 0, 0, 0,# so nothing clipsz = -10# we'll step at most 30 steps before assuming we missed the scenefor _step in range(30):# get the distance, just like in 2Dd = sphere(x, y, z)# test against 0.01, not 0: we're a little more forgiving with the distance# in 3D for faster convergenceif d <= 0.01:# we hit the sphere!return '#'else:# didn't hit anything yet, move the ray forward# we can safely move forward by `d` without hitting anything since we know# that's the distance to the scenez += d# we didn't hit anything after 30 steps, return the backgroundreturn ' '

渲染球体的所有代码如下:

import math, timedef sphere(x: float, y: float, z: float) -> float:radius = 0.4return math.sqrt(x**2 + y**2 + z**2) - radiusdef sample(x: float, y: float) -> str:radius = 0.4z = -10for _step in range(30):d = sphere(x, y, z)if d <= 0.01:return '#'else:z += dreturn ' '# this is unchangedwhile True:frame_chars = []for y in range(20):for x in range(80):remapped_x = x / 80 * 2 - 1remapped_y = (y / 20 * 2 - 1) * (2 * 20/80)frame_chars.append(sample(remapped_x, remapped_y))frame_chars.append('\n')print('\033[2J' + ''.join(frame_chars))time.sleep(1/30)

好了,我们绘制出了一个三维的球体。下面,我们来画三维的甜甜圈。


三维的甜甜圈


为了绘制三维的甜甜圈,接下来我们需要将绘制球体的 SDF 换成绘制更复杂的甜甜圈,其余代码保持不变:

import math, timedef donut(x: float, y: float, z: float) -> float:radius = 0.4thickness = 0.3# first, we get the distance from the center and subtract the radius,# just like the 2d donut.# this value is the distance from the edge of the xy circle along a line# drawn between [x, y, 0] and [0, 0, 0] (the center of the donut).xy_d = math.sqrt(x**2 + y**2) - radius# now we need to consider z, which, since we're evaluating the donut at# [0, 0, 0], is the distance orthogonal (on the z axis) to that# [x, y, 0]..[0, 0, 0] line.# we can use these two values in the usual euclidean distance function to get# the 3D version of our 2D donut "distance from edge" value.d = math.sqrt(xy_d**2 + z**2)# then, we subtract `thickness / 2` as before to get the signed distance,# just like in 2D.return d - thickness / 2# unchanged from before, except for s/sphere/donut/g:def sample(x: float, y: float) -> str:z = -10for _step in range(30):d = donut(x, y, z)if d <= 0.01:return '#'else:z += dreturn ' 'while True:frame_chars = []for y in range(20):for x in range(80):remapped_x = x / 80 * 2 - 1remapped_y = (y / 20 * 2 - 1) * (2 * 20/80)frame_chars.append(sample(remapped_x, remapped_y))frame_chars.append('\n')print('\033[2J' + ''.join(frame_chars))time.sleep(1/30)

这个甜甜圈还不够完美,下面我们来添加一些动画,证明它是三维的。


旋转的三维甜甜圈


为了让甜甜圈旋转起来,我们需要在计算 SDF 之前对 sample 计算的点进行变换:

def sample(x: float, y: float) -> str:...for _step in range(30):# calculate the angle based on time, to animate the donut spinningθ = time.time() * 2# rotate the input coordinates, which is equivalent to rotating the sdft_x = x * math.cos(θ) - z * math.sin(θ)t_z = x * math.sin(θ) + z * math.cos(θ)d = donut(t_x, y, t_z)...

在这段代码中,y 值保持不变,所以甜甜圈是围绕 y 轴旋转的。我们在每次采样时计算 θ 值,然后计算旋转矩阵:

import math, timedef donut(x: float, y: float, z: float) -> float:radius = 0.4thickness = 0.3return math.sqrt((math.sqrt(x**2 + y**2) - radius)**2 + z**2) - thickness / 2def sample(x: float, y: float) -> str:z = -10for _step in range(30):θ = time.time() * 2t_x = x * math.cos(θ) - z * math.sin(θ)t_z = x * math.sin(θ) + z * math.cos(θ)d = donut(t_x, y, t_z)if d <= 0.01:return '#'else:z += dreturn ' 'while True:frame_chars = []for y in range(20):for x in range(80):remapped_x = x / 80 * 2 - 1remapped_y = (y / 20 * 2 - 1) * (2 * 20/80)frame_chars.append(sample(remapped_x, remapped_y))frame_chars.append('\n')print('\033[2J' + ''.join(frame_chars))time.sleep(1/30)

这样,三维的甜甜圈就画好了。下面,我们使用法向量估算器,添加一些简单的光照和纹理。


添加光照和糖霜


为了增加光照和糖霜纹理,我们需要计算法向量。法向量的定义是从对象表面上每个点垂直地发散出来的向量,就像仙人掌上的刺,或者某人在接触到静电气球后头发爆炸的样子。

大多数表面都有计算法向量的公式,但是当一个场景中融合了多个 SDF 时,计算就会非常困难。另外,谁愿意针对每个 SDF 编写一个法向量函数?所以,我们还是需要一点小技巧:在目标点周围的每个轴上对 SDF 进行采样,并以此来估算法向量:

Sdf = typing.Callable[[float, float, float], float]def normal(sdf: Sdf, x: float, y: float, z: float) -> tuple[float, float, float]:# an arbitrary small amount to offset around the pointε = 0.001# calculate each axis independentlyn_x = sdf(x + ε, y, z) - sdf(x - ε, y, z)n_y = sdf(x, y + ε, z) - sdf(x, y - ε, z)n_z = sdf(x, y, z + ε) - sdf(x, y, z - ε)# normalize the result to length = 1norm = math.sqrt(n_x**2 + n_y**2 + n_z**2)return (n_x / norm, n_y / norm, n_z / norm)

为了理解该函数的原理,我们可以假设一种特殊情况:法向量的一个分量为 0,比如 x=0。这意味着,这个点上的 SDF 在 x 轴上是平的,也就是说 sdf(x + ε, y, z) == sdf(x - ε, y, z)。

随着这些值的发散,法向量的 x 分量会向正方向或负方向移动。这只是一个估算值,但对于渲染来说已经足够了,甚至一些高级演示也会使用这种方法。但这种方法的缺点是速度非常慢,因为每次调用都需要对 SDF 进行六次采样。随着场景 SDF 变得越来越复杂,性能就会出现问题。

不过,对我们来说这就足够了。如果光线命中,我们就在 sample 中计算法向量,并使用它来计算一些光照和纹理:

if d <= 0.01:_, nt_y, nt_z = normal(donut, t_x, y, t_z)is_lit = nt_y < -0.15is_frosted = nt_z < -0.5if is_frosted:return '@' if is_lit else '#'else:return '=' if is_lit else '.'

我们只关心法向量的 y 和 z 分量,并不在意 x 分量。我们使用 y 来计算光照,假设表面朝上(法向量的 y 接近 -1),则应该被照亮。我们使用 z 来计算糖霜材质,针对不同的值设定阈值,就可以调整甜甜圈的糖霜厚度。为了理解这些值的含义,你可以试试看修改如下代码:

import math, time, typingdef donut(x: float, y: float, z: float) -> float:radius = 0.4thickness = 0.3return math.sqrt((math.sqrt(x**2 + y**2) - radius)**2 + z**2) - thickness / 2Sdf = typing.Callable[[float, float, float], float]def normal(sdf: Sdf, x: float, y: float, z: float) -> tuple[float, float, float]:ε = 0.001n_x = sdf(x + ε, y, z) - sdf(x - ε, y, z)n_y = sdf(x, y + ε, z) - sdf(x, y - ε, z)n_z = sdf(x, y, z + ε) - sdf(x, y, z - ε)norm = math.sqrt(n_x**2 + n_y**2 + n_z**2)return (n_x / norm, n_y / norm, n_z / norm)def sample(x: float, y: float) -> str:z = -10for _step in range(30):θ = time.time() * 2t_x = x * math.cos(θ) - z * math.sin(θ)t_z = x * math.sin(θ) + z * math.cos(θ)d = donut(t_x, y, t_z)if d <= 0.01:_, nt_y, nt_z = normal(donut, t_x, y, t_z)is_lit = nt_y < -0.15is_frosted = nt_z < -0.5if is_frosted:return '@' if is_lit else '#'else:return '=' if is_lit else '.'else:z += dreturn ' 'while True:frame_chars = []for y in range(20):for x in range(80):remapped_x = x / 80 * 2 - 1remapped_y = (y / 20 * 2 - 1) * (2 * 20/80)frame_chars.append(sample(remapped_x, remapped_y))frame_chars.append('\n')print('\033[2J' + ''.join(frame_chars))time.sleep(1/30)

到这里,我们的三维甜甜圈就画好了,不仅做了光照和纹理处理,还可以不停地旋转,而且只用到了 46 行代码

相关推荐

Alist 玩家请进:一键部署全新分支 Openlist,看看香不香!

Openlist(其前身是鼎鼎大名的Alist)是一款功能强大的开源文件列表程序。它能像“万能钥匙”一样,解锁并聚合你散落在各处的云盘资源——无论是阿里云盘、百度网盘、GoogleDrive还是...

白嫖SSL证书还自动续签?这个开源工具让我告别手动部署

你还在手动部署SSL证书?你是不是也遇到过这些问题:每3个月续一次Let'sEncrypt证书,忘了就翻车;手动配置Nginx,重启服务,搞一次SSL得花一下午;付费证书太贵,...

Docker Compose:让多容器应用一键起飞

CDockerCompose:让多容器应用一键起飞"曾经我也是一个手动启动容器的少年,直到我的膝盖中了一箭。"——某位忘记--link参数的运维工程师引言:容器化的烦恼与...

申请免费的SSL证书,到期一键续签

大家好,我是小悟。最近帮朋友配置网站HTTPS时发现,还有人对宝塔面板的SSL证书功能还不太熟悉。其实宝塔早就内置了免费的Let'sEncrypt证书申请和一键续签功能,操作简单到连新手都能...

飞牛NAS部署TVGate Docker项目,实现内网一键转发、代理、jx

前面分享了两期TVGate:Q大的转发代理工具TVGate升级了,操作更便捷,增加了新的功能跨平台内网转发神器TVGate部署与使用初体验现在项目已经开源,并支持Docker部署,本文介绍如何通...

Docker Compose 编排实战:一键部署多容器应用!

当项目变得越来越复杂,一个服务已经无法满足需求时,你可能需要同时部署数据库、后端服务、前端网页、缓存组件……这时,如果还一个一个手动dockerrun,简直是灾难这就是DockerCompo...

深度测评:Vue、React 一键部署的神器 PinMe

不知道大家有没有这种崩溃瞬间:领导突然要看项目Demo,客户临时要体验新功能,自己写的小案例想发朋友圈;找运维?排期?还要走工单;自己买服务器?域名、SSL、Nginx、防火墙;本地起服务?断电、关...

超简单!一键启动多容器,解锁 Docker Compose 极速编排秘籍

想要用最简单的方式在本地复刻一套完整的微服务环境?只需一个docker-compose.yml文件,你就能一键拉起N个容器,自动组网、挂载存储、环境隔离,全程无痛!下面这份终极指南,教你如何用...

日志文件转运工具Filebeat笔记_日志转发工具

一、概述与简介Filebeat是一个日志文件转运工具,在服务器上以轻量级代理的形式安装客户端后,Filebeat会监控日志目录或者指定的日志文件,追踪读取这些文件(追踪文件的变化,不停的读),并将来自...

K8s 日志高效查看神器,提升运维效率10倍!

通常情况下,在部署了K8S服务之后,为了更好地监控服务的运行情况,都会接入对应的日志系统来进行检测和分析,比如常见的Filebeat+ElasticSearch+Kibana这一套组合...

如何给网站添加 https_如何给网站添加证书

一、简介相信大家都知道https是更加安全的,特别是一些网站,有https的网站更能够让用户信任访问接下来以我的个人网站五岁小孩为例子,带大家一起从0到1配置网站https本次配置的...

10个Linux文件内容查看命令的实用示例

Linux文件内容查看命令30个实用示例详细介绍了10个Linux文件内容查看命令的30个实用示例,涵盖了从基本文本查看、分页浏览到二进制文件分析的各个方面。掌握这些命令帮助您:高效查看各种文本文件内...

第13章 工程化实践_第13章 工程化实践课

13.1ESLint+Prettier代码规范统一代码风格配置//.eslintrc.jsmodule.exports={root:true,env:{node...

龙建股份:工程项目中标_龙建股份有限公司招聘网

404NotFoundnginx/1.6.1【公告简述】2016年9月8日公告,公司于2016年9月6日收到苏丹共和国(简称“北苏丹”)喀土穆州基础设施与运输部公路、桥梁和排水公司出具的中标通知书...

福田汽车:获得政府补助_福田 补贴

404NotFoundnginx/1.6.1【公告简述】2016年9月1日公告,自2016年8月17日至今,公司共收到产业发展补助、支持资金等与收益相关的政府补助4笔,共计5429.08万元(不含...

取消回复欢迎 发表评论: