Why Your Web Bundler Matters For Optimized WebGPU-Powered 3D Game Development
Published: 2024-05-10 16:50:33

Browser games have had quite the transformation throughout the years. From Flash to webGL we've seen gaming on the web be taken to new heights. Yet, with each step we take to advance, we seem to hit the same issues and deal with the bottleneck of creating the next big game that anyone can play no matter if they have a console or an expensive PC. The allure of browser-based games is expanding rapidly, not just among casual gamers but also within the AAA space. In this blog I want to share my experience of experimenting with different bundlers and how they affect my usage with WebGPU.
Performance will continue to be one of the most vital specs for game developers. Thats really why we haven't really seen too many AAA games on the web. Usually these games require a lot of GPU/CPU resources that are difficult to generate games on the DOM. This is where WebGPU comes in. 

## WebGPU
[WebGPU](https://developer.mozilla.org/en-US/docs/Web/API/WebGPU_API) is an emerging standard that aims to provide modern 3D graphics and computation capabilities on the web. Unlike WebGL, which is a JavaScript API for rendering interactive 2D and 3D graphics within any compatible web browser without the use of plug-ins, WebGPU is designed from the ground up to provide an efficient, low-level interface to the graphics processing unit (GPU).

Key features of WebGPU include:
1. Low-level Access: WebGPU offers fine-grained control over GPU operations, which means developers can perform more sophisticated rendering and data manipulation. This access allows for more optimized graphics rendering and general computation on the web.
2. Modern API Design: WebGPU is designed to interface with modern GPU features directly, similar to Vulkan, Metal, or DirectX 12. This means it can leverage capabilities that might not be available in older graphics APIs, enabling developers to create more graphically advanced and computationally intensive applications.
3. Cross-Platform Compatibility: As a web standard, WebGPU is intended to work across multiple platforms and devices, abstracting away the platform-specific graphics APIs while providing unified access to GPU capabilities.
4. Security: WebGPU is designed with modern web security standards in mind. It provides a more secure environment for executing GPU tasks, mitigating potential security risks that can arise from allowing web content to interact directly with the system's hardware resources.
5. Efficiency: Better performance and efficiency are key goals of WebGPU. The API allows for pre-compilation and efficient management of GPU resources, minimizing overhead, and maximizing throughput.
6. Compute Shaders: WebGPU supports compute shaders, which are programs that use the GPU for general computation tasks, not just graphics rendering. This expands the possible use cases to include scientific computing, machine learning, and other GPU-accelerated applications.
7. Concurrency and Async: The API is designed to fully take advantage of the GPU's ability to perform parallel operations, with support for asynchronous operations to ensure a smoother experience by not blocking the main thread in complex computations and rendering tasks.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0148cttw2hpl931wxq97.png)

## Choosing a web bundler

WebGPU presents an exciting opportunity to harness the power of modern graphics and computation capabilities directly within web browsers. In tandem, the emergence of Rsbuild, based upon Rspack as a build tool, facilitates an effortless and efficient developmental workflow for web projects.
RSBuild is designed to supercharge the development process, offering out-of-the-box functionality, semantic build configuration, and an array of official plugins that terrace the path for effortless adoption and immediate productivity gains. With RSBuild's emphasis on easy configuration, performance orientation, and a lightweight plugin system, developers can focus more on the creative aspects of their projects and less on the intricacies of the build process.
Leveraging Rsbuild's zero-configuration setup and Rspack's fast Rust-based bundler, we detail how developers can establish an efficient pipeline for developing, bundling, and deploying WebGPU applications. 
Rsbuild can manage WebGPU's modularity and the benefits it brings to the table in terms of developer experience. The examples encompass a range of WebGPU functionalities such as rendering pipelines, compute operations, and asset management while capitalizing on the rapid build times and optimized output of Rsbuild.
1. High-Performance Builds: RSBuild integrates high-performance Rust-based tools such as Rspack and SWC, vital for WebGPU projects where build speed and efficiency are crucial for iterative testing and complex shader compilation.
2. Universal Framework Support: RSBuild's framework agnostic nature allows developers to integrate with various UI frameworks, making it easier to adopt WebGPU across diverse tech stacks.
3. Consistent Artifacts: Stability of building artifacts is paramount for WebGPU applications, where a small change can have a significant visual impact. RSBuild ensures that developers have consistent results between development and production environments.
4. Simplified Configuration: The zero-config start-up and semantic configuration approach streamlines the set-up for Orillusion projects, meaning developers can spend more time leveraging WebGPU's capabilities instead of dealing with build issues.
Leveraging RSBuild Plugins:
The RSBuild plugin system is a game-changer, offering developers a chance to customize their build process according to the specific needs of their WebGPU project. Notable plugins can include:
1. Asset Optimization: Essential for WebGPU projects with large textures or models, asset optimization plugins can automatically compress and manage assets to ensure optimal loading times and runtime performance. You can use plugins like the 
- The Asset Retry Plugin or the Image Compress Plugin
2. Code Security: Protect your intellectual property with obfuscation plugins that add an extra layer of security, particularly important when deploying high-value WebGPU projects.
3. Enhanced Development Workflow: Streamline development with plugins that support hot module reloading(HMR), code splitting, and live previews, all of which are crucial for teams working on sophisticated WebGPU experiences.
4. Cross-Platform Compatibility: Ensure that your WebGPU application runs smoothly across all supported browsers and platforms with plugins designed to handle the nuances of different environments.

Use Cases:
Web LLM- run LLM's on the web powered by WebGPU

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bt3lvnim8ap8f4mrnjkj.png)
## Building 3D worlds:
[Orillusion](https://orillusion.com/): The Illusion of Complexity Simplified
Orillusion is a comprehensive library leveraging WebGPU to offer a high-level abstraction for intricate 3D graphics rendering. It simplifies the development of immersive web experiences, making the power of WebGPU accessible without demanding a deep dive into the lower-level intricacies.
Imagine developing a web application that features an interactive 3D model showcase, designed to be as performant as it is breathtaking. By integrating WebGPU for rendering, Rspack for bundling, and Orillusion for graphics abstraction, we can create an application that is both cutting-edge and efficient.

Orillusion is a comprehensive library leveraging WebGPU to offer a high-level abstraction for intricate 3D graphics rendering. It simplifies the development of immersive web experiences, making the power of WebGPU accessible without demanding a deep dive into the lower-level intricacies.
Imagine developing a web application that features an interactive 3D model showcase, designed to be as performant as it is breathtaking. By integrating WebGPU for rendering, Rspack for bundling, and Orillusion for graphics abstraction, we can create an application that is both cutting-edge and efficient.

`npm create rsbuild@latest`

Next Install orillusion

`npm install @orillusion/core --save`

## Step 2: Incorporating Orillusion for WebGPU Abstraction

With your project scaffolded, import Orillusion to provide a high-level interface to WebGPU. Orillusion makes it easy to create, manipulate, and render 3D models without delving deep into WebGPU's API details.
```javascript
// Import Orillusion
import { Scene, Engine, MeshBuilder } from 'orillusion';

// Initialize the Orillusion Engine
const engine = new Engine('renderCanvas');

// Create a simple 3D scene
const scene = new Scene(engine);
const box = MeshBuilder.createBox('box', { size: 1 }, scene);
```
## Step 3: Crafting the 3D Experience
Next let's take it up a notch

```javascript
import { Object3D, Scene3D, Engine3D, AtmosphericComponent, CameraUtil, webGPUContext, HoverCameraController, View3D, LitMaterial, MeshRenderer, BoxGeometry, DirectLight, KelvinUtil, Object3DUtil } from '@orillusion/core';
import { Stats } from '@orillusion/stats';

class Sample_Skeleton {
    lightObj3D: Object3D;
    scene: Scene3D;
    private Ori: dat.GUI | undefined;
    async run() {
        Engine3D.setting.shadow.autoUpdate = true;
        Engine3D.setting.shadow.updateFrameRate = 1;
        Engine3D.setting.shadow.shadowBound = 100;

        await Engine3D.init();

        this.scene = new Scene3D();
        this.scene.addComponent(Stats);
        let sky = this.scene.addComponent(AtmosphericComponent);

        let camera = CameraUtil.createCamera3DObject(this.scene);
        camera.perspective(60, Engine3D.aspect, 0.01, 5000.0);

        let ctrl = camera.object3D.addComponent(HoverCameraController);
        ctrl.setCamera(-30, -45, 100);
        ctrl.maxDistance = 1000;

        let view = new View3D();
        view.scene = this.scene;
        view.camera = camera;

        Engine3D.startRenderView(view);

        await this.initScene(this.scene);
        sky.relativeTransform = this.lightObj3D.transform;
    }

    async initScene(scene: Scene3D) {
        {
            // load model with skeleton animation
            let man = await Engine3D.res.loadGltf('https://cdn.orillusion.com/gltfs/CesiumMan/CesiumMan_compress.gltf');
            man.scaleX = 30;
            man.scaleY = 30;
            man.scaleZ = 30;
            scene.addChild(man);
        }
        {
            // load model with skeleton animation
            let man = await Engine3D.res.loadGltf('https://cdn.orillusion.com/gltfs/CesiumMan/CesiumMan_compress.gltf');
            man.scaleX = 30;
            man.scaleY = 30;
            man.scaleZ = 30;
            scene.addChild(man);
        }

        /******** floor *******/
        this.scene.addChild(Object3DUtil.GetSingleCube(3000, 1, 3000, .400, .355, .255));

        /******** light *******/
        {
            this.lightObj3D = new Object3D();
            this.lightObj3D.x = 0;
            this.lightObj3D.y = 30;
            this.lightObj3D.z = -40;
            this.lightObj3D.rotationX = 144;
            this.lightObj3D.rotationY = 0;
            this.lightObj3D.rotationZ = 0;
            let directLight = this.lightObj3D.addComponent(DirectLight);
            directLight.lightColor = KelvinUtil.color_temperature_to_rgb(5355);
            directLight.castShadow = true;
            directLight.intensity = 25;
            scene.addChild(this.lightObj3D);
        }
    }
}

new Sample_Skeleton().run();
```
You will get something like this:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1no8qj63zfe5r86hsj5r.png)

Bringing together WebGPU, Rspack, and Orillusion creates an ecosystem that is more than the sum of its parts. Developers can forge web applications exhibiting both stunning visual richness and unparalleled performance. This potent combination caters to the evolving demands of users and paves the way for the next generation of immersive web experiences. As the web continues to evolve, these tools will undoubtedly be at the forefront, powering experiences we've yet to imagine.