¿Qué puedes hacer con WebGPU?

Rate this content
Bookmark

Una de las principales características nuevas que introduce WebGPU son los shaders de cómputo. Cubriré los conceptos básicos de cómo funcionan y repasaré algunas aplicaciones que antes no eran posibles en la web. Ejemplos incluyen las técnicas de renderizado basadas en cómputo de Unreal Engine 5 y simulaciones de partículas complejas.

9 min
07 Apr, 2022

Video Summary and Transcription

WebGPU es una próxima API web que proporciona acceso de bajo nivel a la GPU, ofreciendo un mejor rendimiento y habilitando nuevas técnicas de renderizado. Permite el uso de shaders de cómputo, que brindan un mayor control sobre la sincronización de memoria y el enhebrado, y se pueden utilizar para cálculos generales en una GPU. WebGPU abre posibilidades para efectos únicos en juegos y promete soporte futuro para trazado de rayos en navegadores.

Available in English

1. Introduction to WebGPU

Short description:

WebGPU es una próxima API web para acceder a bajo nivel a la GPU, proporcionando un acceso más directo y un mejor rendimiento. Permite nuevas técnicas y hace que las aplicaciones sean más futuras. Actualmente, se puede habilitar en Chrome o Firefox detrás de una bandera, y estará ampliamente disponible en Chrome en septiembre. Babylon, 3GS y Play Canvas son algunos de los motores que admiten WebGPU. La característica más significativa es Compute Shaders, que permiten la computación general en una GPU.

Hola a todos, y gracias por unirse a mí en esta sesión de ¿Qué puedes hacer con WebGPU? Mi nombre es Omar, trabajo como ingeniero gráfico en Snapchat. Actualmente estoy en Ithaca, Nueva York, y solía hacer juegos en Flash en el pasado.

Así que quiero hablar sobre WebGPU. ¿Qué es, cuál es su estado actual y cuándo estará ampliamente disponible? También quiero mostrar algunas de las cosas nuevas en WebGPU que puedes hacer con él y que no puedes hacer hoy. Además, quiero compartir un montón de enlaces y recursos para ayudarte a orientarte en la dirección correcta. También compartiré un enlace a estas diapositivas, porque tienen muchos enlaces. Así que los tendrás disponibles.

Entonces, ¿qué es WebGPU? Es una próxima API web para acceder a bajo nivel a la GPU. Básicamente, es el siguiente paso del sucesor de WebGL. A simple vista, la gran diferencia es que WebGPU te brinda un acceso más directo a la GPU. A diferencia de WebGL, que era más una abstracción alrededor de OpenGL, no se trataba tanto de cómo funciona el hardware. WebGPU es más una API gráfica moderna. Similar a cómo Vulkan, Metal y DirectX 12 funcionan, te brinda un control más directo sobre lo que el hardware puede hacer. En general, esto significa un mejor rendimiento. También puedes utilizar nuevas técnicas que de otra manera no estarían disponibles, de las cuales hablaré un poco más. Además, esto lo hace más a prueba de futuro, ya que significa que a medida que el hardware realice más funciones como el trazado de rayos, esas funciones se pueden exponer directamente en lugar de tener que crear una nueva capa de API envolvente para que los desarrolladores la utilicen. Esto es muy emocionante. En cuanto al estado actual, se puede utilizar. Se puede habilitar en Chrome o Firefox detrás de una bandera. También se puede utilizar a través de un ensayo de origen, lo que significa que te registras para obtener un token y luego tus usuarios pueden tener habilitado WebGPU en tu URL o dominio, por lo que no tienen que activar una bandera, y estará ampliamente disponible para todos en Chrome en septiembre. Algunos de los motores que lo admiten, Babylon es el más maduro que he visto. Todos estos enlaces llevan a páginas que explican cómo activar WebGPU en estos motores. 3GS, creo que tiene mucho soporte, pero aún no se ha lanzado oficialmente como parte de él, pero aún puedes usarlo hoy. Y luego Play Canvas está actualmente en desarrollo para admitir WebGPU. Los Compute Shaders son la característica más significativa. Esto significa que tienes la capacidad de escribir esencialmente una computación general en una GPU. En lugar de antes, si querías ejecutar cualquier cálculo en la GPU en la web, tenías que ejecutarlo a través de un fragment shader y luego ejecutar los resultados en una textura.

2. Benefits and Possibilities of WebGPU

Short description:

WebGPU ofrece un mejor rendimiento y permite nuevas técnicas de renderizado. Permite renderizar nubes de puntos más rápido utilizando compute shaders y saltándose el pipeline tradicional. Los compute shaders brindan un mayor control sobre la sincronización de memoria y el enhebrado. El enfoque del rasterizador de cómputo es más rápido para escribir elementos pequeños. WebGPU abre posibilidades para efectos únicos en juegos, como objetos deformables en tiempo real. También promete soporte futuro para trazado de rayos en navegadores. Consulta el foro oficial de GitHub de WebGPU para obtener más información y recursos.

Y luego algo más tendría que leer esa textura. Así que eso fue un poco molesto. Entonces esto es simplemente más fácil, pero también podría ser mucho más rápido porque al hacer esto tienes mucho más control sobre la sincronización de memoria y el enhebrado aquí.

Un ejemplo aquí es el renderizado de nubes de puntos. Las nubes de puntos son, en lugar de una malla 3D hecha de triángulos, simplemente millones o a veces miles de millones de puntos. Este es un artículo que habla sobre cómo obtener un renderizado significativamente más rápido utilizando un compute shader en lugar del pipeline tradicional. Puedes ver aquí abajo a la izquierda, con el Vertex y FractShader, obtienes 10 FPS en esta escena y con el compute obtienes alrededor de 300 FPS. Esa es una gran diferencia. Básicamente, lo que están haciendo aquí es saltarse el pipeline de Vertex y Fract. Su compute shader toma los vértices como un búfer y luego escribe los píxeles en otro búfer, los datos de color, y luego se renderiza en la pantalla con un FractShader. Y una técnica interesante que puedes hacer aquí que de otra manera no podrías hacer, como con un FractShader regular, es que como tienen muchos puntos que se renderizan en el mismo píxel, en lugar de mostrar solo el más cercano a la cámara, promedian los colores para hacerlo... En cierto modo, te muestra lo que hay dentro si tienes una nube de puntos compleja que describe un volumen. Y así promedian todos los puntos. Esto es algo que podemos hacer porque tenemos control total sobre cómo se sincronizan los hilos cuando todos escriben en el mismo píxel, pero no es algo sobre lo que tengamos mucho control en un FractShader. Y la otra razón por la que es muy rápido es porque, en general, si estás escribiendo cosas muy pequeñas, como puntos o cuadrados muy pequeños, un enfoque de rasterizador de cómputo será mucho más rápido. Y esto es algo que utiliza Unreal Engine 5's Nanite para acelerar el renderizado, como con triángulos muy pequeños. Y también escribí esto, cómo construir un rasterizador de cómputo, WebGPU, si te interesa cómo funciona esto. Y es una buena manera de comenzar a aprender tanto WebGPU como esta técnica, cómo funciona y por qué puede ser más rápido.

Aquí hay algunos videos de adelanto para mostrarte cuánto control tenemos una vez que construimos algo como esto. Aquí y puede que no se vea muy claro en la pantalla aquí, pero lo que estoy haciendo es cambiar entre sombreado suave y sombreado plano en triángulos individuales a medida que el modelo se mueve hacia adelante y hacia atrás. Normalmente, esto es algo que puedes cambiar en todo el modelo, pero porque en este asterisco de computación controlamos un pipeline completo, puedo cambiar triángulos individuales de suave a plano dinámicamente, o un efecto interesante es incluso tenerlo. Entonces, cuando pasas el mouse por encima o tocas diferentes partes del modelo, pasan de suave a plano, lo que crea un efecto realmente único, creo. Y este es otro que visualiza el orden en el que se dibujan los triángulos, lo cual nuevamente no es algo que normalmente puedas hacer, pero con el pipeline de cómputo, porque tenemos control total sobre él, podemos ver eso. Y más comúnmente tendrás simulaciones de partículas, por lo que nuevamente esto es algo que hoy tal vez harías en la CPU, o si lo haces en las GPU a través de un Frac shader. Pero aquí puedes hacerlo directamente en un compute shader, lo que será más fácil, pero potencialmente también más rápido. Y finalmente, esto es realmente emocionante porque hay muchos juegos que utilizan este tipo de técnicas, no solo para velocidad sino también para crear efectos muy únicos. Como aquí, este es un juego llamado Claybook, donde todo se renderiza utilizando campos de distancia asignados, lo que hace que todo sea deformable en tiempo real, lo cual es realmente genial y muy único. Y hoy en día no puedes hacer esto en la web, pero con WebGPU, cosas como esta serán posibles, lo cual me emociona mucho. Y hay un enlace a la charla donde hablan sobre Claybook y cómo se hizo utilizando estas técnicas aquí. No utilizando WebGPU, pero la técnica de cómputo en general. Entonces, para resumir, lo que WebGPU promete principalmente es un mejor rendimiento, pero también la capacidad de explorar nuevas técnicas de renderizado y tal vez en el futuro, no hoy, pero no soportado hoy, en el futuro, algo como el soporte para trazado de rayos podría llegar al navegador, lo cual sería enorme.

Muchas gracias, y aquí hay enlaces y recursos, el más importante que quiero señalar es el foro oficial de GitHub de WebGPU. Aquí es donde escriben la especificación y los desarrolladores que trabajan en ella son muy amables al responder preguntas y están disponibles para responder cosas. Así que es un buen lugar para aprender, y he aprendido mucho de eso, y también he vinculado el tutorial que escribí sobre cómo crear un rasterizador de cómputo aquí. Muchas gracias. ♪♪

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
Top Content
React is a library for "rendering" UI from components, but many users find themselves confused about how React rendering actually works. What do terms like "rendering", "reconciliation", "Fibers", and "committing" actually mean? When do renders happen? How does Context affect rendering, and how do libraries like Redux cause updates? In this talk, we'll clear up the confusion and provide a solid foundation for understanding when, why, and how React renders. We'll look at: - What "rendering" actually is - How React queues renders and the standard rendering behavior - How keys and component types are used in rendering - Techniques for optimizing render performance - How context usage affects rendering behavior| - How external libraries tie into React rendering
React Summit 2023React Summit 2023
32 min
Speeding Up Your React App With Less JavaScript
Top Content
Too much JavaScript is getting you down? New frameworks promising no JavaScript look interesting, but you have an existing React application to maintain. What if Qwik React is your answer for faster applications startup and better user experience? Qwik React allows you to easily turn your React application into a collection of islands, which can be SSRed and delayed hydrated, and in some instances, hydration skipped altogether. And all of this in an incremental way without a rewrite.
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
Top Content
React 18! Concurrent features! You might’ve already tried the new APIs like useTransition, or you might’ve just heard of them. But do you know how React 18 achieves the performance wins it brings with itself? In this talk, let’s peek under the hood of React 18’s performance features: - How React 18 lowers the time your page stays frozen (aka TBT) - What exactly happens in the main thread when you run useTransition() - What’s the catch with the improvements (there’s no free cake!), and why Vue.js and Preact straight refused to ship anything similar
JSNation 2022JSNation 2022
21 min
The Future of Performance Tooling
Top Content
Our understanding of performance & user-experience has heavily evolved over the years. Web Developer Tooling needs to similarly evolve to make sure it is user-centric, actionable and contextual where modern experiences are concerned. In this talk, Addy will walk you through Chrome and others have been thinking about this problem and what updates they've been making to performance tools to lower the friction for building great experiences on the web.
JS GameDev Summit 2022JS GameDev Summit 2022
33 min
Building Fun Experiments with WebXR & Babylon.js
Top Content
During this session, we’ll see a couple of demos of what you can do using WebXR, with Babylon.js. From VR audio experiments, to casual gaming in VR on an arcade machine up to more serious usage to create new ways of collaboration using either AR or VR, you should have a pretty good understanding of what you can do today.
Check the article as well to see the full content including code samples: article. 

Workshops on related topic

React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
JSNation 2023JSNation 2023
116 min
Make a Game With PlayCanvas in 2 Hours
Featured WorkshopFree
In this workshop, we’ll build a game using the PlayCanvas WebGL engine from start to finish. From development to publishing, we’ll cover the most crucial features such as scripting, UI creation and much more.
Table of the content:- Introduction- Intro to PlayCanvas- What we will be building- Adding a character model and animation- Making the character move with scripts- 'Fake' running- Adding obstacles- Detecting collisions- Adding a score counter- Game over and restarting- Wrap up!- Questions
Workshop levelFamiliarity with game engines and game development aspects is recommended, but not required.
JSNation 2023JSNation 2023
170 min
Building WebApps That Light Up the Internet with QwikCity
Featured WorkshopFree
Building instant-on web applications at scale have been elusive. Real-world sites need tracking, analytics, and complex user interfaces and interactions. We always start with the best intentions but end up with a less-than-ideal site.
QwikCity is a new meta-framework that allows you to build large-scale applications with constant startup-up performance. We will look at how to build a QwikCity application and what makes it unique. The workshop will show you how to set up a QwikCitp project. How routing works with layout. The demo application will fetch data and present it to the user in an editable form. And finally, how one can use authentication. All of the basic parts for any large-scale applications.
Along the way, we will also look at what makes Qwik unique, and how resumability enables constant startup performance no matter the application complexity.
React Day Berlin 2022React Day Berlin 2022
53 min
Next.js 13: Data Fetching Strategies
Top Content
WorkshopFree
- Introduction- Prerequisites for the workshop- Fetching strategies: fundamentals- Fetching strategies – hands-on: fetch API, cache (static VS dynamic), revalidate, suspense (parallel data fetching)- Test your build and serve it on Vercel- Future: Server components VS Client components- Workshop easter egg (unrelated to the topic, calling out accessibility)- Wrapping up
JS GameDev Summit 2022JS GameDev Summit 2022
121 min
PlayCanvas End-to-End : the quick version
Top Content
WorkshopFree
In this workshop, we’ll build a complete game using the PlayCanvas engine while learning the best practices for project management. From development to publishing, we’ll cover the most crucial features such as asset management, scripting, audio, debugging, and much more.
React Advanced Conference 2023React Advanced Conference 2023
148 min
React Performance Debugging
Workshop
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)