# graphics3d/material (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/graphics3d/material/

Material. (shader template reference + metallic-roughness PBR parameters/textures, format-neutral)

## Material extends Object

Material. (shader template reference + metallic-roughness PBR parameters/textures, format-neutral)
- An instance that references a shader (template), and the model only applies the material instance.
- Creates GL textures from the neutral material description (factors + image bytes) made by the importer.
- FBX specular/gloss maps approximate roughness through the glossiness path.

Example: Build a material from an external texture and apply it to a model

```js
import { Material, SkinnedModel, SkinnedModelRenderer } from "./build/vanilla.js";

const canvas = document.createElement("canvas");
const webGL2RenderingContext = canvas.getContext("webgl2");
const skinnedModelRenderer = new SkinnedModelRenderer(webGL2RenderingContext);
const shaderProgram = skinnedModelRenderer.getShaderProgram();
const description = Material.createDefaultDescription();
description.baseColorFactor = [1.0, 0.8, 0.6];
description.roughnessFactor = 0.7;
description.baseColorImage = await Material.loadImageDescription("assets/icons/icon.png", { isColorData: true, anisotropy: 4 });
const material = await Material.createFromDescription(webGL2RenderingContext, shaderProgram, description);
const skinnedModel = await SkinnedModel.loadFromUrl(webGL2RenderingContext, "examples/ancientmountain/assets/fox.glb", skinnedModelRenderer);
skinnedModel.setMaterial(0, material);
const textureBindings = material.getTextureBindings();
console.log(textureBindings.length);
```

- `constructor(webGL2RenderingContext, shaderProgram)` (constructor, since 0.3.0): Constructor.
  - `webGL2RenderingContext` WebGL2RenderingContext: WebGL2 rendering context.
  - `shaderProgram` ShaderProgram: Shader program to set uniforms on. (the material template)
- `static createDefaultDescription()` (static, since 0.3.0): Creates a default material description. (static, white matte non-metal)
  - returns object: Default description. ({ baseColorFactor, metallicFactor, roughnessFactor, emissiveFactor } and 8 image slots, white, metallic 0, roughness 1, all images null)
- `static async createFromDescription(webGL2RenderingContext, shaderProgram, description)` (static, since 0.3.0): Creates from a neutral material description. (static, image bytes → GL textures)
  - If an image cannot be decoded midway, it deletes the textures created so far and throws an error.
  - `webGL2RenderingContext` WebGL2RenderingContext: WebGL2 rendering context.
  - `shaderProgram` ShaderProgram: Shader program to reference.
  - `description` object: Neutral material description. (createDefaultDescription shape, a null image slot becomes a 1x1 solid color texture)
  - returns Promise<Material>: Material with its textures uploaded. (rejected if an image cannot be decoded)
- `async createTexture(imageDescription, fallbackColor)` (method, since 0.3.0): Creates a texture. (image description → GL texture, 1x1 solid color fallback if none)
  - Image description: { bytes, mimeType, flipY } or { source (canvas/bitmap), flipY }
  - isColorData: a color texture stored in sRGB, sampled in linear space with hardware decode (SRGB8_ALPHA8).
  - anisotropy: anisotropic filter level. (ignored if the extension is unsupported)
  - The texture is created after the image is fully decoded. (no texture is left behind if decoding fails, and the upload goes to this texture even if another texture is bound while waiting)
  - `imageDescription` object | null: Image description. ({ bytes, mimeType, flipY, isColorData, anisotropy } or { source, flipY, isColorData, anisotropy }, solid color when null or empty)
  - `fallbackColor` number[]: 1x1 color used when there is no image. ([r, g, b, a], 0 ~ 255)
  - returns Promise<WebGLTexture>: The created GL texture. (mipmapped with repeat wrapping for images, rejected if the image cannot be decoded)
- `static async loadImageDescription(url, options = null)` (static, since 0.3.0): Loads an image description from a URL. (static, an external texture file into a neutral image description)
  - options: { flipY, isColorData, anisotropy }
  - `url` string: Texture file URL.
  - `options` object | null: { flipY = false, isColorData = false, anisotropy = 0 } (all defaults when null)
  - returns Promise<object>: Image description. (throws when the response fails)
- `static createImageDescription(bytes, mimeType = null, options = null)` (static, since 0.4.0): Makes an image description from bytes. (static, the part of loadImageDescription after fetch, for bytes already received via a bundle or BlobAsset)
  - options: { flipY, isColorData, anisotropy }
  - `bytes` Uint8Array: Image file bytes.
  - `mimeType` string | null: Image MIME type. (when null, the Blob is built without a type)
  - `options` object | null: { flipY = false, isColorData = false, anisotropy = 0 } (all defaults when null)
  - returns object: Image description. ({ bytes, mimeType, flipY, isColorData, anisotropy })

  Example: Create an image description from bytes already received

  ```js
  import { Material } from "./build/vanilla.js";
  
  const response = await fetch("assets/icons/icon.png");
  const arrayBuffer = await response.arrayBuffer();
  const bytes = new Uint8Array(arrayBuffer);
  const imageDescription = Material.createImageDescription(bytes, "image/png", { flipY: true, isColorData: true });
  console.log(imageDescription.mimeType, imageDescription.flipY, imageDescription.anisotropy);
  ```

- `setTexture(uniformName, textureUnit, glTexture)` (method, since 0.3.0): Sets an extra texture. (a slot specific to the shader template, uniform name / texture unit outside the default slots)
  - Unit 1 is reserved for the shadow map and 0 / 2~8 are default slots, so use 9 or above.
  - `uniformName` string: Name of the shader's sampler2D uniform.
  - `textureUnit` number: Texture unit number. (9 or above)
  - `glTexture` WebGLTexture: GL texture to bind. (destroy does not delete it)

  Example: Add a texture to a shader-specific slot

  ```js
  import { Material, HumanSkinRenderer, SKIN_TEXTURE_UNIT_DETAILHEIGHT } from "./build/vanilla.js";
  
  const canvas = document.createElement("canvas");
  const webGL2RenderingContext = canvas.getContext("webgl2");
  const humanSkinRenderer = new HumanSkinRenderer(webGL2RenderingContext);
  const shaderProgram = humanSkinRenderer.getShaderProgram();
  const description = Material.createDefaultDescription();
  const material = await Material.createFromDescription(webGL2RenderingContext, shaderProgram, description);
  const heightImageDescription = await Material.loadImageDescription("assets/icons/icon.png");
  const heightTexture = await material.createTexture(heightImageDescription, [128, 128, 128, 255]);
  material.setTexture("detailHeightTexture", SKIN_TEXTURE_UNIT_DETAILHEIGHT, heightTexture);
  const textureBindings = material.getTextureBindings();
  console.log(textureBindings.length);
  ```

- `apply()` (method, since 0.3.0): Applies. (sets uniforms on the referenced shader + binds texture units)
- `getShaderProgram()` (method, since 0.3.0): Returns the referenced shader program. (the material template's shader)
  - returns ShaderProgram: Referenced shader program.
- `getBaseColorFactor()` (method, since 0.3.0): Returns the base color factor.
  - returns number[]: Base color factor. ([r, g, b])
- `getMetallicFactor()` (method, since 0.3.0): Returns the metallic factor.
  - returns number: Metallic factor.
- `getRoughnessFactor()` (method, since 0.3.0): Returns the roughness factor.
  - returns number: Roughness factor.
- `getEmissiveFactor()` (method, since 0.3.0): Returns the emissive factor.
  - returns number[]: Emissive factor. ([r, g, b])
- `getUseGlossiness()` (method, since 0.3.0): Returns whether the glossiness path is used.
  - returns boolean: True when roughness is derived from the glossiness texture.
- `setBaseColorFactor(baseColorFactor)` (method, since 0.4.0): Set the base color factor. (linear rgb multiplier; on a shared material every model using it changes)
  - `baseColorFactor` number[]: Base color factor. ([r, g, b], linear, the first three values are copied)

  Example: Tint only the material copy red

  ```js
  import { Material, SkinnedModelRenderer } from "./build/vanilla.js";
  
  const canvas = document.createElement("canvas");
  const webGL2RenderingContext = canvas.getContext("webgl2");
  const skinnedModelRenderer = new SkinnedModelRenderer(webGL2RenderingContext);
  const shaderProgram = skinnedModelRenderer.getShaderProgram();
  const description = Material.createDefaultDescription();
  const sharedMaterial = await Material.createFromDescription(webGL2RenderingContext, shaderProgram, description);
  const instanceMaterial = sharedMaterial.createInstance();
  instanceMaterial.setBaseColorFactor([1, 0.4, 0.4]);
  console.log(sharedMaterial.getBaseColorFactor().join(", "), instanceMaterial.getBaseColorFactor().join(", "));
  instanceMaterial.destroy();
  sharedMaterial.destroy();
  ```

- `createInstance()` (method, since 0.4.0): Create a material copy. (like Unity's material and sharedMaterial, only the values fork and the textures are borrowed from the original)
  - Copies the factors, flags, default slot textures and extra textures added with setTexture. No GPU texture is uploaded again.
  - The copy's destroy does not delete the borrowed textures. Finish using the copies before destroying the original (the material that created the textures).
  - returns Material: Copy that uses the same shader and textures with values that can change separately. (texture byte count 0)
- `getTextureByteCount()` (method, since 0.4.0): Return the texture byte count. (GPU bytes of the default slot textures this material created, including mipmaps; 0 for a copy)
  - returns number: GPU texture byte count. (counted as RGBA8, a solid 1x1 is 4)
- `setSubsurfaceFactor(subsurfaceFactor)` (method, since 0.3.0): Sets the subsurface factor. (screen-space scattering mask multiplier of the skin shader, 0 for non-scattering parts like eyes / teeth)
  - `subsurfaceFactor` number: Scattering mask multiplier. (default 1, 0 for parts that do not scatter)
- `getSubsurfaceFactor()` (method, since 0.3.0): Returns the subsurface factor.
  - returns number: Scattering mask multiplier.
- `setUseAlphaCutout(useAlphaCutout)` (method, since 0.3.0): Sets whether alpha cutout is used. (for materials with an opacity texture attached later)
  - `useAlphaCutout` boolean: Uses alpha cutout when true.
- `getUseAlphaCutout()` (method, since 0.3.0): Returns whether alpha cutout is used. (when it has an opacity map, hair/eyelashes etc.)
  - returns boolean: True when alpha cutout is used.
- `getTextureBindings()` (method, since 0.3.0): Returns the texture binding list. (uniform name / texture unit / GL texture)
  - returns Array<[string, number, WebGLTexture]>: List of [uniform name, texture unit, GL texture]. (the 8 default slots followed by those added with setTexture)
- `getWebGL2RenderingContext()` (method, since 0.3.0): Returns the rendering context.
  - returns WebGL2RenderingContext: Rendering context.
- `destroy()` (method, since 0.4.0): Destroy. (deletes the default slot textures; extra textures added with setTexture belong to whoever added them and stay)
  - A copy made with createInstance does not delete the borrowed textures and only clears the slots.
