Skip to content

Commit

Permalink
fix(website): improve example code
Browse files Browse the repository at this point in the history
  • Loading branch information
ibgreen committed Nov 11, 2023
1 parent 8ca0819 commit b7b4c7e
Show file tree
Hide file tree
Showing 11 changed files with 223 additions and 91 deletions.
Empty file.
23 changes: 23 additions & 0 deletions docs/api-reference/shadertools/modules/lights.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# lights (Shader Module)

The `lights`` shader module collects uniforms describing the lights in a scene.
No view dependent uniforms are includes so the resulting uniform block should be reusable for all draw calls in a scene.

## Material modules

Actual lighting computations are done by the various material shader modules, such as:

- `phongMaterial`
- `goraudmaterial`
- `pbrMaterial`

Different draw calls can use different material uniform buffers and/or different material modules.

All material modules depend on this lighting module and base lighting calculations
on the lights defined by this module, meaning that the same lighting uniform buffer can be
bound.

## Defining lights

The lights module lets the application define the ambient light color and a number of additional lights that can either be point lights (e.g, a light bulb) or directional lights (e.g. sunlight).

12 changes: 9 additions & 3 deletions docs/api-reference/shadertools/modules/pbr.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
# PBR (Shader Module)

An implementation of PBR (Physically-Based Rendering) based on the [Khronos Reference Implementation](https://github.com/KhronosGroup/glTF-WebGL-PBR).
Implements Physically Based Shading of a microfacet surface defined by a glTF material.

A reference implementation for Physically Based Shading of a microfacet surface defined by a glTF material.
Lighting is expected to be defined by the `lights` module.

References:

## References

- [Real Shading in Unreal Engine 4](http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf)
- [Physically Based Shading at Disney](http://blog.selfshadow.com/publications/s2012-shading-course/burley/s2012_pbs_disney_brdf_notes_v3.pdf)
- [README.md - Environment Maps](https://github.com/KhronosGroup/glTF-WebGL-PBR/#environment-maps)
- ["An Inexpensive BRDF Model for Physically based Rendering" by Christophe Schlick](https://www.cs.virginia.edu/~jdl/bib/appearance/analytic%20models/schlick94b.pdf)

## Attribution

This implementation of PBR (Physically-Based Rendering) is a fork of the [Khronos Reference Implementation](https://github.com/KhronosGroup/glTF-WebGL-PBR) under the Apache 2.0 license.

Empty file.
108 changes: 67 additions & 41 deletions examples/tutorials/lighting/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,16 @@ Drawing a phong-shaded cube
`;

type AppUniforms = {
uModel: NumberArray;
uMVP: NumberArray;
uEyePosition: NumberArray;
modelMatrix: NumberArray;
mvpMatrix: NumberArray;
eyePosition: NumberArray;
};

const appUniforms: {uniformTypes: Record<keyof AppUniforms, ShaderUniformType>} = {
const app: {uniformTypes: Record<keyof AppUniforms, ShaderUniformType>} = {
uniformTypes: {
uMVP: 'mat4x4<f32>',
uModel: 'mat4x4<f32>',
uEyePosition: 'vec3<f32>'
modelMatrix: 'mat4x4<f32>',
mvpMatrix: 'mat4x4<f32>',
eyePosition: 'vec3<f32>'
}
};

Expand All @@ -34,16 +34,16 @@ const vs = glsl`\
varying vec2 vUV;
uniform appUniforms {
mat4 uModel;
mat4 uMVP;
vec3 uEyePosition;
} app;
mat4 modelMatrix;
mat4 mvpMatrix;
vec3 eyePosition;
} uApp;
void main(void) {
vPosition = (app.uModel * vec4(positions, 1.0)).xyz;
vNormal = mat3(app.uModel) * normals;
vPosition = (uApp.modelMatrix * vec4(positions, 1.0)).xyz;
vNormal = mat3(uApp.modelMatrix) * normals;
vUV = texCoords;
gl_Position = app.uMVP * vec4(positions, 1.0);
gl_Position = uApp.mvpMatrix * vec4(positions, 1.0);
}
`;

Expand All @@ -58,14 +58,14 @@ const fs = glsl`\
uniform sampler2D uTexture;
uniform appUniforms {
mat4 uModel;
mat4 uMVP;
vec3 uEyePosition;
} app;
mat4 modelMatrix;
mat4 mvpMatrix;
vec3 eyePosition;
} uApp;
void main(void) {
vec3 materialColor = texture2D(uTexture, vec2(vUV.x, 1.0 - vUV.y)).rgb;
vec3 surfaceColor = lighting_getLightColor(materialColor, app.uEyePosition, vPosition, normalize(vNormal));
vec3 surfaceColor = lighting_getLightColor(materialColor, uApp.eyePosition, vPosition, normalize(vNormal));
gl_FragColor = vec4(surfaceColor, 1.0);
}
Expand All @@ -79,34 +79,30 @@ export default class AppAnimationLoopTemplate extends AnimationLoopTemplate {
static info = INFO_HTML;

uniformStore = new UniformStore<{
app: AppUniforms,
lighting: typeof lighting['defaultUniforms'],
phongMaterial: typeof phongMaterial['defaultUniforms']
app: AppUniforms;
lighting: (typeof lighting)['defaultUniforms'];
phongMaterial: (typeof phongMaterial)['defaultUniforms'];
}>({
app: appUniforms,
lighting,
app,
lighting,
phongMaterial
});

model: Model;
modelMatrix = new Matrix4();
viewMatrix = new Matrix4().lookAt({eye: eyePosition});
mvpMatrix = new Matrix4();

constructor({device}: AnimationProps) {
super();

const texture = device.createTexture({data: 'vis-logo.png'});
// Set up static uniforms

this.model = new Model(device, {
vs,
fs,
geometry: new CubeGeometry(),
modules: [phongMaterial],
moduleSettings: {
material: {
specularColor: [255, 255, 255]
},
this.uniformStore.setUniforms({
phongMaterial: {
specularColor: [255, 255, 255]
},
lighting: lighting.getUniforms({
lights: [
{
type: 'ambient',
Expand All @@ -118,25 +114,52 @@ export default class AppAnimationLoopTemplate extends AnimationLoopTemplate {
position: [1, 2, 1]
}
]
}),
app: {
modelMatrix: this.modelMatrix,
eyePosition
}
});

const texture = device.createTexture({data: 'vis-logo.png'});

this.model = new Model(device, {
vs,
fs,
geometry: new CubeGeometry(),
modules: [phongMaterial],
moduleSettings: {
// material: {
// specularColor: [255, 255, 255]
// },
// lights: [
// {
// type: 'ambient',
// color: [255, 255, 255]
// },
// {
// type: 'point',
// color: [255, 255, 255],
// position: [1, 2, 1]
// }
// ]
},
bindings: {
uTexture: texture,
appUniforms: this.uniformStore.getManagedUniformBuffer(device, 'app'),
lightingUniforms: this.uniformStore.getManagedUniformBuffer(device, 'lighting'),
phongMaterialUniforms: this.uniformStore.getManagedUniformBuffer(device, 'phongMaterial')
},
uniforms: {
uEyePosition: eyePosition
},
parameters: {
depthWriteEnabled: true,
depthCompare: 'less-equal'
depthCompare: 'less-equal'
}
});
}

onFinalize() {
this.model.destroy();
this.uniformStore.destroy();
}

onRender({device, aspect, tick}) {
Expand All @@ -151,11 +174,14 @@ export default class AppAnimationLoopTemplate extends AnimationLoopTemplate {
.multiplyRight(this.modelMatrix);

this.uniformStore.setUniforms({
app: {uMVP: this.mvpMatrix, uModel: this.modelMatrix}
app: {
mvpMatrix: this.mvpMatrix,
modelMatrix: this.modelMatrix
}
});

const renderPass = device.beginRenderPass({
clearColor: [0, 0, 0, 1],
clearColor: [0, 0, 0, 1],
clearDepth: true
});
this.model.draw(renderPass);
Expand Down
21 changes: 13 additions & 8 deletions modules/core/src/lib/uniforms/uniform-block.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
// luma.gl, MIT license
import type {ShaderUniformType} from '../../adapter/types/shader-types';
import type {UniformValue} from '../../adapter/types/types';
import {ShaderLayout, UniformBufferBindingLayout, UniformInfo} from '../../adapter/types/shader-layout';
import { arrayEqual } from '../utils/array-equal';
import {
ShaderLayout,
UniformInfo,
UniformBufferBindingLayout
} from '../../adapter/types/shader-layout';
import {arrayEqual, arrayCopy} from '../utils/array-equal';

/**
/**
* A uniform block holds values of the of uniform values for one uniform block / buffer.
* It also does some book keeping on what has changed, to minimize unnecessary writes to uniform buffers.
* @todo - Track changes to individual uniforms (for WebGL1)
Expand All @@ -21,15 +25,16 @@ export class UniformBlock<TUniforms extends Record<string, UniformValue>> {

constructor(props?: {
name?: string;
shaderLayout?: ShaderLayout;
uniformTypes?: Record<keyof TUniforms, Record<string, ShaderUniformType>>
shaderLayout?: ShaderLayout;
uniformTypes?: Record<keyof TUniforms, Record<string, ShaderUniformType>>;
}) {
this.name = props?.name;

// TODO - Extract uniform layout from the shaderLayout object
if (props?.name && props?.shaderLayout) {
const binding = props?.shaderLayout.bindings
?.find(binding => binding.type === 'uniform' && binding.name === props?.name);
const binding = props?.shaderLayout.bindings?.find(
binding => binding.type === 'uniform' && binding.name === props?.name
);
if (!binding) {
throw new Error(props?.name);
}
Expand Down Expand Up @@ -68,7 +73,7 @@ export class UniformBlock<TUniforms extends Record<string, UniformValue>> {
if (arrayEqual(this.uniforms[key], value)) {
return;
}
this.uniforms[key] = value;
this.uniforms[key] = arrayCopy(value);
this.modifiedUniforms[key] = true;
this.modified = true;
}
Expand Down
9 changes: 9 additions & 0 deletions modules/core/src/lib/utils/array-equal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,12 @@ export function arrayEqual(a: unknown, b: unknown, limit: number = 16) {
}
return true;
}

/** Copy a value */
export function arrayCopy<T>(a: T): T {
const numberArray = isNumberArray(a);
if (numberArray) {
return numberArray.slice() as T;
}
return a;
}
2 changes: 1 addition & 1 deletion modules/engine/src/animation-loop/render-loop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import type {AnimationProps} from './animation-props';
* as an argument to create an AnimationLoop.
*/
export abstract class AnimationLoopTemplate {
constructor(animationProps?: AnimationProps) {}
constructor(animationProps: AnimationProps) {}
async onInitialize(animationProps: AnimationProps): Promise<unknown> { return null; }
abstract onRender(animationProps: AnimationProps): unknown;
abstract onFinalize(animationProps: AnimationProps): void;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@ uniform lightingUniforms {
} lighting;
PointLight lighting_getPointLight(int index) {
return PointLight(lightColor, lightPosition, lightAttenuation);
return PointLight(lighting.lightColor, lighting.lightPosition, lighting.lightAttenuation);
}
DirectionalLight lighting_getDirectionalLight(int index) {
return DirectionalLight(lightColor, lightDirection);
return DirectionalLight(lighting.lightColor, lighting.lightDirection);
}
float getPointLightAttenuation(PointLight pointLight, float distance) {
Expand Down
Loading

0 comments on commit b7b4c7e

Please sign in to comment.