0
\$\begingroup\$

I'm doing something in Unity where I need to specify the position and orientation of vertices with two Vector4s, and they're not just position and normal vectors. I've already written my custom shader and now I need to make mesh objects that can be fed into it.

So how do I make my custom mesh? Should I inherit from the mesh class? Will I still be able to use the normal mesh filter and mesh renderer components or should I replace those too? I am comfortable coding the data structure for my new mesh, the question is interfacing with the Unity rendering pipeline and sending the data to my shader in the right way.

\$\endgroup\$
1
  • \$\begingroup\$ I can link a gist in an answer, hopefully today. You don't need to override Mesh, though. Just create a class that builds your mesh programmtically. The Mesh class can already accept any data - that data is usually just provided in a model. I've been using my class to build procedural meshes that can unfold themselves and then be folded (like origami) back into their shape. Unity's existing Mesh, MeshFilter, and MeshRenderer are more than sufficient - you just need to feed them appropriate vertices and normals (and UVs, should you choose to). \$\endgroup\$ – Jesse Williams Sep 1 '20 at 12:22
1
\$\begingroup\$

I don't recommend creating a new Mesh class for this.

Instead, send your additional 4D data to the GPU as texture coordinates. Don't let the name fool you - these don't need to have anything to do with textures, they're just streams of arbitrary float data you can use however you want in the shaders.

This might look something like this:

void Add4DMeshData(Mesh source) {
    var vertices = mesh.vertices;
    var normals = mesh.normals;
    var positions = new Vector4[vertices.Length];
    var orientations = new Vector4[vertices.Length];

    for(int i = 0; i < vertices.Length; i++) {
        positions[i] = Get4DPosition(vertices[i]);
        orientations[i] = Get4DOrientation(normals[i]);
    }
 

    mesh.SetUVs(0, positions);
    mesh.SetUVs(1, orientations);
}

Your shader can then read these streams in its input struct...

struct vs_input {
    float4 position    : TEXCOORD0;
    float4 orientation : TEXCOORD1;
    // etc...
};

...and do whatever you need with them, no new Mesh class required.

\$\endgroup\$
2
  • \$\begingroup\$ And then I suppose I send the regular uv coordinates through the regular vertices channel? \$\endgroup\$ – A. Kriegman Aug 2 '20 at 2:41
  • \$\begingroup\$ You have lots of UV channels to work with, so you don't strictly have to. But the option is available to you. \$\endgroup\$ – DMGregory Aug 2 '20 at 2:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.