Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions samples/material/Sample_Anisotropy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { GUIHelp } from '@orillusion/debug/GUIHelp';
import {
AtmosphericComponent, BoxGeometry, CameraUtil, Color, DirectLight, Engine3D, HoverCameraController, KelvinUtil,
LitMaterial, MeshRenderer, Object3D, Scene3D, SphereGeometry, View3D,
} from '@orillusion/core';

/**
* KHR_materials_anisotropy demo (brushed-metal highlights).
*
* Top row: anisotropy strength 0 → 1 on the same metal — the round highlight
* stretches into a streak across the grain. Bottom row: full strength with
* the grain rotated 0° → 150°, which turns the streak. The GUI drives the
* large sphere on the right.
*/
class Sample_Anisotropy {
private scene: Scene3D;
private hero: LitMaterial;

async run() {
const engine = await Engine3D.init({ setting: { shadow: { enable: true, shadowBound: 60 } } });
this.scene = new Scene3D();
this.scene.addComponent(AtmosphericComponent).sunY = 0.6;

const camera = CameraUtil.createCamera3DObject(this.scene);
camera.perspective(45, engine.aspect, 0.1, 1000);
camera.object3D.addComponent(HoverCameraController).setCamera(10, -10, 46);

const lightObj = new Object3D();
lightObj.rotationX = 35; lightObj.rotationY = 160;
const light = lightObj.addComponent(DirectLight);
light.lightColor = KelvinUtil.color_temperature_to_rgb(5600);
light.intensity = 3.5;
light.castShadow = true;
light.enableCSM = true;
this.scene.addChild(lightObj);

this.build();

const view = new View3D();
view.scene = this.scene;
view.camera = camera;
engine.startRenderView(view);
this.initGUI();
}

private metal(strength: number, rotation: number): LitMaterial {
const m = new LitMaterial();
m.baseColor = new Color(0.72, 0.72, 0.75);
m.metallic = 1.0;
m.roughness = 0.35;
m.anisotropyRotation = rotation;
m.anisotropy = strength;
return m;
}

private add(geo: any, mat: LitMaterial, x: number, y: number): Object3D {
const o = new Object3D();
const mr = o.addComponent(MeshRenderer);
mr.geometry = geo; mr.material = mat; mr.castShadow = true;
o.x = x; o.y = y;
this.scene.addChild(o);
return o;
}

private build() {
const sphere = new SphereGeometry(2, 64, 64);
for (let i = 0; i < 6; i++) {
this.add(sphere, this.metal(i / 5, 0), (i - 2.5) * 5, 8.5);
this.add(sphere, this.metal(1, (i * 30 * Math.PI) / 180), (i - 2.5) * 5, 3);
}
this.hero = this.metal(0.9, 0);
this.add(new SphereGeometry(4, 96, 96), this.hero, 23, 6);

const floorMat = new LitMaterial();
floorMat.baseColor = new Color(0.5, 0.5, 0.52); floorMat.roughness = 0.9; floorMat.metallic = 0;
const floor = this.add(new BoxGeometry(140, 1, 80), floorMat, 5, -0.5);
floor.getComponent(MeshRenderer).castShadow = false;
}

private initGUI() {
GUIHelp.init();
const f = GUIHelp.addFolder('Anisotropy (big sphere)');
const s = { strength: 0.9, rotationDeg: 0, roughness: 0.35 };
f.add(s, 'strength', 0, 1, 0.01).onChange((v: number) => this.hero.anisotropy = v);
f.add(s, 'rotationDeg', 0, 180, 1).onChange((v: number) => this.hero.anisotropyRotation = (v * Math.PI) / 180);
f.add(s, 'roughness', 0.05, 1, 0.01).onChange((v: number) => this.hero.roughness = v);
f.open();
}
}

new Sample_Anisotropy().run();
2 changes: 2 additions & 0 deletions src/assets/shader/ShaderLib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import { BxDF_frag } from './lighting/BxDF_frag';
import { Clearcoat_frag } from './materials/program/Clearcoat_frag';
import { Sheen_frag } from './materials/program/Sheen_frag';
import { Iridescence_frag } from './materials/program/Iridescence_frag';
import { Anisotropy_frag } from './materials/program/Anisotropy_frag';
import { Lit_shader } from './materials/Lit_shader';
import { PBRLItShader } from './materials/PBRLItShader';
import { BxdfDebug_frag } from './materials/program/BxdfDebug_frag';
Expand Down Expand Up @@ -132,6 +133,7 @@ export class ShaderLib {
ShaderLib.register('Clearcoat_frag', Clearcoat_frag);
ShaderLib.register('Sheen_frag', Sheen_frag);
ShaderLib.register('Iridescence_frag', Iridescence_frag);
ShaderLib.register('Anisotropy_frag', Anisotropy_frag);
ShaderLib.register('LitShader', Lit_shader);
ShaderLib.register('PBRLItShader', PBRLItShader);

Expand Down
10 changes: 9 additions & 1 deletion src/assets/shader/lighting/BxDF_frag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export let BxDF_frag: string = /*wgsl*/ `
#include "BxdfDebug_frag"
#include "Sheen_frag"
#include "Iridescence_frag"
#include "Anisotropy_frag"
#include "ReflectionCG"

//ORI_ShadingInput
Expand Down Expand Up @@ -83,6 +84,9 @@ export let BxDF_frag: string = /*wgsl*/ `

fn BxDFShading(){
initFragData();
#if USE_ANISOTROPY
initAnisotropy();
#endif

let sunLight = lightBuffer[0] ;

Expand Down Expand Up @@ -155,7 +159,11 @@ export let BxDF_frag: string = /*wgsl*/ `
var indirectionDiffuse = indirectionDiffuse_Function(fragData.NoV,fragData.N,fragData.Metallic,fragData.Albedo.rgb,fragData.Roughness,fragData.Ao,fragData.F0);
iblDiffuseResult += indirectionDiffuse / 3.14;

var indirectionSpec = indirectionSpec_Function(fragData.R,fragData.Roughness,fragData.NoV,fragData.Ao,gammaToLiner(fragData.F0));
var specReflectDir = fragData.R;
#if USE_ANISOTROPY
specReflectDir = anisotropyReflection(fragData.Roughness);
#endif
var indirectionSpec = indirectionSpec_Function(specReflectDir,fragData.Roughness,fragData.NoV,fragData.Ao,gammaToLiner(fragData.F0));
#if USE_CASTREFLECTION
indirectionSpec *= globalUniform.hdrExposure ;
#endif
Expand Down
5 changes: 5 additions & 0 deletions src/assets/shader/lighting/LightingFunction_frag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ fn sampleLighting(light:LightData,direction:vec3f,iblSpecularResult:vec3f , inte
var att = max(0.0,intensity);

var lighting:vec3f = lightContribution(NdotH,NdotL,NdotV,HdotL,fragData.Roughness,fragData.Albedo.rgb / 3.14, metallic ,shadow,fragData.F0,lightColor.rgb);
#if USE_ANISOTROPY
// Swap the isotropic specular lobe for the anisotropic one; diffuse is untouched.
let isoSpec = DGF_Function(NdotH,NdotL,NdotV,HdotL,fragData.Roughness,shadow,fragData.F0,lightColor.rgb);
lighting += isoSpec * (anisotropySpecularRatio(lightDir, fragData.Roughness) - 1.0);
#endif
// ACES is now applied as a final post-pass (TonemapPost) so the
// light contribution stays linear HDR here. Just modulate by
// attenuation. Direct premultiply matches the standard PBR
Expand Down
90 changes: 90 additions & 0 deletions src/assets/shader/materials/program/Anisotropy_frag.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/**
* KHR_materials_anisotropy — stretched specular highlights (brushed metal,
* hair-like finishes, vinyl records).
*
* The engine's isotropic specular term keeps its own conventions; this chunk
* supplies the RATIO between the anisotropic GGX lobe and the isotropic one
* (D and correlated-Smith visibility), which is exactly 1 when the strength
* is 0, plus the bent reflection vector for the environment term.
*
* `materialUniform.anisotropy` = (strength 0..1, rotation in radians, unused, unused).
* The tangent frame comes from screen-space derivatives of position and UV,
* so the mesh needs UVs (it falls back to an arbitrary tangent without them).
* `AnisotropyUtil` mirrors the math on the CPU.
* @internal
*/
export let Anisotropy_frag: string = /*wgsl*/ `
#if USE_ANISOTROPY
var<private> anisoT: vec3<f32>;
var<private> anisoB: vec3<f32>;

/// Build the rotated, orthonormal tangent frame. Call once per fragment, outside branches.
fn initAnisotropy() {
let N = fragData.N;
let worldPos = ORI_VertexVarying.vWorldPos.xyz;
let q0 = dpdx(worldPos);
let q1 = dpdy(worldPos);
let st0 = dpdx(ORI_VertexVarying.fragUV0.xy);
let st1 = dpdy(ORI_VertexVarying.fragUV0.xy);
let q0perp = cross(N, q0);
let q1perp = cross(q1, N);
var T = q1perp * st0.x + q0perp * st1.x;
// Gram-Schmidt against the shading normal.
T = T - N * dot(N, T);
if (dot(T, T) < 1e-12) {
// No usable UV gradient: any tangent perpendicular to N.
var up = vec3<f32>(0.0, 1.0, 0.0);
if (abs(N.y) > 0.99) { up = vec3<f32>(1.0, 0.0, 0.0); }
T = cross(up, N);
}
T = normalize(T);
let B0 = normalize(cross(N, T));
let rot = materialUniform.anisotropy.y;
anisoT = normalize(T * cos(rot) + B0 * sin(rot));
anisoB = normalize(cross(N, anisoT));
}

/// (anisotropic D·V) / (isotropic D·V) for light direction L. 1 when strength is 0.
fn anisotropySpecularRatio(L: vec3<f32>, roughness: f32) -> f32 {
let N = fragData.N;
let V = fragData.V;
let H = normalize(L + V);
let NoH = clamp(dot(N, H), 0.0, 1.0);
let NoL = clamp(dot(N, L), 0.0001, 1.0);
let NoV = clamp(dot(N, V), 0.0001, 1.0);
let strength = clamp(materialUniform.anisotropy.x, 0.0, 1.0);
let a = max(roughness * roughness, 0.002);
let at = mix(a, 1.0, strength * strength);
let ab = a;

let ToH = dot(anisoT, H); let BoH = dot(anisoB, H);
let ToV = dot(anisoT, V); let BoV = dot(anisoB, V);
let ToL = dot(anisoT, L); let BoL = dot(anisoB, L);

// D
let a2 = a * a;
let dIsoDen = NoH * NoH * (a2 - 1.0) + 1.0;
let dIso = a2 / (dIsoDen * dIsoDen);
let dAniDen = ToH * ToH / (at * at) + BoH * BoH / (ab * ab) + NoH * NoH;
let dAni = 1.0 / (at * ab * dAniDen * dAniDen);

// V (height-correlated Smith)
let vIso = 0.5 / (NoL * sqrt(NoV * NoV * (1.0 - a2) + a2) + NoV * sqrt(NoL * NoL * (1.0 - a2) + a2));
let vAni = 0.5 / (NoL * length(vec3<f32>(at * ToV, ab * BoV, NoV)) + NoV * length(vec3<f32>(at * ToL, ab * BoL, NoL)));

return (dAni * vAni) / max(dIso * vIso, 1e-8);
}

/// Reflection vector bent toward the grain so environment reflections stretch too.
fn anisotropyReflection(roughness: f32) -> vec3<f32> {
let N = fragData.N;
let V = fragData.V;
let strength = clamp(materialUniform.anisotropy.x, 0.0, 1.0);
let bentTangent = cross(anisoB, V);
var bentNormal = cross(bentTangent, anisoB);
let k = 1.0 - strength * (1.0 - roughness);
bentNormal = normalize(mix(bentNormal, N, k * k * k * k));
return 2.0 * dot(V, bentNormal) * bentNormal - V;
}
#endif
`;
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export let PhysicMaterialUniform_frag = /* wgsl */`

sheenColor: vec4<f32>,
iridescence: vec4<f32>,
anisotropy: vec4<f32>,

baseMapOffsetSize:vec4<f32>,
normalMapOffsetSize:vec4<f32>,
Expand Down
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ export * from "./assets/shader/materials/Sprite_shader"
export * from "./assets/shader/materials/UnLit"
export * from "./assets/shader/materials/UnLitTextureArray"
export * from "./assets/shader/materials/WaterShader"
export * from "./assets/shader/materials/program/Anisotropy_frag"
export * from "./assets/shader/materials/program/BxdfDebug_frag"
export * from "./assets/shader/materials/program/Clearcoat_frag"
export * from "./assets/shader/materials/program/ClusterDebug_frag"
Expand Down Expand Up @@ -488,6 +489,7 @@ export * from "./loader/parser/gltf/GLTFType"
export * from "./loader/parser/gltf/TypeArray"
export * from "./loader/parser/gltf/extends/KHR_draco_mesh_compression"
export * from "./loader/parser/gltf/extends/KHR_lights_punctual"
export * from "./loader/parser/gltf/extends/KHR_materials_anisotropy"
export * from "./loader/parser/gltf/extends/KHR_materials_clearcoat"
export * from "./loader/parser/gltf/extends/KHR_materials_emissive_strength"
export * from "./loader/parser/gltf/extends/KHR_materials_ior"
Expand Down Expand Up @@ -673,6 +675,7 @@ export * from "./textures/TextureCubeFaceData"
export * from "./textures/Uint16Texture"
export * from "./textures/Uint8ArrayTexture"
export * from "./textures/VirtualTexture"
export * from "./util/AnisotropyUtil"
export * from "./util/AxisObject"
export * from "./util/BoundUtil"
export * from "./util/BytesArray"
Expand Down
2 changes: 2 additions & 0 deletions src/loader/parser/gltf/GLTFSubParserConverter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { GLTFType } from "./GLTFType";
import { KHR_materials_clearcoat } from "./extends/KHR_materials_clearcoat";
import { KHR_materials_sheen } from "./extends/KHR_materials_sheen";
import { KHR_materials_iridescence } from "./extends/KHR_materials_iridescence";
import { KHR_materials_anisotropy } from "./extends/KHR_materials_anisotropy";
import { KHR_materials_specular } from "./extends/KHR_materials_specular";
import { KHR_materials_variants } from "./extends/KHR_materials_variants";
import { KHR_materials_emissive_strength } from "./extends/KHR_materials_emissive_strength";
Expand Down Expand Up @@ -737,6 +738,7 @@ export class GLTFSubParserConverter {
KHR_materials_clearcoat.apply(this.gltf, dmaterial, mat);
KHR_materials_sheen.apply(this.gltf, dmaterial, mat);
KHR_materials_iridescence.apply(this.gltf, dmaterial, mat);
KHR_materials_anisotropy.apply(this.gltf, dmaterial, mat);
KHR_materials_specular.apply(this.gltf, dmaterial, mat);
KHR_materials_unlit.apply(this.gltf, dmaterial, mat);
KHR_materials_emissive_strength.apply(this.gltf, dmaterial, mat, this.subParser.ctx);
Expand Down
23 changes: 23 additions & 0 deletions src/loader/parser/gltf/extends/KHR_materials_anisotropy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_anisotropy

import { LitMaterial } from '../../../../materials/LitMaterial';

/**
* @internal
* @group Loader
*/
export class KHR_materials_anisotropy {
/**
* Applies `anisotropyStrength` and `anisotropyRotation`. The
* `anisotropyTexture` (per-texel direction and strength) is not sampled yet.
*/
public static apply(gltf: any, dmaterial: any, tMaterial: any) {
const ext = dmaterial.extensions?.[`KHR_materials_anisotropy`];
if (!ext) return;
const mat = tMaterial as LitMaterial;
dmaterial.anisotropyStrength = typeof ext.anisotropyStrength === 'number' ? ext.anisotropyStrength : 0;
dmaterial.anisotropyRotation = typeof ext.anisotropyRotation === 'number' ? ext.anisotropyRotation : 0;
mat.anisotropyRotation = dmaterial.anisotropyRotation;
mat.anisotropy = dmaterial.anisotropyStrength;
}
}
2 changes: 2 additions & 0 deletions src/loader/parser/prefab/mats/shader/StandShader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ export class StandShader extends Shader {
this.setUniformColor(`sheenColor`, new Color(0, 0, 0, 0));
// KHR_materials_iridescence: x = factor (0 = off), y = film IOR, z = film thickness (nm), w unused.
this.setUniformVector4(`iridescence`, new Vector4(0, 1.3, 400, 0));
// KHR_materials_anisotropy: x = strength (0 = off), y = rotation (radians), z / w unused.
this.setUniformVector4(`anisotropy`, new Vector4(0, 0, 0, 0));

this.setUniformVector4(`baseMapOffsetSize`, new Vector4(0, 0, 1, 1));
this.setUniformVector4(`normalMapOffsetSize`, new Vector4(0, 0, 1, 1));
Expand Down
36 changes: 36 additions & 0 deletions src/materials/LitMaterial.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export class LitMaterial extends Material {
colorPass.setUniform(`clearcoatIor`, sourceShader.getUniform(`clearcoatIor`));
colorPass.setUniform(`sheenColor`, sourceShader.getUniform(`sheenColor`));
colorPass.setUniform(`iridescence`, sourceShader.getUniform(`iridescence`));
colorPass.setUniform(`anisotropy`, sourceShader.getUniform(`anisotropy`));

colorPass.setTexture(`baseMap`, sourceShader.getTexture(`baseMap`));
colorPass.setTexture(`normalMap`, sourceShader.getTexture(`normalMap`));
Expand Down Expand Up @@ -163,6 +164,41 @@ export class LitMaterial extends Material {
return c ? c.a : 0;
}

private _anisotropyParams(): Vector4 {
const v = this.shader.getUniformVector4(`anisotropy`) as Vector4;
return v ? new Vector4(v.x, v.y, v.z, v.w) : new Vector4(0, 0, 0, 0);
}

/**
* Specular anisotropy strength (KHR_materials_anisotropy), 0…1: how far
* highlights stretch across the grain direction. Above 0 enables the
* effect; 0 disables it. The mesh needs UVs — the grain follows +U,
* turned by `anisotropyRotation`.
*/
public set anisotropy(value: number) {
const v = this._anisotropyParams();
v.x = Math.min(Math.max(value, 0), 1);
this.shader.setUniformVector4(`anisotropy`, v);
this.shader.setDefine(`USE_ANISOTROPY`, v.x > 0);
}

/** Get the anisotropy strength. */
public get anisotropy(): number {
return this._anisotropyParams().x;
}

/** Rotation of the grain direction around the normal, in radians, counter-clockwise from +U. */
public set anisotropyRotation(value: number) {
const v = this._anisotropyParams();
v.y = value;
this.shader.setUniformVector4(`anisotropy`, v);
}

/** Get the grain rotation in radians. */
public get anisotropyRotation(): number {
return this._anisotropyParams().y;
}

private _iridescenceParams(): Vector4 {
const v = this.shader.getUniformVector4(`iridescence`) as Vector4;
return v ? new Vector4(v.x, v.y, v.z, v.w) : new Vector4(0, 1.3, 400, 0);
Expand Down
Loading
Loading