Giter VIP home page Giter VIP logo

lamina's Introduction


lamina

🍰 An extensible, layer based shader material for ThreeJS


Chat on Twitter Chat on Twitter


These demos are real, you can click them! They contain the full code, too. πŸ“¦ More examples here


Notice

From @farazzshaikh: Lamina has been archived as of April 5 2023.

This project needs maintainers and a good rewrite from scratch. Lamina does a lot of hacky processing to achieve its API goals. As time has gone by I have started to doubt if it’s worth it. These hacks make it unreliable, unpredictable and slow. Not to mentaion, quite convoluted to maintain and debug. There might be better APIs or implimentations for this kind of library but I currently do not have the bandwidth to dedicate to finding them. Perhaps in the future.

Lamina is built on top of three-custom-shader-material (CSM) and any effects that are achieved by lamina can be done with CSM in a predictable and performant manner albeit at a lower level.

Feel free to use Lamina, however, support will be lacking. If you'd like to resurrect this library, then feel free to reach out on our Discord and tag me (Faraz#9759).


lamina lets you create materials with a declarative, system of layers. Layers make it incredibly easy to stack and blend effects. This approach was first made popular by the Spline team.

import { LayerMaterial, Depth } from 'lamina'

function GradientSphere() {
  return (
    <Sphere>
      <LayerMaterial
        color="#ffffff" //
        lighting="physical"
        transmission={1}
      >
        <Depth
          colorA="#810000" //
          colorB="#ffd0d0"
          alpha={0.5}
          mode="multiply"
          near={0}
          far={2}
          origin={[1, 1, 1]}
        />
      </LayerMaterial>
    </Sphere>
  )
}
Show Vanilla example

Lamina can be used with vanilla Three.js. Each layer is just a class.

import { LayerMaterial, Depth } from 'lamina/vanilla'

const geometry = new THREE.SphereGeometry(1, 128, 64)
const material = new LayerMaterial({
  color: '#d9d9d9',
  lighting: 'physical',
  transmission: 1,
  layers: [
    new Depth({
      colorA: '#002f4b',
      colorB: '#f2fdff',
      alpha: 0.5,
      mode: 'multiply',
      near: 0,
      far: 2,
      origin: new THREE.Vector3(1, 1, 1),
    }),
  ],
})

const mesh = new THREE.Mesh(geometry, material)

Note: To match the colors of the react example, you must convert all colors to Linear encoding like so:

new Depth({
  colorA: new THREE.Color('#002f4b').convertSRGBToLinear(),
  colorB: new THREE.Color('#f2fdff').convertSRGBToLinear(),
  alpha: 0.5,
  mode: 'multiply',
  near: 0,
  far: 2,
  origin: new THREE.Vector3(1, 1, 1),
}),

Layers

LayerMaterial

LayerMaterial can take in the following parameters:

Prop Type Default
name string "LayerMaterial"
color THREE.ColorRepresentation | THREE.Color "white"
alpha number 1
lighting 'phong' | 'physical' | 'toon' | 'basic' | 'lambert' | 'standard' 'basic'
layers* Abstract[] []

The lighting prop controls the shading that is applied on the material. The material then accepts all the material properties supported by ThreeJS of the material type specified by the lighting prop.

* Note: the layers prop is only available on the LayerMaterial class, not the component. Pass in layers as children in React.

Built-in layers

Here are the layers that lamina currently provides

Name Function
Fragment Layers
Color Flat color.
Depth Depth based gradient.
Fresnel Fresnel shading (strip or rim-lights).
Gradient Linear gradient.
Matcap Load in a Matcap.
Noise White, perlin or simplex noise .
Normal Visualize vertex normals.
Texture Image texture.
Vertex Layers
Displace Displace vertices using. noise

See the section for each layer for the options on it.

Debugger

Lamina comes with a handy debugger that lets you tweek parameters till you're satisfied with the result! Then, just copy the JSX and paste!

Replace LayerMaterial with DebugLayerMaterial to enable it.

<DebugLayerMaterial color="#ffffff">
  <Depth
    colorA="#810000" //
    colorB="#ffd0d0"
    alpha={0.5}
    mode="multiply"
    near={0}
    far={2}
    origin={[1, 1, 1]}
  />
</DebugLayerMaterial>

Any custom layers are automatically compatible with the debugger. However, for advanced inputs, see the Advanced Usage section.

Writing your own layers

You can write your own layers by extending the Abstract class. The concept is simple:

Each layer can be treated as an isolated shader program that produces a vec4 color.

The color of each layer will be blended together using the specified blend mode. A list of all available blend modes can be found here

import { Abstract } from 'lamina/vanilla'

// Extend the Abstract layer
class CustomLayer extends Abstract {
  // Define stuff as static properties!

  // Uniforms: Must begin with prefix "u_".
  // Assign them their default value.
  // Any unifroms here will automatically be set as properties on the class as setters and getters.
  // There setters and getters will update the underlying unifrom.
  static u_color = 'red' // Can be accessed as CustomLayer.color
  static u_alpha = 1 // Can be accessed as CustomLayer.alpha

  // Define your fragment shader just like you already do!
  // Only difference is, you must return the final color of this layer
  static fragmentShader = `   
    uniform vec3 u_color;
    uniform float u_alpha;

    // Varyings must be prefixed by "v_"
    varying vec3 v_Position;

    vec4 main() {
      // Local variables must be prefixed by "f_"
      vec4 f_color = vec4(u_color, u_alpha);
      return f_color;
    }
  `

  // Optionally Define a vertex shader!
  // Same rules as fragment shaders, except no blend modes.
  // Return a non-projected vec3 position.
  static vertexShader = `   
    // Varyings must be prefixed by "v_"
    varying vec3 v_Position;

    void main() {
      v_Position = position;
      return position * 2.;
    }
  `

  constructor(props) {
    // You MUST call `super` with the current constructor as the first argument.
    // Second argument is optional and provides non-uniform parameters like blend mode, name and visibility.
    super(CustomLayer, {
      name: 'CustomLayer',
      ...props,
    })
  }
}

πŸ‘‰ Note: The vertex shader must return a vec3. You do not need to set gl_Position or transform the model view. lamina will handle this automatically down the chain.

πŸ‘‰ Note: You can use lamina's noise functions inside of your own layer without any additional imports: lamina_noise_perlin(), lamina_noise_simplex(), lamina_noise_worley(), lamina_noise_white(), lamina_noise_swirl().

If you need a specialized or advance use-case, see the Advanced Usage section

Using your own layers

Custom layers are Vanilla compatible by default.

To use them with React-three-fiber, you must use the extend function to add the layer to your component library!

import { extend } from "@react-three/fiber"

extend({ CustomLayer })

// ...
const ref = useRef();

// Animate uniforms using a ref.
useFrame(({ clock }) => {
  ref.current.color.setRGB(
    Math.sin(clock.elapsedTime),
    Math.cos(clock.elapsedTime),
    Math.sin(clock.elapsedTime),
  )
})

<LayerMaterial>
  <customLayer
    ref={ref}     // Imperative instance of CustomLayer. Can be used to animate unifroms
    color="green" // Uniforms can be set directly
    alpha={0.5}
  />
</LayerMaterial>

Advanced Usage

For more advanced custom layers, lamina provides the onParse event.

This event runs after the layer's shader and uniforms are parsed.

This means you can use it to inject functionality that isn't by the basic layer extension syntax.

Here is a common use case - Adding non-uniform options to layers that directly sub out shader code.

class CustomLayer extends Abstract {
  static u_color = 'red'
  static u_alpha = 1

  static vertexShader = `...`
  static fragmentShader = `
    // ...
    float f_dist = lamina_mapping_template; // Temp value, will be used to inject code later on.
    // ...
  `

  // Get some shader code based off mapping parameter
  static getMapping(mapping) {
    switch (mapping) {
      default:
      case 'uv':
        return `some_shader_code`

      case 'world':
        return `some_other_shader_code`
    }
  }

  // Set non-uniform defaults.
  mapping: 'uv' | 'world' = 'uv'

  // Non unifrom params must be passed to the constructor
  constructor(props) {
    super(
      CustomLayer,
      {
        name: 'CustomLayer',
        ...props,
      },
      // This is onParse callback
      (self: CustomLayer) => {
        // Add to Leva (debugger) schema.
        // This will create a dropdown select component on the debugger.
        self.schema.push({
          value: self.mapping,
          label: 'mapping',
          options: ['uv', 'world'],
        })

        // Get shader chunk based off selected mapping value
        const mapping = CustomLayer.getMapping(self.mapping)

        // Inject shader chunk in current layer's shader code
        self.fragmentShader = self.fragmentShader.replace('lamina_mapping_template', mapping)
      }
    )
  }
}

In react...

// ...
<LayerMaterial>
  <customLayer
    ref={ref}
    color="green"
    alpha={0.5}
    args={[mapping]} // Non unifrom params must be passed to the constructor using `args`
  />
</LayerMaterial>

Layers

Every layer has these props in common.

Prop Type Default
mode BlendMode "normal"
name string <this.constructor.name>
visible boolean true

All props are optional.

Color

Flat color.

Prop Type Default
color THREE.ColorRepresentation | THREE.Color "red"
alpha number 1

Normal

Visualize vertex normals

Prop Type Default
direction THREE.Vector3 | [number,number,number] [0, 0, 0]
alpha number 1

Depth

Depth based gradient. Colors are lerp-ed based on mapping props which may have the following values:

  • vector: distance from origin to fragment's world position.
  • camera: distance from camera to fragment's world position.
  • world: distance from fragment to center (0, 0, 0).
Prop Type Default
colorA THREE.ColorRepresentation | THREE.Color "white"
colorB THREE.ColorRepresentation | THREE.Color "black"
alpha number 1
near number 2
far number 10
origin THREE.Vector3 | [number,number,number] [0, 0, 0]
mapping "vector" | "camera" | "world" "vector"

Fresnel

Fresnel shading.

Prop Type Default
color THREE.ColorRepresentation | THREE.Color "white"
alpha number 1
power number 0
intensity number 1
bias number 2

Gradient

Linear gradient based off distance from start to end in a specified axes. start and end are points on the axes selected. The distance between start and end is used to lerp the colors.

Prop Type Default
colorA THREE.ColorRepresentation | THREE.Color "white"
colorB THREE.ColorRepresentation | THREE.Color "black"
alpha number 1
contrast number 1
start number 1
end number -1
axes "x" | "y" | "z" "x"
mapping "local" | "world" | "uv" "local"

Noise

Various noise functions.

Prop Type Default
colorA THREE.ColorRepresentation | THREE.Color "white"
colorB THREE.ColorRepresentation | THREE.Color "black"
colorC THREE.ColorRepresentation | THREE.Color "white"
colorD THREE.ColorRepresentation | THREE.Color "black"
alpha number 1
scale number 1
offset THREE.Vector3 | [number, number, number] [0, 0, 0]
mapping "local" | "world" | "uv" "local"
type "perlin' | "simplex" | "cell" | "curl" "perlin"

Matcap

Set a Matcap texture.

Prop Type Default
map THREE.Texture undefined
alpha number 1

Texture

Set a texture.

Prop Type Default
map THREE.Texture undefined
alpha number 1

BlendMode

Blend modes currently available in lamina

normal divide
add overlay
subtract screen
multiply softlight
lighten reflect
darken negation

Vertex layers

Layers that affect the vertex shader

Displace

Displace vertices with various noise.

Prop Type Default
strength number 1
scale number 1
mapping "local" | "world" | "uv" "local"
type "perlin' | "simplex" | "cell" | "curl" "perlin"
offset THREE.Vector3 | [number,number,number] [0, 0, 0]

lamina's People

Contributors

alexwarnes avatar bravokiloecho avatar codyjasonbennett avatar drcmda avatar farazzshaikh avatar hazem3500 avatar igghera avatar madou avatar pixelass avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lamina's Issues

LayerMaterials: With Base baked in, transparency should be the default and can be deterministic

If we bake in the base as mentioned in #8 there's no need to call transparent. You still could I guess, just to be 100% sure or if you planned on adjusting the other values later.

But if you place a color in base:

 <LayerMaterial>
    <Base color="#603295" />
</LaterMaterial>

or by #8 :

<LayerMaterial color="#603295">

There's no alpha set so it is 100% opaque

where this becomes confusing is actually on the inverse:

 <LayerMaterial>
    <Base color="#603295" alpha=".5" />
</LaterMaterial>

You would think that layer is 50% see through (opaque) but it's not...

Transparent maps to the material, while base and alpha map to the material color map..

I have NO IDEA what this would do..

//simplified from @Fasani Blob experiment
<mesh>
  <sphereGeometry args={[0.8, 128, 128]} />
  <LayerMaterial>
    <Base color="#603295" />
          {...}
  </LayerMaterial>
</mesh>
<mesh ref={glow} scale={0.6} visible={showGlow}>
    <circleGeometry args={[2, 16]} />
    <LayerMaterial depthWrite={false} side={THREE.FrontSide} blending={THREE.AdditiveBlending}>
        {...}
    </LayerMaterial>
</mesh>

In that instance the user accidentally left of the transparent value on glow. Now, because the blending mode isnt the default we know we're supposed to be transparent..

TLDR: based on input props we can assume the intended transparency value

Transparency on meshStandardMaterial in Three.js doscs

Possible to update vertex positions?

first off wanted to say lamina is awesome, have really enjoyed playing around with it so far!

I was interested in making some custom layers that modified vertex positions eg:

  1. fullscreen layer (gl_Position = vec4(position * 2.0, 1.0) ...)
  2. height-map displacement layer (gl_Position.z += texture2d(map, uv).r)

Is this kinda thing out of scope for Lamina?

took a stab at implementing these but ran into issues because the ${body.vert} is included before gl_position is set and currently gl_position is determined entirely by unmodifiable input values. (modelViewMatrix, position, & projectionMatrix).

Tree shaking of debug code?

I noticed that the DebugLayerMaterial code adds ~50KB gzipped to my production js bundle even if I'm not using the debug layer. Looks like the main reason is because it's importing leva and its dependencies. I think this is something like an extra 2-3x the size of lamina's core code.

Tested with webpack and vite, but it's possible this is just my setup. I did a hacky fix with my bundler to alias leva to an empty exports file in production, but it would be nice to have the debug code automatically excluded if unused.

(Also, love the library!)

three-custom-shader-material 3.5.3 'csm_Normal' undeclared identifier

Warn: The three-custom-shader-material dependency does not work when it is updated to 3.5.3.
The examples use "three-custom-shader-material": "3.3.6" successfully, so that may be required to keep this stable.
Root Issue here: FarazzShaikh/THREE-CustomShaderMaterial#22

In my own package.json, I added this to the dependencies:

    "three": "^0.139.1",
    "three-custom-shader-material": "3.3.6",

and then this wonderful lib began to work as expected!

Thank you for your efforts in making shader work much easier <3

Uncaught TypeError: type is not a function

I'm running into this error while using the current version of @react-three/fiber (first affected version is 8.0.21). For example, updating the dependencies in the complex-material leads to the following:

yarn.lock:

 "@react-three/fiber@^8.0.3":
-  version "8.0.9"
-  resolved "https://registry.yarnpkg.com/@react-three/fiber/-/fiber-8.0.9.tgz#e231626dc923a7fefd1d47588ce2c5af09726213"
-  integrity sha512-9hh3w0JjPwtoqRexCnAVSPK3kdjtTqpaeTDZOW2RHmfU0gSYaKijY+PtaiHjoym/2oTfa21mCmaROXXS2jDvvQ==
+  version "8.0.22"
+  resolved "https://registry.yarnpkg.com/@react-three/fiber/-/fiber-8.0.22.tgz#68c69ba7c0c4f5354562c5acfd5f0c9c64b9a64d"
+  integrity sha512-HkQR+SKm0Bi4qq9sxCV2rv2aXxEhWPcj52bLOCiW3WpF8sGJtmdc/pP4ih5gXwN7I5NMTa2eDeoSYkIPOwt1/g==

Error:

Uncaught TypeError: type is not a function
    at attach (index-f1b43982.esm.js:194:1)
    at switchInstance (index-f1b43982.esm.js:1024:1)
    at commitUpdate (index-f1b43982.esm.js:1119:1)
    at commitWork (react-reconciler.development.js:15871:1)
    at commitMutationEffectsOnFiber (react-reconciler.development.js:16204:1)
    at commitMutationEffects_complete (react-reconciler.development.js:16057:1)
    at commitMutationEffects_begin (react-reconciler.development.js:16046:1)
    at commitMutationEffects (react-reconciler.development.js:16016:1)
    at commitRootImpl (react-reconciler.development.js:18932:1)
    at commitRoot (react-reconciler.development.js:18811:1)

Line:

} else child.__r3f.previousAttach = type(parent, child);

Transmission property not working in vanilla version.

I'm making a new material like this:

export class JourneySphereMaterial extends LayerMaterial {
	constructor() {
		super({
			color: 'white',
			lighting: 'physical',
			transmission: 1,
			// @ts-ignore
			thickness: 0,
			roughness: 0.42,
			metalness: 0.19,
		});
//Transmission only works if this is set, should work in init properties too?
		this.transmission = 1;
	}
}

However some properties like thickness gives a typescript error, and transmission isn't even set on the material created. I have to set it manually with that last line in the example for it to take effect.

Using with Sveltekit

Fantastic lib! I'm using it in my svelte-kit app (with pnpm).
First I get these worrying error messages, is there a way to only import the vanilla parts of this?
image

It does however run and work very nice in dev, but when building for production I face this error:
image
I see the package both provides a .cjs and a .js esm export, and I do try importing the esm one like this:
image
Any idea on how I should configure vite to be able to build this?

Possible to copy the implement of Fragment Layers to extend Three.js standard materials?

Hello,
I just wonder can I just copy this repo's Fragment Layers shader code to extend the three.js standard materials by your previous repo THREE-CustomShaderMaterial ?

For example, copy the glsl from Fresnel shader code , then use CustomShaderMaterial

const material = new CustomShaderMaterial({
    THREE.MeshPhysicalMaterial    // baseMaterial
    /* glsl */ ` ... `,           // Fresnel shader code from Fresnel.ts
    {
      intensity: 1           // options
      color: 0xff00ff
    }
  })

Skinned Meshes stop working with Lamina

Skinned meshes stop working when using Lamina. I think it might be because the shader is not implementing skinned meshes maybe?

Example without lamina:

Screen Shot 2022-04-16 at 19 26 13

Screen Shot 2022-04-16 at 19 26 05

When i add Lamina:

Screen Shot 2022-04-16 at 19 26 27

Screen Shot 2022-04-16 at 19 26 35

Why does CustomLayer example change the position if the comment says it shouldn't be transformed?

Am I the only one that thinks that the implementation of https://github.com/pmndrs/lamina/blob/main/README.md?plain=1#L205-L216 is confusing when looking at the comment?

For me it sounds like, that a CustomLayer should't change the position via the vertex-shader, but in the example it totally does exactly that:

  // Optionally Define a vertex shader!
  // Same rules as fragment shaders, except no blend modes.
  // Return a non-transformed vec3 position.
  static vertexShader = `   
    // Varyings must be prefixed by "v_"
    varying vec3 v_Position;
    void main() {
      v_Position = position;
      return position * 2.;
    }

So Return a non-transformed vec3 position. sounds to me that return position * 2.; shouldn't be done (I mean of course you can do that, but as a best practise it shouldn't right?).

When I copied the example I was surprised that my mesh had increased in size.

Simplify inputs for common symbols/types

Consider this blend effect

        <LayerMaterial transparent depthWrite={false} side={THREE.FrontSide} blending={THREE.AdditiveBlending}>

With strings:

        <LayerMaterial transparent depthWrite={false} side="front" blending="additive">

Side has 3 options, front, back, both. Blending does have a lot more, so you could still allow it to be passed, but otherwise make it easier...

Setting Alpha in vanilla material doesn't work.

export class JourneySphereMaterial extends LayerMaterial {
	constructor() {
		super({
			color: 'white',
			lighting: 'physical',
			transparent: true,
			transmission: 1,
			// @ts-ignore
			thickness: 0,
			alpha: 0.8,
		});
//This doesn't work, nor does using opacity.
		this.alpha= 0.2;
	}
}

Please create an example for TS Custom Layers

It took me a few hours to figure it out using the src

// src/layers/CustomLayer/index.tsx

import { forwardRef } from "react";
import { Abstract } from "lamina/vanilla";
import { LayerProps } from "lamina/types";
import { Node, extend } from "@react-three/fiber";
import { getNonUniformArgs } from "../../utils";
import vertexShader from "./vertex.glsl";
import fragmentShader from "./fragment.glsl";

interface CustomLayerProps extends LayerProps {
  color?: THREE.ColorRepresentation | THREE.Color;
  alpha?: number;
}

class CustomLayer extends Abstract {
  // Define stuff as static properties!

  // Uniforms: Must begin with prefix "u_".
  // Assign them their default value.
  // Any uniforms here will automatically be set as properties on the class as setters and getters.
  // There are setters and getters will update the underlying uniforms.
  static u_color = "red"; // Can be accessed as CustomExampleLayer.color
  static u_alpha = 1; // Can be accessed as CustomExampleLayer.alpha

  // Define your fragment shader just like you already do!
  // Only difference is, you must return the final color of this layer
  static fragmentShader = fragmentShader;

  // Optionally Define a vertex shader!
  // Same rules as fragment shaders, except no blend modes.
  // Return a non-transformed vec3 position.
  static vertexShader = vertexShader;

  constructor(props?: CustomLayerProps) {
    super(CustomLayer, {
      name: "CustomLayer",
      ...props,
    });
  }
}

declare global {
  namespace JSX {
    interface IntrinsicElements {
      customLayer_: Node<CustomLayer, typeof CustomLayer>;
    }
  }
}

extend({ CustomLayer_: CustomLayer });

const CustomLayerComponent = forwardRef<CustomLayer, CustomLayerProps>((props, ref) => {
  return <customLayer_ ref={ref} args={getNonUniformArgs(props)} {...props} />;
}) as React.ForwardRefExoticComponent<
  CustomLayerProps & React.RefAttributes<CustomLayer>
>;

export default CustomLayerComponent;
// src/App

import { useRef } from "react";
import { DebugLayerMaterial } from "lamina";
import { Mesh } from "three";
import { Plane } from "@react-three/drei";
import { GroupProps } from "@react-three/fiber";
import CustomLayer, { CustomLayerProps } from "./layers/CustomLayer";

export default function App({
  customLayerProps,
  ...props
}: GroupProps & { customLayerProps?: CustomLayerProps }) {
  const ref = useRef<Mesh>(null!);

  return (
    <group {...props}>
      <Plane
        ref={ref}
        args={[10, 10, 100, 100]}
        rotation={[Math.PI / -2, 0, 0]}
      >
        <DebugLayerMaterial
          color={"#ffffff"}
          lighting={"physical"} //
          transmission={1}
          roughness={0.1}
          thickness={3}
        >
          <CustomLayer color="green" alpha="0.5" />
        </DebugLayerMaterial>
      </Plane>
    </group>
  );
}

If you notice I import the .glsl directly. You can do this without ejecting by using the @rescripts/cli library. It gives you better syntax highlighting

// .rescripts.js

const { edit, getPaths } = require("@rescripts/utilities");

const predicate = (valueToTest) => {
  return valueToTest.oneOf;
};

const transform = (match) => ({
  ...match,
  oneOf: [
    // Need to add as second-to-last to avoid being intercepted by the file-loader in CRA
    ...match.oneOf.slice(0, -1),
    {
      test: /\.(glsl|frag|vert)$/,
      exclude: [/node_modules/],
      use: ["raw-loader", "glslify-loader"],
    },
    ...match.oneOf.slice(-1),
  ],
});

function rescriptGlslifyPlugin() {
  return (config) => {
    const matchingPaths = getPaths(predicate, config);
    return edit(transform, matchingPaths, config);
  };
}

module.exports = [[rescriptGlslifyPlugin]];

and the packlage.json to make the imports work

// package.json

{
  ...
  "dependencies": {
    "glslify": "^7.1.1",
    "glslify-loader": "^2.0.0",
    "lamina": "^1.1.8",
    "raw-loader": "^4.0.2",
    ...
  },
  "scripts": {
    "start": "rescripts start",
    "build": "rescripts build",
    "test": "rescripts test",
    "eject": "rescripts eject"
  },
  ...
  "devDependencies": {
    "@rescripts/cli": "^0.0.16",
    "@rescripts/rescript-env": "^0.0.14",
    "@rescripts/utilities": "^0.0.8"
  }
}

now you can load your glsl files

// src/layers/CustomLayer/vertexShader.glsl

varying vec3 v_Position;

void main() {
  v_Position = position;
  return position * 2.;
}
// src/layers/CustomLayer/fragmentShader.glsl

uniform vec3 u_color;
uniform float u_alpha;

// Varyings must be prefixed by "v_"
varying vec3 v_Position;

vec4 main() {
  // Local variables must be prefixed by "f_"
  vec4 f_color = vec4(u_color, u_alpha);
  return f_color;
}

Transparent Fresnel

Is it possible to make the black part of the fresnel transparent just like in Spline?

Screen Shot 2022-07-25 at 15 24 22

Screen Shot 2022-07-25 at 15 36 00

Create reasonable defaults to make things cleaner, best practices, and fault tolerant

Can you spot the "mistakes?"

<mesh>
    <sphereGeometry args={[1, 64, 64]} />
    <LayerMaterial>
        <Base color="#603295" />
        <Depth colorA="white" colorB="#0F1C4D" alpha={0.5} mode="normal" near={0} far={2} origin={[1, 1, 1]} />
        <Depth colorA="red"  alpha={0.5} mode="add" near={3} far={2} origin={[-1, 1, 1]} />
        <Fresnel mode="add" color="orange" intensity={0.5} power={2} bias={0.05} />
        <Noise scale={2} mapping="world" type="curl"  colorA="white" colorB="0x000000" mode="softlight" />
        <Noise mapping="local" /*type="curl" */ scale={100} colorA="#aaa" colorB="black" type="simplex" mode="softlight" />
        <Noise mapping="local" type="simplex" scale={100} colorA="white" colorB="black" mode="subtract" alpha={0.2} />
    </LayerMaterial>
    </mesh>
    <mesh>
    <circleGeometry args={[2, 16]} />
    <LayerMaterial transparent depthWrite={false} side={THREE.FrontSide} blending={THREE.AdditiveBlending}>
        <Depth colorA="orange" colorB="black" alpha={1} mode="normal" near={-2} far={1.4} origin={[0, 0, 0]} />
        <Noise mapping="local" type="simplex" scale={200} colorA="#fff" colorB="black" mode="multiply" />
    </LayerMaterial>
</mesh>

Desktop - 1 (1)

With the complex interweaving it can get incredibly difficult to debug or even correctly configure things on even relatively simple 2 mesh layouts. This totally isn't "bad"

but people will make bad..

Now obviously if people go in an and configure things "correctly" they will have complex files as well, however I think some of the things can have baselines, where the changing or overriding is clear by performing it at all.
Consider <noise>

BTW are we missing Noise props? This page mede it clear to understand, but our inputs are unique

---- This is real.. We used this in a multiple demos ----

<Noise scale={2} mapping="world" type="curl"  colorA="white" colorB="0x000000" mode="softlight" />
<Noise mapping="local" /*type="curl" */ scale={100} colorA="#aaa" colorB="black" type="simplex" mode="softlight" />
<Noise mapping="local" type="simplex" scale={100} colorA="white" colorB="black" mode="subtract" alpha={0.2} />

With Baseline configurations

<Noise  type="curl" mapping="world"   colorA="#ff0000" colorB="0x000000" mode="softlight" />
<Noise colorA="#aaa"  scale={2} mode="softlight" />
<Noise  alpha={0.2} mode="subtract" />

I feel like it's a LOT clearer what I'm fiddling with, and when I change the type Im doing it knowingly..

Maybe even catch it:

<LayerMaterial>
  <Noise type="curl" />
  <Noise type="curl" />
  <Noise type="curl" />
  <Noise type="curl" />
</LayerMaterial>
/***WARNING** More than 3 Noise Layers can cause significant frame loss: https://levadocs.io/curl */

NextJS build fails due to import error related to react-merge-refs upgrade

Hi there, when importing lamina into my project, I'm getting the following build error in NextJS (12.2.4):

Uncaught Error: require() of ES Module /[My_Project]/node_modules/lamina/node_modules/react-merge-refs/dist/index.mjs not supported.
Instead change the require of /[My_Project]/node_modules/lamina/node_modules/react-merge-refs/dist/index.mjs to a dynamic import() which is available in all CommonJS modules.

This may be a downstream issue but when I reverted lamina to 1.1.20 (changes here where there was a major version bump to react-merge-refs), the build error goes away (and a shader compilation error appears). Apparently NextJS has enabled ES Modules by default since v12. Any thoughts on how to proceed? Thanks!

Problems using the lamina noise functions in custom layer

I tried to move some of the Noise.ts into my custom layer as I'm working on a shader that will likely use noise and needed a starting point. The uniform values are set to the values in the Noise.ts, however, I keep getting the error about csm_DiffuseColor = lamina_finalColor;. Any insight into what may be going wrong would be much appreciated. Stuck =).

    uniform vec3 u_color;
    uniform vec3 u_colorA;
    uniform vec3 u_colorB;
    uniform vec3 u_colorC;
    uniform vec3 u_colorD;
    uniform vec3 u_offset;
    uniform float u_scale;
    uniform float u_alpha;
    uniform float u_time;
    varying vec3 v_Position;
    varying vec2 v_Uv;


    vec4 main() {
      // Local variables must be prefixed by "f_"
      float f_n = lamina_noise_perlin((v_Position + u_offset) * u_scale);
      float f_step1 = 0.;
      float f_step2 = 0.2;
      float f_step3 = 0.6;
      float f_step4 = 1.;



      vec3 f_color = mix(u_colorA, u_colorB, smoothstep(f_step1, f_step2, f_n));
      f_color = mix(f_color, u_colorC, smoothstep(f_step2, f_step3, f_n));
      f_color = mix(f_color, u_colorD, smoothstep(f_step3, f_step4, f_n));

      vec4 f_color_test = vec4(vec3(v_Uv, 0.), u_time);
      // return f_color_test;
      return vec4(f_color, u_alpha);

    }
  

The Error

Program Info Log: Fragment shader is not compiled.
οΏ½

FRAGMENT

ERROR: 0:832: ';' : syntax error
οΏ½

  827: 
  828: 
  829: 
  830:     lamina_finalColor = lamina_blend_alpha(lamina_finalColor, 
  831: 
> 832:           csm_DiffuseColor = lamina_finalColor;
  833:          
  834:         
  835:           
  836: #if 0 > 0
  837: 	vec4 plane;
  838: 	

related deps:

    "@react-three/cannon": "^6.4.0",
    "@react-three/drei": "^9.25.3",
    "@react-three/fiber": "^8.6.2",
    "https": "^1.0.0",
    "lamina": "^1.1.23",
    "leva": "^0.9.31",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "^5.0.1",
    "three": "^0.144.0",
    "three-stdlib": "^2.15.0"

RFC: Change behavior of how vertex shader layers are modifying positions

It's great that Lamina layers can also provide vertex shaders that modify the vertex positions, but unless I've severely misunderstood something (and please tell me if I did), the way that vertex shaders are currently set up makes it kinda iffy to have multiple vertex-shading layers stacked in sequence.

As far as I understand, from the perspective of a layer's vertex shader, the following happens:

  • A position variable is provided, containing the original vertex position from the geometry buffer.
  • The vertex shader is expected to implement a void main that returns a new, modified position.
  • If you have multiple Lamina layers that do this, each new layer will start with position being set to the original vertex position, essentially overwriting what the layers before already did to mutate it.

This makes it very hard to implement stacks of animation shaders (where one, for example, would animate the vertices based on velocity applied over time, and another apply a rotation) without completely bypassing this setup and writing all changes into a shared global variable, only to then have the final layer write into the actual position.

I don't know if this has implications (beyond potentially breaking existing code), so consider this an RFC: I propose that the system is changed to expect layer vertex shaders to mutate an existing position variable, eg.:

// wobble position vertexShader
void main() {
  position.x += sin(u_time);
}

// wobble scale vertexShader
void main() {
  position *= 2.0 + cos(u_time);
}

// etc.

Blend modes and ratios do not make sense here, so plain old mutation like this should be fine, but I'd be happy to hear what kind of stuff this will break.

LayerMaterial should create it's base by default

The base can only be called once and at the origin

<LayerMaterial>
    <Base color="#603295" >
</LayerMaterial>

becomes:

<LayerMaterial color="#603295" >
...
</LayerMaterial>

Similar to how R3f handles camera. Now base only has 3 arguments and only 1 will regularly be set, but if they had a specific requirement or need and really wanted they still could still do:

<LayerMaterial>
    <Base color={compareAllyColors{userColorVar, safeColorVar)} alpha={() => isDarkMode ? 1 : .5}  blend={/**No idea why base blends?**/} >
</LayerMaterial>

R3F Canvas & Camera:

<Canvas camera={{ positon: [0,5,0] }}>
    <Lights >
        <mesh></mesh>
</Canvas>
<Canvas>
    <perspectiveCamera ref="camRef" position={ [0,5,0 }>
        <Lights >
        <mesh></mesh>
</Canvas>

LayerMaterial clone() method doesn't works

clone material is not same as origin material

const material = new LayerMaterial({
      color: new THREE.Color(0xff0000),
      lighting: 'physical',
    });

const cube = new THREE.Mesh(geometry, material.clone());
Wrong Result, Should be red (0xff0000)

ζˆͺ屏2022-07-03 上午2 53 26

And no matter I clone multiple materials, the clone materials always have the same uuid ...
ζˆͺ屏2022-07-03 上午3 06 14

how to make depth layer mapping = world work

hi Team, sorry, this may not an issue but a Q&A, but since there no Q&A section in the project, so I have to riase an issue here instead.

I am doing a test with the Depth layer, when set mapping to world, it seems that only near/far works, when I changed the position of the mesh, its appearance doesn't changed.

Below is my code
https://github.com/rock117/my-lamina-test/blob/main/src/App.vue

As the document listed and the source code, if my undestanding is correct only the mesh's position effect the material render

 case 'world':
        return `length(v_${uuid}_position - vec3(0.))`

when changed the mesh's position, its appearance should update.

But what ever I changed the position, the appearance still not update.
do I need to set any other settings(except near,far) or invoke any Three/Lamina API to make the material update? thanks.
图片

Add mask layers

Hi, is it possible to make a layer that's last in line in the fragment shader renderer. The reason I ask is because I'm trying to create a an AlphaGradient Layer, essentially the same as the Gradient layer, except it works as a "mask" for the whole object, so you should be able to use it to fade out an object selectively using the same params as you use to control the Gradient Layer.

Here's a test were I just tried hardcoding the alpha value to be 0.0 to make it invisible, however this quick test revealed that the alpha value doesn't seem to propegate / override the main material?

import { Abstract } from 'lamina/vanilla'

export default class AlphaGradient extends Abstract {
  static u_colorA = 'white'
  static u_colorB = 'black'
  static u_alpha = 1

  static u_start = 1
  static u_end = -1
  static u_contrast = 1

  static vertexShader = `
		varying vec3 v_position;

		vod main() {
      v_position = lamina_mapping_template;
		}
  `

  static fragmentShader = `
    uniform vec3 u_colorA;
    uniform vec3 u_colorB;
    uniform vec3 u_axis;
    uniform float u_alpha;
    uniform float u_start;
    uniform float u_end;
    uniform float u_contrast;

		varying vec3 v_position;

    void main() {

      float f_step = smoothstep(u_start, u_end, v_position.axes_template * u_contrast);
      vec3 f_color = mix(u_colorA, u_colorB, f_step);

      return vec4(f_color, 0.0);
    }
  `

  axes: 'x' | 'y' | 'z' = 'x'
  mapping: 'local' | 'world' | 'uv' = 'local'

  constructor(props?) {
    super(
      AlphaGradient,
      {
        name: 'AlphaGradient',
        ...props,
      },
      (self: AlphaGradient) => {
        self.schema.push({
          value: self.axes,
          label: 'axes',
          options: ['x', 'y', 'z'],
        })

        self.schema.push({
          value: self.mapping,
          label: 'mapping',
          options: ['uv', 'world', 'local'],
        })

        const mapping = AlphaGradient.getMapping(self.mapping)

        self.vertexShader = self.vertexShader.replace('lamina_mapping_template', mapping || 'local')
        self.fragmentShader = self.fragmentShader.replace('axes_template', self.axes || 'x')
      }
    )
  }

  private static getMapping(type?: string) {
    switch (type) {
      default:
      case 'local':
        return `position`
      case 'world':
        return `(modelMatrix * vec4(position,1.0)).xyz`
      case 'uv':
        return `vec3(uv, 0.)`
    }
  }
}

Typescript and build issues

πŸ‘‹ Hello my friends. We are testing lamina, which looks amazing.

Sadly we are having several issues:

Typings:

Argument of type '{ color: string; shading: string; transmission: number; layers: Depth[]; }' is not assignable to parameter of type '(LayerMaterialParameters & AllMaterialParams) | undefined'.
  Object literal may only specify known properties, and 'shading' does not exist in type 'LayerMaterialParameters & AllMaterialParams'.

via

const material = new LayerMaterial({
	color: "#f00",
	shading: "physical", // <-- Typing does not match @types/three
	transmission: 1,
	/* ...*/
})

Screenshot 2022-03-16 at 07 53 53

Build fails: (using next.js on Vercel)

During development everything works. The issue occurs when running next build

> Build error occurred
--
07:08:40.409 | TypeError: THREE.MathUtils.generateUUID(...).replaceAll is not a function
07:08:40.409 | at new Abstract (/vercel/path0/node_modules/lamina/vanilla.cjs.js:124:48)
07:08:40.410 | at new Depth (/vercel/path0/node_modules/lamina/vanilla.cjs.js:372:5)
07:08:40.410 | at /vercel/path0/.next/server/pages/poop.js:53:12 {
07:08:40.410 | type: 'TypeError'
07:08:40.410 | }

Screenshot 2022-03-16 at 07 54 44

Reproduction:

Sadly our sandbox repository is currently private so hopefully the Codesandbox helps.

https://codesandbox.io/s/fast-violet-3ikixi?file=/src/App.tsx:315-379

Versions:

{
  "lamina": "^1.1.3",
   "three": "^0.138.3",
  "@react-three/fiber": "^7.0.26"
}

Help is highly appreciated.
If you need a better example, we can create a full reproduction of our setup (it's really just wrapped in a basic next.js page).
Our original example uses Suspense which does not change the behavior and is not required for this example to run.

Add all base material properties to debugger

Seems like now it just exposes base color, alpha and lighting.
Since lighting changes the base material perhaps the base materials properties (roughness, transmission etc.) could then be exposed too?

Blend two normal maps

Hello,

I want to create a PBR material that blends two normals maps. The first one should use uv index 0 and the second one should use uv index 1.

Is that possible with lamina?

Best

Module not found: Can't resolve 'react-dom/client'

On NextJS

info  - automatically enabled Fast Refresh for 1 custom loader
wait  - compiling /_error (client and server)...
error - ./node_modules/lamina/index.js:12:0
Module not found: Can't resolve 'react-dom/client

package.json

"dependencies": {
 ...
    "lamina": "^1.1.9",
    "react": "17.0.2",
    "react-dom": "17.0.2",
...
  },

Thanks for any input!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.