Inferno

Inferno

SwiftUI开源GPU图形特效库

Inferno是一个为SwiftUI设计的开源Fragment Shader集合。它提供水波纹、黑洞、闪光等GPU加速视觉效果,代码易读易懂。项目包含iOS和macOS示例应用。开发者只需复制相关Metal文件即可使用这些特效,简化SwiftUI应用的视觉设计。适用于iOS 17.0+和macOS 14.0+。

SwiftUIInfernoMetalshaderGPUGithub开源项目
<p align="center"> <img src="https://www.hackingwithswift.com/files/inferno/inferno-logo.png" alt="Inferno logo" width="272" height="272" /> </p> <p align="center"> <img src="https://img.shields.io/badge/iOS-17.0+-blue.svg" /> <img src="https://img.shields.io/badge/macOS-14.0+-brightgreen.svg" /> <img src="https://img.shields.io/badge/MSL-3.1-orange.svg" /> <img src="https://img.shields.io/badge/Swift-5.9-ff69b4.svg" /> <a href="https://twitter.com/twostraws"> <img src="https://img.shields.io/badge/Contact-@twostraws-lightgrey.svg?style=flat" alt="Twitter: @twostraws" /> </a> </p>

Inferno is an open-source collection of fragment shaders designed for SwiftUI apps. The shaders are designed to be easy to read and understand, even for relative beginners, so you’ll find each line of code rephrased in plain English as well as an overall explanation of the algorithm used at the top of each file.

If you’re already comfortable with shaders then please download one or more that interest you and get going. If not, most of the remainder of this README acts as a primer for using shaders in SwiftUI.

See it in action

This repository contains a cross-platform sample project demonstrating all the shaders in action. The sample project is built using SwiftUI and requires iOS 17 and macOS 14.

The sample project contains a lot of extra helper code to demonstrate all the shaders in various ways. To use the shaders in your own project, you just need to copy the relevant Metal files across, and optionally also Transitions.swift if you're using a transition shader.

The Inferno Sandbox app demonstrating the simple loupe shader.

How to use Inferno in your project

If you use SwiftUI, you can add special effects from Inferno to add water ripples, spinning black holes, flashing lights, embossing, noise, gradients, and more – all done on the GPU for maximum speed.

To use a shader from here, copy the appropriate .metal file into your project, then start with sample code for that shader shown below. If you're using an Inferno transition, you should also copy Transitions.swift to your project.

To find out more, click below to watch my YouTube video about building shaders for use with SwiftUI.

Video: SwiftUI + Metal – Learn to build your own shaders

What are shaders?

<details> <summary> Details (Click to expand) </summary>

Fragment shaders are tiny programs that operate on individual elements of a SwiftUI layer. They are sometimes called “pixel shaders” – it’s not a wholly accurate name, but it does make them easier to understand.

Effectively, a fragment shader gets run on every pixel in a SwiftUI view, and can transform that pixel however it wants. That might sound slow, but it isn’t – all the fragment shaders here run at 60fps on all phones that support iOS 17, and 120fps on all ProMotion devices.

The transformation process can recolor the pixel however it wants. Users can customize the process by passing various parameters into each shader, and SwiftUI also provides some values for us to work with, such as the coordinate for the pixel being modified and its current color.

</details>

How are shaders written?

<details> <summary> Details (Click to expand) </summary>

Shaders are written in the Metal Shading Language (MSL), which is a simple, fast, and extremely efficient language based on C++ that is optimized for high-performance GPU operations. Metal shaders are compiled at build-time and linked into a .metallib file. When you activate a shader in your app, the corresponding Metal function is loaded from the metallib and is then used to create a program to be executed on the GPU.

SwiftUI is able to work with a variety of Metal shaders, depending on what kind of effect you're trying to create.

MSL comes with a wide variety of built-in data types and functions, many of which operate on more than one data types. The data types used in Inferno are nice and simple:

  • bool: A Boolean, i.e. true or false.
  • float: A floating-point number.
  • float2: A two-component floating-point vector, used to hold things like X and Y coordinates or width and height.
  • half: A half-precision floating-point number.
  • half2: A two-component half-precision floating-point number.
  • half3: A three-component floating-point vector, used to hold RGB values.
  • half4: A four-component floating-point vector, used to hold RGBA values.
  • uint2: A two-component integer vector, used to hold X and Y coordinates or width and height.

Shaders commonly move fluidly between float, float2, half3, and half4 as needed. For example, if you create a half4 from a float then the number will just get repeated for each component in the vector. You’ll also frequently see code to create a half4 by using a half3 for the first three values (usually RGB) and specifying a fourth value as a float. Converting between half and float is free.

Be mindful when choosing the type of your variables: the GPU is heavily optimized for performing floating-point operations, and (especially on iOS), half-precision floating-point operations. That means you should prefer to use the half data types whenever the precision requirements allow it. This will also save register space and increase the so-called "occupancy" of the shader program, effectively letting more GPU cores run your shader simultaneously. Check out the Learn performance best practices for Metal shaders tech talk for more details.

Also, be careful with scalar numbers in your shader code. Make sure to use the correct type of number for an operation. For example, float y = (x - 1) / 2 works, but 1 and 2 are int here and are needlessly converted to float at runtime. Instead, write float y = (x - 1.0) / 2.0. Number literals for the corresponding types look like this:

  • float: 0.5, 0.5f, or 0.5F
  • half: 0.5h or 0.5H
  • int: 42
  • uint: 42u or 42U

Here are the functions used in Inferno:

  • abs() calculates the absolute value of a number, which is its non-negative value. So, positive values such as 1, 5, and 500 remain as they are, but negative values such as -3 or -3000 have their signs removed, making them 3 or 3000. If you pass it a vector (e.g. float2) this will be done for each component.
  • ceil() rounds a number up to its nearest integer. If you pass it a vector (e.g. float2) this will be done for each component.
  • cos() calculates the cosine of a value in radians. The cosine will always fall between -1 and 1. If you provide cos() with a vector (e.g. vec3) it will calculate the cosine of each component in the vector and return a vector of the same size containing the results.
  • distance() calculates the distance between two values. For example, if you provide it with a pair vec2 you’ll get the length of the vector created by subtracting one from the other. This always returns a single number no matter what data type you give it.
  • dot() calculates the dot product of two values. This means multiplying each component of the first value by the respective component in the second value, then adding the result.
  • floor() rounds a number down to its nearest integer. If you pass it a vector (e.g. float2) this will be done for each component.
  • fmod() calculates the remainder of a division operation. For example, fmod(10.5, 3.0) is 1.5.
  • fract() returns the fractional component of a value. For example, fract(12.5) is 0.5. If you pass this a vector then the operation will be performed component-wise, and a new vector will be returned containing the results.
  • min() is used to find the lower of two values. If you pass vectors, this is done component-wise, meaning that the resulting vector will evaluate each component in the vector and place the lowest in the resulting vector.
  • max() is used to find the higher of two values. If you pass vectors, this is done component-wise, meaning that the resulting vector will evaluate each component in the vector and place the highest in the resulting vector.
  • mix() smooth interpolates between two values based on a third value that’s specified between 0 and 1, providing a linear curve.
  • pow() calculates one value raised to the power of another, for example pow(2.0, 3.0) evaluates to 2 * 2 * 2, giving 8. As well as operating on a float, pow() can also calculate component-wise exponents – it raises the first item in the first vector to the power of the first item in the second vector, and so on.
  • sin() calculates the sine of a value in radians. The sine will always fall between -1 and 1. If you provide sin() with a vector (e.g. float2) it will calculate the sine of each component in the vector and return a vector of the same size containing the results.
  • smoothstep() interpolates between two values based on a third value that’s specified between 0 and 1, providing an S-curve shape. That is, the interpolation starts slow (values near 0.0), picks up speed (values near 0.5), then slows down towards the end (values near 1.0).
  • sample() provides the color value of a SwiftUI layer at a specific location. This is most commonly used to read the current pixel’s color.

More about all of this can be found in the Metal Shading Language Specification.

</details>

Sending values to shaders

<details> <summary> Details (Click to expand) </summary>

Many shaders can operate without any special input from the user – it can manipulate the data it was sent by SwiftUI, then send back new data.

Because SwiftUI uses dynamic member lookup to find shader functions at runtime, this means a simple shader can be applied like this:

Image(systemName: "figure.walk.circle")
    .font(.system(size: 300))
    .colorEffect(
        ShaderLibrary.yourShaderFunction()
    )

However, often you’ll want to customize the way shaders work, a bit like passing in parameters to a function. Shaders are a little more complicated because these values need to be uploaded to the GPU, but the principle is the same.

SwiftUI handles this data transfer using helper methods that convert common Swift and SwiftUI data types to their Metal equivalents. For example, if you want to pass a Float, CGFloat, or Double from Swift to Metal, you'd do this:

Image(systemName: "figure.walk.circle")
    .font(.system(size: 300))
    .colorEffect(
        ShaderLibrary.yourShaderFunction(
            .float(someNumber)
        )
    )

SwiftUI provides three modifiers that let us apply Metal shaders to view hierarchies. Each one provides different input to your shader function, but each can also accept any number of further values to customize the way your shader works.

  • The colorEffect() modifier passes in the current pixel's position in user space (i.e., based on the actual size of your layer, measured in points), and its current color.
  • The distortionEffect() modifier passes in just the current pixel's position in user space.
  • The layerEffect() modifier passes in the current pixel's position in user space, and also the SwiftUI layer itself so you can read values from there freely.

In the documentation below, shader parameters are listed without the ones SwiftUI passes in automatically – you just see the ones you actually need to pass yourself.

Tip: When writing more complex shaders, you'll often find yourself needing to optimize your code for maximum efficiency. One of the best places to start with this is by looking into shader uniforms: rather than calculating a value that is the same for every fragment inside a shader, instead precompute values on the CPU and pass them directly into the shader. This means such calculations are done once per draw, rather than once per fragment.

</details>

Reading the shader code

<details> <summary> Details (Click to expand) </summary>

All the shaders in Inferno were specifically written for readability. Specifically, they:

  1. Start with a brief comment outlining what each shader does.
  2. List all input parameters (where they are used), along with ranges and a suggested starting point.
  3. Have an explanation of the algorithm used.
  4. Provide detailed line-by-line English translations of what the code means.

The combination of what the code does (the interlinear comments) and what the code means (the algorithm introduction) should hopefully make these shaders comprehensible to everyone.

One small note: you will commonly see final color values multiplied by the original color’s alpha, just to make sure we get very smooth edges where this is transparency.

</details>

Shaders included in Inferno

<details> <summary> Details (Click to expand) </summary>

Inferno provides a selection of shaders, most of which allow some customization using input parameters.

Animated Gradient Fill

<details> <summary> Details (Click to expand) </summary>

An animated gradient fill shader.

A colorEffect() shader that generates a constantly cycling color gradient, centered on the input view.

Parameters:

  • size: The size of the whole image, in user-space.
  • time: The number of elapsed seconds since the shader was created.

Example code:

struct ContentView: View { @State private var startTime = Date.now var body: some View { TimelineView(.animation) { timeline in let elapsedTime = startTime.distance(to: timeline.date) Image(systemName: "figure.walk.circle") .font(.system(size: 300)) .visualEffect { content, proxy in content .colorEffect( ShaderLibrary.animatedGradientFill( .float2(proxy.size), .float(elapsedTime) ) ) } } } }
</details>

Checkerboard

<details> <summary> Details (Click to expand) </summary>

A checkerboard shader.

A colorEffect() shader that replaces the current image with a checkerboard pattern, flipping between the original color and a replacement.

Parameters:

  • replacement: The replacement color to be used for checkered squares.
  • size: The size of the checker squares.

Example code:

Image(systemName: "figure.walk.circle") .font(.system(size: 300)) .colorEffect( ShaderLibrary.checkerboard( .color(.red), .float(50) ) )
</details>

Circle Wave

<details> <summary> Details (Click to expand) </summary>

A circle wave shader.

A colorEffect() shader that generates circular waves moving out or in, with varying size, brightness, speed, strength, and more.

Parameters:

  • size: The size of the whole image, in user-space.
  • time: The number of elapsed seconds since the shader was created.
  • brightness: How bright the colors should be. Ranges from 0 to 5 work best; try starting with 0.5 and experiment.
  • speed: How fast the wave should travel. Ranges from -2 to 2 work best, where negative numbers cause waves to come inwards; try starting with 1.
  • strength: How intense the waves should be. Ranges from 0.02 to 5 work best; try starting with 2.
  • density: How large each wave should be. Ranges from 20 to 500 work best; try starting with 100.
  • center: The center of the effect, where 0.5/0.5 is dead center
  • circleColor: The color to use for the waves. Use darker colors to create a less intense core.

Example code:

struct ContentView: View { @State private var startTime = Date.now var body: some View { TimelineView(.animation) { timeline in let elapsedTime = startTime.distance(to: timeline.date) Image(systemName: "figure.walk.circle") .font(.system(size: 300)) .padding() .drawingGroup() .visualEffect { content, proxy in content .colorEffect( ShaderLibrary.circleWave( .float2(proxy.size), .float(elapsedTime), .float(0.5), .float(1), .float(2), .float(100), .float2(0.5, 0.5), .color(.blue)

编辑推荐精选

扣子-AI办公

扣子-AI办公

职场AI,就用扣子

AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!

堆友

堆友

多风格AI绘画神器

堆友平台由阿里巴巴设计团队创建,作为一款AI驱动的设计工具,专为设计师提供一站式增长服务。功能覆盖海量3D素材、AI绘画、实时渲染以及专业抠图,显著提升设计品质和效率。平台不仅提供工具,还是一个促进创意交流和个人发展的空间,界面友好,适合所有级别的设计师和创意工作者。

图像生成AI工具AI反应堆AI工具箱AI绘画GOAI艺术字堆友相机AI图像热门
码上飞

码上飞

零代码AI应用开发平台

零代码AI应用开发平台,用户只需一句话简单描述需求,AI能自动生成小程序、APP或H5网页应用,无需编写代码。

Vora

Vora

免费创建高清无水印Sora视频

Vora是一个免费创建高清无水印Sora视频的AI工具

Refly.AI

Refly.AI

最适合小白的AI自动化工作流平台

无需编码,轻松生成可复用、可变现的AI自动化工作流

酷表ChatExcel

酷表ChatExcel

大模型驱动的Excel数据处理工具

基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。

AI工具酷表ChatExcelAI智能客服AI营销产品使用教程
TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
AIWritePaper论文写作

AIWritePaper论文写作

AI论文写作指导平台

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

AI辅助写作AI工具AI论文工具论文写作智能生成大纲数据安全AI助手热门
博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。

AI办公办公工具AI工具博思AIPPTAI生成PPT智能排版海量精品模板AI创作热门
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

下拉加载更多