3D Web Programming

Fivos DOGANIS

whoami

💼 linkedin.com/in/fivosdoganis
📧 fivos.doganis@gmail.com
🐦 @fdoganis

University of Hull

  • Master of Science by Research (2001)
    Augmented Reality in Archaeology: Registration Issues

IRCAD (2002 - 2003)

  • Institut de Recherche contre les Cancers de l'Appareil Digestif
  • Startup
    • Virtual-Surg team
  • Augmented Reality Research Engineer

Dassault Systèmes (2003+)

  • 3D Visualization Engineer
    • Scenegraph
    • Materials
    • Geometry, Tessellation
  • Virtual and Augmented Reality (XR) Engineer
  • XR Research Engineer
  • XR Research Manager

Dassault Systèmes

From Shape to Life

Course audience

  • Computer Science students learning Computer Graphics, Physics or Machine Learning
    • and who are afraid to ask "what's a GPU?", "what's a shader?"
  • Web designers wishing to add 3D graphics to their sites
  • Game developers wishing to conquer the Web
  • Anyone looking for a simple introduction to 3D
    • and who has no clue where to start

➡️ Feel free to skim through technical sections and use this course as future reference

Course prerequisites

We'll start from scratch but these should help:

  • Math
  • Programming
    • JavaScript notions, or any similar language (HTML kept minimal)
  • 3D API
    • OpenGL, DirectX, Metal
  • 3D Software (Blender, Unity, Unreal Engine, Godot Engine)

Course contents

  • Demo
    • Existing 3D Web Apps
  • Theory
    • A brief history of 3D on the Web
    • Concepts: Architecture, Pipeline, APIs
  • Practice
    • 3D Web Programming
      • WebGL, THREE.js
      • Other APIs

📅 Planning

  • Day 1 (6 hours)

    • 📖 Theory
    • 💻 WebGL exercises
    • 🍜 Lunch
    • 🎮 THREE.js Theory + full exercise
    • ⚗️ Explore examples + choose a personal project
  • Day 2 (6 hours)

    • 🖊️ Evaluation: Quizz 20 questions / ~20 min
    • ⭐ Personal project / game jam ➡️ bonus points!

Project evaluation criteria

Bonus points for:

  • originality 👀
  • interactions 👋
  • physics 💥 / animations 🏃 / sounds 🎶 / eye-candy 🎆
  • GIS 🌍
  • code quality ✨, tricks 😏, performance ⏱️
  • fun 🎉

3D Web Apps

  • Games
  • e-Commerce
  • 3D content creation
  • 3D data exploration
  • Interactive art

Minecraft Classic

Aviator

Heraclos, (Gobelins)

Blob Opera (Google)

Apple iPhone Studio

BMW

OUIGO

SculptGL

3D Sculptor (Dassault Systèmes)

OnShape (PTC)

SketchFab (Epic)

Zygote Body

NASA

iTowns (IGN)

The Cursed Library

History

The past, present and future of Web 3D

"Dis Papy, c'était comment la 3D avant?"

Prehistory (1983 - 1993)

  • Silicon Graphics (SGI) hardware only
    • IRIX OS
  • IRIS GL (1983)
    • API close to hardware
  • IRIS Inventor (1988)
  • OpenGL 1.0 (1993)
    • Open API, Multi-OS

Fixed Pipeline (1993 - 2004)

  • 3dfx Glide API (1996)
    • Voodoo: "hardware 3D acceleration" for all
  • Microsoft Direct X API (1997)
    • Windows-only ☹️
  • OpenGL ES (2004)
  • OpenGL 2.0 (2004)
  • Foundation of nVIDIA (1993)

  • NV1 in SEGA Saturn (1994)

  • GeForce 256 (1999)

    • democratizes the GPU: Graphics Processing Unit, Transform & Ligthing
  • GeForce 3 (2001): NV2A in Microsoft's Xbox, programmable shading

Other players

  • SGI + Nintendo: Project Reality / N64 (1996)
    • SGI ends in 2006 💀

  • Imagination Technologies (PowerVR GPU) + Sega: Dreamcast (1998)

  • Intel i740 (1998) : OS in 3D

  • ATI (AMD) + Nintendo: Gamecube (2001)

Shaders, Mobile, Web (2004+)

  • OpenGL ES 2.0 (2007)
    • Mobile subset with shaders
  • Canvas 3D (2007), WebGL ancestor
  • WebGL 1.0 (2011) ⭐ 🎉
    • OpenGL ES 2.0 functionality for the Web!
  • OpenGL ES 3.0 (2012), 3.1 (2014): not for Apple 😢
  • WebGL 2.0 (2017)
    • OpenGL ES 3.0 exposed to the Web

Before WebGL, you couldn’t really do 3D on the web at all.
There was powerful 3D hardware everywhere on both desktops and mobile phones, but the web couldn’t tap into any of it.
There were some plugins, but users had to do an extra installation step that was a huge obstacle to adoption.
All the browser vendors knew that this was a challenge that needed to be resolved, which is why we came together as a Khronos Working Group.

Vladimir Vukićević (WebGL creator, WebVR guru)

WebGL architecture: software stack

  • Code: HTML + CSS + JS
    • JS code inside the web page makes WebGL API calls
  • Browser:
    • browser interprets JS code (using JS Engine)
    • turns WebGL calls into OpenGL calls (binding)
  • OS + Driver: converts OpenGL calls to
    • DirectX calls on Windows, Metal on Apple (using ANGLE)
    • OpenGL or OpenGL ES calls on other OSes
  • CPU + GPU: run the hardware accelerated code!

Binding example: from JS to C++

gl.drawElements(primitiveType, count, indexType, offset);
JSValue JSCanvasRenderingContext3D::glDrawElements(JSC::ExecState* exec, JSC::ArgList const& args)
{
    unsigned mode = args.at(0).toInt32(exec);
    unsigned type = args.at(1).toInt32(exec);
    
    unsigned int count = 0;
    
    // If the third param is not an object, it is a number, which is the count.
    // In this case if there is a 4th param, it is the offset. If there is no
    // 4th param, the offset is 0
    if (!args.at(2).isObject()) {
        count = args.at(2).toInt32(exec);
        unsigned int offset = (args.size() > 3) ? args.at(3).toInt32(exec) : 0;
        impl()->glDrawElements(mode, count, type, (void*) offset);
    } else {

Impact of stack on performance

  • Interpreted JS code is ~10x slower than native code
    • unless you use WebAssembly ("only" 2x slower than native)
  • On mobile devices, native code is ~10x slower than on desktop
  • Performance tips
    • reduce processing in JS code, let the shaders do the hard work
    • once shaders are compiled and rendering data is on the GPU, the code runs at near native speeds
    • GPU memory is limited: use Draco geometry compression, and Basis GPU texture compression

Evolution

The end of an API?

Evolution issues

  • New hardware, new needs since 1993
    • mobiles, wearables 📱 ⌚ 🕶️
    • embedded systems, AI, Vision 🚗 🚀
  • API has become more and more complex
    • coding fast and bug-free drivers is hard
    • OpenGL extensions are not universal
    • API subset needed to deprecate old and slow APIs
  • ➡️ New API needed, and it should be
    • low-level, universal, fast and abstract

But do we really need a new API?

API Fragmentation 💥

  • Proprietary API proliferation ➡️ no portability 😦
    • close to the GPU ➡️ fast
    • new ➡️ "clean"
  • Direct X 12 (Microsoft) : Windows, Xbox
  • Mantle (AMD) transferred to Khronos to become Vulkan
    • new open low-level standard ⭐
  • Metal (Apple)
    • looks like Vulkan, Metal was created first

Can we reunite all these new APIs?

Which common subset to use?

WebGL Next == WebGPU ?

  • Apple's "WebMetal", API similar to Metal
  • API partially reused and renamed WebGPU
    • temporary name, API still being defined
    • both low-level and object-oriented (no global state!)
    • fast
    • subset for web AND native, despite the "web" in the name
      • a bit like "Vulkan ES" / "Metal ES"
  • Might replace WebCL (Compute Shaders), abandoned 😢
  • Compatible with WebAssembly

All this is so confusing, which API should I actually use ⁉️

Well...

We hope for universal availability of WebGL 2.0 soon. If you need to ship your product today, WebGL 2.0 is the way to go. WebGL will be supported indefinitely. You do not need to worry about it going away.

WebGPU's timeline is discussed in the answer to the previous question. WebXR and WebAR are already working on WebGPU integration.

Khronos WebGL meetup, November 18, 2020

WebGL 2.0 can now be considered universally available across browsers, operating systems and devices.
As an application author, you can target WebGL 2.0 with confidence.
We encourage you to migrate to WebGL 2.0
It's no longer necessary to maintain a WebGL 1.0 fallback path unless you need to reach absolutely every device.
In particular, older Windows machines and Android devices.

WebGPU standardization continues; conformance testing in high gear
Aiming to reach 1.0 in 2022 Q2 (spec and conformance tests).

Khronos WebGL + WebGPU meetup, January 25, 2022

https://caniuse.com/webgl

WebGL 1.0 ✅

➡️ available everywhere! 🎉

https://caniuse.com/webgl2 [november 2022]

WebGL 2.0 ⚠️

➡️ official, you can start coding with it! (check availability)

  • retrocompatibility: WebGL 1.0 works in a WebGL 2.0 context
  • WebGL 1.0 polyfill to support a subset of WebGL 2.0 (⚠️ shaders)
  • you should learn WebGL 1 to understand existing code.

WebGL 2.0 on iOS

➡️ Test WebGL 2 support here:

WebGL 2.0 : standardized extensions

    Depth Textures (WEBGL_depth_texture)
    Floating Point Textures (OES_texture_float/OES_texture_float_linear)
    Half Floating Point Textures (OES_texture_half_float/OES_texture_half_float_linear)
    Vertex Array Objects (OES_vertex_array_object)
    Standard Derivatives (OES_standard_derivatives)
    Instanced Drawing (ANGLE_instanced_arrays)
    UNSIGNED_INT indices (OES_element_index_uint)
    Setting gl_FragDepth (EXT_frag_depth)
    Blend Equation MIN/MAX (EXT_blend_minmax)
    Direct texture LOD access (EXT_shader_texture_lod)
    Multiple Draw Buffers (WEBGL_draw_buffers)
    Texture access in vertex shaders

➡️ when WebGL 2.0 is not supported, we can get close to it using WebGL 1.0 + these extensions!

WebGL 1.0.1 ✅

WebGL 1.0.1 == WebL 1.0 + omnipresent extensions

ANGLE_instanced_arrays
EXT_blend_minmax
OES_element_index_uint
OES_standard_derivatives
OES_vertex_array_object // use it!
WEBGL_debug_renderer_info
WEBGL_lose_context

➡️ always available, use them!

WebGL 1.0.2 ✅

WebGL 1.0.2 == WebL 1.0.1 + omnipresent extensions (since 2021)

EXT_texture_filter_anisotropic
OES_texture_float
OES_texture_float_linear
OES_texture_half_float
OES_texture_half_float_linear
WEBGL_depth_texture 

➡️ always available, use them!

WebGL 1.0.3 ⚠️

WebGL 1.0.3 == WebL 1.0.2 + omnipresent extensions (since 2022):

EXT_shader_texture_lod
EXT_sRGB
EXT_frag_depth
WEBGL_draw_buffers 

➡️ check availability before use

WebGL 2.0 extensions ⚠️

WebGL 2.0 omnipresent extensions since 2022:

EXT_texture_filter_anisotropic
OES_texture_float_linear
WEBGL_debug_renderer_info
WEBGL_lose_context 
EXT_color_buffer_float

➡️ check availability before use

⚠️ Available != no bugs

#WebGL2 is a rubbish job on #IOS14. On Ipad pro more than half of the conformance tests fail ( 153553 over 260803 - tested here: https://khronos.org/registry/webgl/sdk/tests/webgl-conformance-tests.html). For GPGPU I still use WebGL1 for IOS devices.

@xavierbourry, July 2020

WebGPU (reminders)

➡️ probably the future Web 3D API, keep an eye on it! 👀

Conclusion: which API should I use?

  • 1️⃣ Start with WebGL 1.0, many exampled (13-year-old API!)
    • to understand the concepts
      • state machine, pipeline, buffers, shaders
      • see OpenGL course!
    • and how WebGL interacts with a web page
      • see HTML / JavaScript / CSS course
  • 2️⃣ Check new features introduced in WebGL 2.0
  • 3️⃣ Use high-level APIs: THREE.js, Babylon, A-Frame etc.
    • for a smooth transition to WebGPU!

WebGL

Concepts

Concepts > Syntax

  • APIs evolve
  • GPUs change too
  • But all modern APIs and GPUs have a lot in common
  • Common, transposable concepts are more important than syntax and APIs

➡️ understand how GPUs work for maximum performance

➡️ transpose your knowledge easily to other APIs, OSes or architectures

CPU vs GPU

Reminders

There's a freaking supercomputer in your browser,
and nobody seems to have noticed!

Steve Sanderson

CPU

www.thebookofshaders.com

GPU

www.thebookofshaders.com

Goal

Send as much data as possible to the GPU, for fast processing

  • "upload" (CPU ➡️ GPU) is slow 🐢
    • group data into buffers before transfer
  • GPU processing is very fast
    • using shaders
      • working in parallel
      • simple instructions
      • compiled in native low-level GPU code

Constraints

  • Rendering is fast but "download" (CPU ⬅️ GPU) VERY slow 🐌
  • Buffers are not flexible for dynamic data
  • Arrays must be converted to textures (for GPGPU)
    • conversion takes time especially for dynamic data
    • possible loss of accuracy
  • Shaders are complex to write
    • pixels are isolated, processed in parallel, independently
    • instructions are limited
    • optimizing and debugging is not trivial!

CPU

OpenGL, is a state machine

Reminders

WebGL is a state machine too!

  • data preparation
    • format, type, buffers...
  • global state preparation
    • color, blending...
  • rendering
    • send to GPU for shader processing

OpenGL Pipeline

Reminders

Rasterization

Interactive illustration

WebGL Fundamentals

by
Gregg Tavares (@greggman)
Chrome WebGL implementor

Shaders are essential

They allow to unleash the power of the GPU

  • Shader code is fast
    • thousands of specialized cores inside a GPU!
    • once the data and the compiled code have been sent to the GPU, the performance is the same regardless of thelanguage or API
  • Rendering is flexible
    • the rendering pipeline was fixed, not programmable before 2001
    • "rendering" has been hijacked to perform fast parallel physics and machine learning computations on the GPU (GPGPU)

Shader programming steps

  • the application sends to the GPU:
    • buffers (vertices, normals, connectivity info...) and textures
    • shaders to compile and run
  • vertex shaders are called once per vertex ⭐
  • each primitive (point, line, triangle) is converted to fragments(rasterization)
  • pixel fragment shaders are called once per fragment ⭐

From the triangle to the pixel

Interactive illustration

Making WebGL Dance

by
Steven Wittens

GLSL: Shader Programming Language

  • variable types ⭐

    • uniform: input, sent by the app, constant in the shader code
    • attribute: input of the vertex shader, sent by the app: data of the vertex buffer, varies per vertex
    • varying: output of the vertex shader / input of the fragment shader
  • functions: C language dialect

  • GLSL for WebGL 1.0, cf page 3

  • GLSL pour WebGL 2.0: version OpenGL ES 3.0, cf page 8

WebGL

Let's code!

BREAK

30' ⌛

Appendices

  • WebGL History

https://web.eecs.umich.edu/~sugih/courses/eecs487/lectures/20-History+ES+WebGL.pdf

  • WebGL 2 Course

https://perso.univ-rennes1.fr/pierre.nerzic/IAI2/IMR2 - Synthèse d'images - CM2.pdf

  • Tools for analyzing, debugging, checking and dumping WebGL

https://github.com/greggman/webgl-helpers#webgl-gl-error-checkjs

960px preview

![bg](https://ipfs.io/ipfs/QmVv73K78yysLhq5r16ZBUVUQ6mnw8DKfNMrTGxjJs4788)

![bg](https://bafybeifdf6t2elc24tlxggq4r4h7vgyvrkevojokjzu4ekkrxxqrswfqrm.ipfs.infura-ipfs.io/)

![bg](https://archive.smashing.media/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/431d55c0-9712-4196-8dd6-85b14088a9f1/moments-of-happiness-lion.gif)

![bg](https://cdn.dribbble.com/users/2813/screenshots/2123957/media/984bf5be1f6853bac7a9b9f110e9cc9a.gif)

<!-- _footer: cover art : "Chill the lion" by Karim Maaloul https://codepen.io/Yakudoo/details/YXxmYR/

<!-- _footer: image de couverture: https://versum.xyz/token/versum/4130

# ![height:110px](https://www.isep.fr/wp-content/themes/isep/img/logo_isep.svg)

![bg right](https://d201n44z4ifond.cloudfront.net/wp-content/uploads/sites/6/2019/10/16165332/Screen-Shot-2019-10-15-at-12.56.22-PM.png)

![bg left:50%](https://events.3ds.com/sites/default/files/styles/playground_experience_medium/public/2019-03/immersive-collaboration-experience-tribe-2-experience-1_0.PNG)

![bg](https://media.wired.com/photos/59267509f3e2356fd80094d1/master/pass/Singapore_Bishan_windsim_HP.jpg)

![bg fit](https://mms.businesswire.com/media/20141112006720/en/441072/4/Dassault_Systemes_Living_Heart_1.jpg)

![bg 110%](http://www.cao.fr/images_cp/plein/6772.jpg)

source: https://web.eecs.umich.edu/~sugih/courses/eecs487/lectures/20-History+ES+WebGL.pdf

![bg right vertical fit](https://steemitimages.com/p/KWcVEiwEzuiBTRjkbQErt6ge69ftc1GVX4fCr3en9K5bs5hCcEWsc6RNrn4oJbz7d748cj3ToFWMzCn4gM)

WebGL stack

<!-- _backgroundColor: #00000d ![bg w:800](https://architosh.com/wp-content/uploads/2017/02/architosh_webGL.jpg) ![bg w:800](https://architosh.com/wp-content/uploads/2017/02/architosh_webGPU.jpg)

![bg fit](https://tech.metail.com/wp-content/uploads/2018/05/webgl01.png)