<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by William Mishra-Manning on Medium]]></title>
        <description><![CDATA[Stories by William Mishra-Manning on Medium]]></description>
        <link>https://medium.com/@manning.w27?source=rss-384faa1a8ea4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*g6HaOgKi6qPWebDm</url>
            <title>Stories by William Mishra-Manning on Medium</title>
            <link>https://medium.com/@manning.w27?source=rss-384faa1a8ea4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:13:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manning.w27/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Advanced Graphics Programming in Unreal, part 7]]></title>
            <link>https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-7-d3500d4b8195?source=rss-384faa1a8ea4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3500d4b8195</guid>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[technical-art]]></category>
            <category><![CDATA[graphics-programming]]></category>
            <category><![CDATA[unreal-engine-5]]></category>
            <dc:creator><![CDATA[William Mishra-Manning]]></dc:creator>
            <pubDate>Thu, 26 Jun 2025 23:44:05 GMT</pubDate>
            <atom:updated>2026-04-13T03:19:52.779Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a seven-part article series.</p><p>Part 1: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-1-10488f2e17dd">Introduction</a><br>Part 2: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-2-abf8237491c1">Rendering Abstractions (RHI, RDG) and Threading</a><br>Part 3: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-3-f37f4d4407d7">Scenes. Views, and SceneViewExtension</a><br>Part 4: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-4-c89d6fb98b59">Global Shaders</a><br>Part 5: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-5-ea988fd1034e">Simple Material Shaders</a><br>Part 6: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-6-5477dbb64608">Advanced Material Shaders</a><br><strong>Part 7: Mesh-Material Shaders and Mesh Passes</strong></p><h3>Mesh-Material Shaders</h3><p>In this final article, we will go over mesh passes using Mesh-Material Shaders. This is a variant of Material Shaders which draw specific Primitive Components from the game scene.</p><p><strong><em>NOTE: “</em></strong><em>Primitive Component” is what Unreal calls any renderable thing in the world</em></p><p>We will add a mesh pass to the demo that draws into the Game of Life state, making it feel more interactive and tied to the world. I will also add a bonus mesh pass to the Demo which I invite you to explore on your own.</p><h3>Theory</h3><h4>Vertex Factories</h4><p>By now you should be comfortable with the idea that Material Shaders compile against every applicable Material, to create different behaviors within the same shader. Mesh-Material shaders add a second layer of compilation, <strong>Vertex Factories</strong>, to handle the huge variety of geometry in a 3D scene.</p><p>A Static Mesh, Skeletal Mesh, Niagara Particle System, and Random Voxel Plugin you Bought on the Marketplace all have their own kind of <strong>Vertex Factory</strong>, generating the vertex data that your shader needs:</p><ul><li>Static meshes will pull from vertex buffers.</li><li>Skeletal meshes will pull from dynamic vertex buffers, and/or apply dynamic bone transforms in the vertex shader.</li><li>Niagara particles could have a huge variety of vertex data buffers, depending on the specific effect. They can also choose bewteen GPU- or CPU-based storage.</li><li>Third-party plugins that offer custom primitives, such as voxel landscapes, will sometimes have their own Vertex Factory which you can’t plan for.</li></ul><blockquote>Creating your own factory is out of scope for this series, but like all things Unreal it doesn’t seem too hard once you can get through the boilerplate.</blockquote><blockquote>Update: actually it <em>is </em>really complicated. One day I might write a new series on it.</blockquote><p>In Unity, for example, you couldn’t plan on one way to handle all of the different kinds of primitives. In many cases, like skeletal meshes, it’s nearly impossible to get the data you want. But in Unreal you can write your shader to be <em>completely agnostic</em> to all these data formats! You only need one shader to work with all of them, by setting it up to compile against the object’s <strong>Vertex Factory</strong> and invoking that factory’s shader code. It’s the exact same technique used to integrate with Materials.</p><h4>Workflow</h4><p>Writing a custom mesh pass starts pretty simply, with defining a new Mesh-Material shader class and USF file. Usually you will need at least two shaders, Vertex and Pixel, but it’s common to use one USF file to define both of them.</p><p>Unfortunately it doesn’t stop there — the primary workflow for Mesh-Material shaders is significantly different than for others. Here is a quick rundown of what makes them special:</p><p><strong>RDG usage</strong></p><p>The mesh pass should go through the global helper functions AddSimpleMeshPass(…) or AddDrawDynamicMeshPass(…). Both of these take a lambda for you to assemble your draw calls within, executed immediately (not during RDG execution).</p><p>It’s not 100% clear to me what the difference is between the two, but AddDrawDynamicMeshPass(…) is only used for decal rendering in the engine while most other passes seem to use AddSimpleMeshPass(…). The latter takes an FInstanceCullingManager while the former does not, yet you can also pass nullptr for the culling manager and things work fine.</p><p><strong>Components and their Batches</strong></p><p>Any renderable primtive splits its contents into “mesh batches”. A single batch roughly corresponds to a draw call. However you must convert them into real draw calls for your pass, and that means enlisting the help of a “mesh-pass processor” by defining a new child of FMeshPassProcessor.</p><p>In fact, it’s tricky to even get the mesh batches from a primitive in the first place. My library provides a helper to do that, EGP::ForEachBatch(…), which works for all the primitive types tried so far except landscapes — unfortunately I cannot get landscapes working in a mesh pass :(</p><p>Actually, back up even further: merely gathering all the renderable components in a scene is arcane and prone to multithreaded crashes! So again, I made a utility to handle this. It’s explained in detail below, but the gist is that you create a new type of scene component and attach it to any Primitive Component which you want to send to the render pass. If you need to render most/all scene objects in your pass, I recommend editing the engine source to add a new official pass instead of following this article.</p><p><strong>Parameters</strong></p><p>Mesh-Material shaders can’t really use shader parameter structs. You may remember back in article 4, Global Shaders, that there is a “Legacy” workflow for parameters? Now you’re forced to use that. This is described more in detail below.</p><h4>Gathering Primitives</h4><p>In theory, and according to the Unreal docs, it should be possible to iterate over all renderable mesh batches in a Scene-View. However I have never gotten that to work -- the official code snippet iterates over all <em>decals</em> in the scene, which is not terribly useful.</p><p>Instead I like to define a custom component which attaches to specific Primitive Components, to signal them to our mesh pass. This new component handles the tricky details of getting primitive data into the render thread.</p><p>As mentioned before, if you really want a mesh pass that draws most or all of the scene then I highly recommend forking the engine to add it as a new official pass. Not only to get around this problem, but also to get the full performance benefit of static batching which isn’t available to a plugin mesh pass. If you go this route then use the existing mesh passes as a guide; the Renderer module contains an enum of passes and a special array holding each one’s Mesh Pass Processor.</p><p>My library provides a framework for gathering primitives, to go with the Scene-View Extension and Pass object we created back in part 3. Assuming you already have that SVE and Pass object, do the following:</p><ul><li>Create a new child of U_EGP_RenderPassComponent, and attach it to other components which should be part of your mesh pass.</li><li>For any per-object parameters you want in your mesh shader, add fields to this new component. I highly recommend exposing them to Blueprints and the Details panel with (BlueprintReadWrite, EditAnywhere).</li><li>Define a POD proxy struct for the component, holding copies of its fields for the render thread. If you don’t have any fields, just define an empty struct.</li><li>Inside the component class, invoke the macro EGP_PASS_COMPONENT_SIMPLE_PROXY_IMPL(FMyProxy, expr). Here expr is an expression that constructs the proxy struct. If creating your proxy struct is complicated, then paste the definition of the macro into your class to get more control.</li><li>Override GetPassType() to report the type of your pass object, for example u_GOL_RenderPass::StaticClass() .</li><li>Update the parent type of your scene view extension (T_EGP_RenderPassSceneViewExtension ) to have two more template parameters: the new component type, and its proxy struct.</li></ul><p>Now your SVE can easily iterate over all marked components in the scene, by calling ForEachComponent_RenderThread(someLambda). Components also have a toggle to remove them from the effect, which makes them stop appearing in this iteration.</p><h4>Parameters</h4><p>There is no clear way to use parameter structs in a Mesh-Material shader. You need to fall back to the low-level Legacy method, parameter fields, which was explained in the <strong>Detail</strong> section of <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-4-c89d6fb98b59">the 4th article (on Global Shaders)</a>. You can also see it in practice in this article’s <strong>Demo</strong> section.</p><p>Along with the lack of parameter structs, there is a totally different workflow for passing and binding parameters for a mesh pass. The bright side is this new workflow allows you to have different parameter values per-object if you wish.</p><ol><li>Define a custom subtype of FMeshMaterialShaderElementData. This struct represents the parameters for one mesh batch in your custom pass, and the base type only contains some LOD info. Add fields representing your shader parameters, both per-batch and global. If your pass has no parameters, you can use the parent type directly and skip the next two steps.</li><li>In your shader class, shadow the built-in member function GetShaderBindings(...). Change the argument of type FMeshMaterialShaderElementData to your new subtype.</li><li>Inside your GetShaderBindings(...) overload, make sure to call the parent’s implementation, then bind your own shader parameter fields to the element data that was passed in using FMeshDrawSingleShaderBindings. To understand this step better, see the section on <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-4-c89d6fb98b59#0c6d">Legacy parameters back in part 4</a>.</li><li>As you write the Mesh Pass Processor for your pass (covered below), you’ll be creating one instance of the element data struct for each mesh batch. Here is the standard snippet, found within most implementations of FMeshPassProcessor::AddMeshBatch(...) :</li></ol><pre>FMyShaderElementData element;<br>//Set up universal element data (culling, LOD stuff).<br>elementData.InitializeMeshMaterialData(ViewIfDynamicMeshCommand,<br>                                       proxy, batch, staticMeshID,<br>                                       false); //Not always false<br>//Set our own parameters.<br>element.MyFloat = deltaSeconds;<br>element.MyVector = axis;<br>//Now we can pass it into ‘BuildMeshDrawCommands()’.</pre><h4>RDG Resources</h4><p>Despite not being able to use a parameter struct for shaders, you should still make one to inform the RDG of your pass’s inputs and outputs. I believe you could also manually tell the RDG what resources are used and set up render targets yourself through the RHI command-list, but that’s more trouble than making the struct.</p><p>Unfortunately, as far as I can tell, <strong>mesh shaders cannot have RDG texture/buffer parameters</strong>. The reason is that there is no callback to set shader parameters right at the time of execution, after the RDG textures have a real RHI handle backing them. Your textures need to already have valid RHI handles when first setting up the pass.</p><h4>Mesh Pass Processor</h4><p>A Mesh Pass Processor, or MPP, generates the draw calls for your mesh pass given one mesh batch at a time. There is boilerplate to churn through, but the idea isn’t that complicated:</p><ol><li>Override or shadow the function AddMeshBatch(…)</li><li>Compile your shader against the batch’s Material and Vertex Factory</li><li>Pick draw settings like blend mode and depth usage</li><li>Ideally let the Material/batch override those draw settings</li><li>Create an “element data” instance (FMeshMaterialShaderElementData, mentioned above) to feed in your shader parameters</li><li>Generate the draw calls by invoking BuildMeshDrawCommands(…).</li></ol><p>The demo will use a very standard implementation which you can build off of.</p><h4>Pass Execution</h4><p>All that’s left is to dispatch the mesh pass within your Scene-View Extension.</p><p>Call AddSimpleMeshPass(…), provide the parameter struct (still needed to inform RDG) and various other details, and then inside the lambda you can create one or more of your mesh-pass processors and queue up some batches.</p><p>To actually get the mesh batches from the scene, as mentioned before you can execute my SVE helper function ForEachComponent_RenderThread(…) to iterate over each pass component and its associated data — POD proxy, target primitive component, and the POD proxy <em>for </em>the primitive component. Inside this inner lambda, iterate through its batches with EGP::ForEachBatch(…). Finally, inside <em>that </em>lambda, you can call your MPP’s AddMeshBatch(…) implementation. See the demo for an example of this.</p><h3>Demo</h3><p>Let’s add a mesh pass to the Game of Life effect. My demo scene has a variety of primitives in it, and here I give them interesting effect behavior through their Materials.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FpO8ziOCuwk0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpO8ziOCuwk0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FpO8ziOCuwk0%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/abe8f80a2c180bf6baf9d483712f9fac/href">https://medium.com/media/abe8f80a2c180bf6baf9d483712f9fac/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F3viEv-rT8s8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D3viEv-rT8s8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F3viEv-rT8s8%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/29432ba8eb7b9ab05b2d93625c46f071/href">https://medium.com/media/29432ba8eb7b9ab05b2d93625c46f071/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fas4XAPthJBM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Das4XAPthJBM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fas4XAPthJBM%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fa4884aef19430942ef018932b0efb5/href">https://medium.com/media/2fa4884aef19430942ef018932b0efb5/href</a></iframe><p>To make the effects more obvious I’ve cleared out the Init pass in my effect material so that the viewport starts with no living cells. I also removed the previous article’s test behavior in the Simulate pass, which illustrated the behavior of different threshold values.</p><h4>Landscapes :(</h4><p>Unfortunately, while in theory all scene primitives can participate in this pass, I failed to get a landscape working. I had to write a special C++ helper just to find all ULandscapeComponent instances in the scene (they didn’t belong directly to the Landscape actor, seemingly because of large-world-streaming stuff), and then they numbered in the hundreds which destroyed the performance of the custom pass.</p><p>If you want to dig deeper, I left in my C++/BP function which enumerates a landscape’s multiple proxy components. Let me know if you can get landscapes working in your pass!</p><h4>Mesh Pass Component</h4><p>To start, let’s define the component that marks a primitive as being part of the mesh pass. We will also define some per-primitive settings for our pass. For now the only parameter will be a Blend Mode enum, defining how the primitive affects the sim state texture: alpha-blending, additive blending, or multiply blending.</p><p>In the header, above the rest of the render pass, add this:</p><pre>//The blend mode used for a primitive in the GoL mesh pass.<br>UENUM(BlueprintType)<br>enum class EGoLMeshBlendModes<br>{<br>    Alpha,<br>    Additive,<br>    Multiply,<br>    COUNT UMETA(Hidden)<br>};<br>ENUM_RANGE_BY_COUNT(EGoLMeshBlendModes,<br>                    static_cast&lt;int&gt;(EGoLMeshBlendModes::COUNT));<br><br>//A POD struct containing all render parameters for one primitive<br>//    in our Game of Life effect.<br>USTRUCT(BlueprintType)<br>struct GOL_DEMO_API FGoLPrimitiveRenderSettings<br>{<br>    GENERATED_BODY()<br>public:<br><br>    UPROPERTY(BlueprintReadWrite, EditAnywhere)<br>    EGoLMeshBlendModes BlendMode = EGoLMeshBlendModes::Alpha;<br> <br>    bool operator==(const FGoLPrimitiveRenderSettings&amp; r2) const<br>    {<br>        return BlendMode == r2.BlendMode;<br>    }<br>};<br>inline uint32 GetTypeHash(const FGoLPrimitiveRenderSettings&amp; r)<br>{<br>    //Dump all the fields into a tuple and let Unreal hash it for us.<br>    return GetTypeHash(MakeTuple(r.BlendMode));<br>}<br><br>//Marks a primitive-component (mesh, particle system, etc)<br>//    so that it renders into the GoL sim.<br>UCLASS(meta=(BlueprintSpawnableComponent))<br>class GOL_DEMO_API UGoLComponent : public U_EGP_RenderPassComponent<br>{<br>    GENERATED_BODY()<br>public:<br><br>    UPROPERTY(BlueprintReadWrite, EditAnywhere,<br>              meta=(ShowOnlyInnerProperties))<br>    FGoLPrimitiveRenderSettings RenderSettings;<br> <br>    virtual TSubclassOf&lt;U_EGP_RenderPass&gt; GetPassType() const override;<br>    <br>    //The proxy struct is our own custom type,<br>    //    and we need to override some non-templated functions<br>    //    to create/destroy it within a byte buffer.<br>    //In most cases you can do this with the below helper macro.<br>    //The second argument is an R-value that creates the proxy.<br>    EGP_PASS_COMPONENT_SIMPLE_PROXY_IMPL(FGoLPrimitiveRenderSettings,<br>                                         RenderSettings)<br>};</pre><p>Update the SVE’s type signature to mention the component and its proxy:</p><pre>struct GOL_DEMO_API F_GOL_PassSVE<br>    : public T_EGP_RenderPassSceneViewExtension&lt;U_GOL_RenderPass,<br>                                                UGoLComponent,<br>                                                FGoLPrimitiveRenderSettings&gt;<br>...</pre><p>Implement functions in the cpp:</p><pre>TSubclassOf&lt;U_EGP_RenderPass&gt; UGoLComponent::GetPassType() const<br>{<br>    return U_GOL_RenderPass::StaticClass();<br>}</pre><p>Now go into your demo scene and attach this new component to any renderable thing you want to be in the pass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E1oPD2J4ImJuVa6Nq7hqbA.png" /><figcaption>The component on the static mesh, with its settings</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hq9e2hQUsBqiF89cFEOarA.png" /><figcaption>The component on the particle system, with its settings</figcaption></figure><h4>New Material Outputs</h4><p>Previously all our Material shaders were screen-space, using the Post-Process domain, and we had one uber-Material to define all pass behaviors. However the mesh pass will use the Materials already given to each primitive, which are in the Surface domain. We will define new Mesh-pass material output pins, which any 3D material can write to. Example Materials from my demo scene are below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IbZoiZzoLE2Q7EeyXpyISA.png" /><figcaption>The rigged mesh uses its head Fresnel effect as the output of the GoL pass, and the rest of its body has <em>no</em> effect on the pass by feeding the Head mask into the GoL alpha.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*5N89rz9qmdHrvccL4K3a5w.png" /><figcaption>The particle material outputs live cells if rendering its front-face, and dead cells otherwise. The Alpha output is useless because the particles use Additive blending.</figcaption></figure><p>Add the new node to a header file.</p><pre>UCLASS(CollapseCategories, HideCategories=Object,<br>       DisplayName=&quot;GoL Outputs: Mesh&quot;)<br>class GOL_DEMO_API UMaterialExpressionGoLMeshOutputs : public UMaterialExpressionCustomOutput<br>{<br>    GENERATED_BODY()<br>public:<br><br>    UPROPERTY(meta=(RequiredInput=false))<br>    FExpressionInput DiscreteOutput;<br>    UPROPERTY(meta=(RequiredInput=false))<br>    FExpressionInput ContinuousOutput;<br>    UPROPERTY(meta=(RequiredInput=false))<br>    FExpressionInput OutputAlpha;<br><br>    UPROPERTY(EditAnywhere,<br>              meta=(OverridingInputProperty=DiscreteOutput))<br>    float DiscreteOutputConst = 0.5f;<br>    UPROPERTY(EditAnywhere,<br>              meta=(OverridingInputProperty=ContinuousOutput))<br>    float ContinuousOutputConst = 0.5f;<br>    UPROPERTY(EditAnywhere,<br>              meta=(OverridingInputProperty=OutputAlpha))<br>    float OutputAlphaConst = 1.0f;<br><br>    virtual FString GetFunctionName() const override {<br>        return TEXT(&quot;GoL_Outputs_Mesh_&quot;);<br>    }<br>    virtual FString GetDisplayName() const override {<br>        return TEXT(&quot;GoL Outputs: Mesh (pixel shader)&quot;);<br>    }<br><br>#if WITH_EDITOR<br>    virtual void GetCaption(TArray&lt;FString&gt;&amp; output) const override {<br>        output.Add(TEXT(&quot;Game of Life Outputs: “<br>                          “Mesh pass (pixel shader)&quot;));<br>    }<br>    virtual int32 GetNumOutputs() const override { return 3; }<br>    virtual EShaderFrequency GetShaderFrequency() override {<br>        return SF_Pixel;<br>    }<br>    virtual int32 Compile(FMaterialCompiler*, int32 pinIdx) override;<br>#endif<br>};</pre><p>Implement it in a cpp file.</p><pre>int32 UMaterialExpressionGoLMeshOutputs::Compile(FMaterialCompiler* compiler,<br>                                                 int32 pinIdx)<br>{<br>    int32 codeID;<br>    auto doPin = [&amp;](int32 i, FExpressionInput&amp; pin, float* fallback)<br>    {<br>        if (pinIdx != i)<br>            return false;<br>        if (pin.IsConnected())<br>            codeID = pin.Compile(compiler);<br>        else if (fallback)<br>            codeID = compiler-&gt;Constant(*fallback);<br>        else<br>            codeID = INDEX_NONE;<br>        return true;<br>    };<br><br>    if (!doPin(0, DiscreteOutput, &amp;DiscreteOutputConst) &amp;&amp;<br>          !doPin(1, ContinuousOutput, &amp;ContinuousOutputConst) &amp;&amp;<br>          !doPin(2, OutputAlpha, &amp;OutputAlphaConst))<br>    {<br>        codeID = INDEX_NONE;<br>    }<br>    return compiler-&gt;CustomOutput(this, pinIdx, codeID);<br>}</pre><p>Now you can add some initial outputs to your demo scene’s Materials. However they won’t do anything until we create and invoke the new shader.</p><h4>Mesh-Material Shader</h4><p>Start with the HLSL, in a new file <em>Shaders/Mesh.usf</em>:</p><pre>#include &quot;/Engine/Private/Common.ush&quot;<br><br>//Include the Material code THEN the Vertex Factory code.<br>//For Intellisense, as a stand-in,<br>//    use the Material template and a specific built-in vertex factory.<br>#if defined(__RESHARPER__) || defined(__INTELLISENSE__)<br>    #define VERTEXSHADER 1<br>    #define PIXELSHADER 1<br>    #include &quot;/Engine/Private/MaterialTemplate.ush&quot;<br>    #include &quot;/Engine/Private/LocalVertexFactory.ush&quot;<br>#else<br>    #include &quot;/Engine/Generated/Material.ush&quot;<br>    #include &quot;/Engine/Generated/VertexFactory.ush&quot;<br>#endif<br><br>//Define the outputs from the VS into the PS.<br>struct FPassVSToPS<br>{<br>    float4 Position : SV_POSITION;<br><br>    //Generated by the Vertex Factory<br>    FVertexFactoryInterpolantsVSToPS VFInterpolants;<br>};<br><br>#if VERTEXSHADER<br>//The vertex shader is a pretty simple pass-through,<br>//    invoking the Vertex Factory for world-space data<br>//    and the Material for vertex animations.<br>void MainVS(FVertexFactoryInput inputs, out FPassVSToPS outputs)<br>{<br>    //Set up viewport uniforms.<br>    ResolvedView = ResolveView();<br><br>    //Invoke the vertex-factory to get input data.<br>    FVertexFactoryIntermediates vfIntermediates =<br>       GetVertexFactoryIntermediates(inputs);<br>    float4 worldPos4 = VertexFactoryGetWorldPosition(<br>        inputs,<br>        vfIntermediates<br>    );<br>    float3x3 tangentToLocal = VertexFactoryGetTangentToLocal(<br>        inputs,<br>        vfIntermediates<br>    );<br><br>    //Invoke the Material and apply its world-position-offset pin.<br>    FMaterialVertexParameters mParameters =<br>      GetMaterialVertexParameters(inputs, vfIntermediates,<br>                                  worldPos4.xyz, tangentToLocal);<br>    worldPos4.xyz += GetMaterialWorldPositionOffset(mParameters);<br><br>    //Calculate PS inputs.<br>    outputs.VFInterpolants = VertexFactoryGetInterpolantsVSToPS(<br>        inputs, vfIntermediates, mParameters<br>    );<br>    outputs.Position = INVARIANT(mul(<br>        VertexFactoryGetRasterizedWorldPosition(inputs,<br>                                                vfIntermediates,<br>                                                worldPos4),<br>        ResolvedView.TranslatedWorldToClip<br>    ));<br>}<br>#endif<br><br>#if PIXELSHADER<br><br>Texture2D&lt;float2&gt; PreviousStateTex;<br>SamplerState PreviousStateSampler;<br><br>//The pixel shader routes our custom Material output pins<br>//    to the simulation state.<br>void MainPS(in FPassVSToPS inputs //No comma; below macro may be empty<br>            OPTIONAL_IsFrontFace,<br>            //Output includes an Alpha channel for blending,<br>            //   even though the actual texture is two-channel<br>            out float4 outState : SV_Target0)<br>{<br>    //Process uniforms.<br>    #if INSTANCED_STEREO<br>        ResolvedView = ResolveView(input.FactoryInterpolants.EyeIndex);<br>    #else<br>        ResolvedView = ResolveView();<br>    #endif<br><br>    //Process Material and Vertex Factory inputs.<br>    FMaterialPixelParameters mParameters = GetMaterialPixelParameters(<br>        inputs.VFInterpolants, inputs.Position<br>    );<br>    FPixelMaterialInputs mInputs;<br>    CalcMaterialParameters(<br>        mParameters, mInputs,<br>        inputs.Position, bIsFrontFace<br>    );<br><br>    //Read and write our custom outputs.<br>    outState.x =<br>        #if HAVE_GoL_Outputs_Mesh_0<br>            GoL_Outputs_Mesh_0(mParameters)<br>        #else<br>            0<br>        #endif<br>    ;<br>    outState.y =<br>        #if HAVE_GoL_Outputs_Mesh_1<br>            GoL_Outputs_Mesh_1(mParameters)<br>        #else<br>            outState.x<br>        #endif<br>    ;<br>    outState.a =<br>        #if HAVE_GoL_Outputs_Mesh_2<br>            GoL_Outputs_Mesh_2(mParameters)<br>        #else<br>            1.0<br>        #endif<br>    ;<br>}<br><br>#endif</pre><p>Now we can add a new class to the cpp file, along with an “element data” struct holdings its parameters. As mentioned before, we have to use the Legacy parameters here.</p><pre>//Parameters for the mesh pass.<br>//Unfortunately we can&#39;t reference RDG resources here :(<br>struct FGoLMeshShaderElementData : public FMeshMaterialShaderElementData<br>{<br>    FRHITexture* PreviousStateTex;<br>    FRHISamplerState* PreviousStateSampler;<br>};<br><br>class FGoLMeshVS : public FMeshMaterialShader<br>{<br>public:<br>    DECLARE_SHADER_TYPE(FGoLMeshVS, MeshMaterial);<br><br>    static bool ShouldCompilePermutation(const FMeshMaterialShaderPermutationParameters&amp; params)<br>    {<br>        return params.MaterialParameters.MaterialDomain == MD_Surface &amp;&amp;<br>               FMeshMaterialShader::ShouldCompilePermutation(params);<br>    }<br><br>    FGoLMeshVS() = default;<br>    FGoLMeshVS(const ShaderMetaType::CompiledShaderInitializerType&amp; initializer)<br>        : FMeshMaterialShader(initializer)<br>    {<br>    }<br>};<br><br>class FGoLMeshPS : public FMeshMaterialShader<br>{<br>public:<br>    DECLARE_SHADER_TYPE(FGoLMeshPS, MeshMaterial);<br><br>    static bool ShouldCompilePermutation(const FMeshMaterialShaderPermutationParameters&amp; params)<br>    {<br>        return params.MaterialParameters.MaterialDomain == MD_Surface &amp;&amp;<br>               FMeshMaterialShader::ShouldCompilePermutation(params);<br>    }<br><br>    FGoLMeshPS() = default;<br>    FGoLMeshPS(const ShaderMetaType::CompiledShaderInitializerType&amp; initializer)<br>        : FMeshMaterialShader(initializer)<br>    {<br>        //The user&#39;s Material may or may not make use of<br>        //    the previous state texture,<br>        //    so those uniforms must be marked Optional.<br>        PreviousStateTex.Bind(<br>            initializer.ParameterMap,<br>            TEXT(&quot;PreviousStateTex&quot;),<br>            SPF_Optional<br>        );<br>        PreviousStateSampler.Bind(<br>            initializer.ParameterMap,<br>            TEXT(&quot;PreviousStateSampler&quot;),<br>            SPF_Optional<br>        );<br>    }<br><br>    //Binds parameters to the shader for a given element.<br>    void GetShaderBindings(<br>        const FScene* scene,<br>        ERHIFeatureLevel::Type featureLevel,<br>        const FPrimitiveSceneProxy* primitiveSceneProxy,<br>        const FMaterialRenderProxy&amp; materialRenderProxy,<br>        const FMaterial&amp; material,<br>        const FMeshPassProcessorRenderState&amp; drawRenderState,<br>        const FGoLMeshShaderElementData&amp; element,<br>        FMeshDrawSingleShaderBindings&amp; shaderBindings) const<br>    {<br>        FMeshMaterialShader::GetShaderBindings(<br>            scene, featureLevel,<br>            primitiveSceneProxy, materialRenderProxy, material,<br>            drawRenderState, element, shaderBindings<br>        );<br><br>        shaderBindings.AddTexture(PreviousStateTex, PreviousStateSampler,<br>                                  element.PreviousStateSampler,<br>                                  element.PreviousStateTex);<br>    }<br><br>private:<br><br>    LAYOUT_FIELD(FShaderResourceParameter, PreviousStateTex);<br>    LAYOUT_FIELD(FShaderResourceParameter, PreviousStateSampler);<br>};<br><br>IMPLEMENT_MATERIAL_SHADER_TYPE(, FGoLMeshVS, TEXT(&quot;/GameOfLife/Mesh.usf&quot;),<br>                               TEXT(&quot;MainVS&quot;), SF_Vertex);<br>IMPLEMENT_MATERIAL_SHADER_TYPE(, FGoLMeshPS, TEXT(&quot;/GameOfLife/Mesh.usf&quot;),<br>                               TEXT(&quot;MainPS&quot;), SF_Pixel);<br><br>//This struct doesn&#39;t feed into either shader,<br>//    but tells the RDG about our mesh pass.<br>BEGIN_SHADER_PARAMETER_STRUCT(FGoLMeshPassParameters, )<br>    SHADER_PARAMETER_RDG_TEXTURE_SRV(Texture2D&lt;float2&gt;, PrevState)<br>    SHADER_PARAMETER_STRUCT_REF(FViewUniformShaderParameters, View)<br>    SHADER_PARAMETER_RDG_UNIFORM_BUFFER(FSceneUniformParameters, Scene)<br>    SHADER_PARAMETER_STRUCT_INCLUDE(FInstanceCullingDrawParams,<br>                                    InstanceCullingDrawParams)<br>    RENDER_TARGET_BINDING_SLOTS()<br>END_SHADER_PARAMETER_STRUCT()</pre><h4>Execute the Pass</h4><p>Lastly we need to draw this pass in our Scene-View Extension, enlisting the help of a new Mesh Pass Processor.</p><p>Put this in your cpp file:</p><pre>//New includes we&#39;ll need:<br>#include &quot;Runtime/Renderer/Public/MeshPassProcessor.inl&quot;<br>#include &quot;SimpleMeshDrawCommandPass.h&quot;<br>#include &quot;EGP_DownsampleDepthPass.h&quot;<br>#include &quot;EGP_GetMeshBatches.h&quot;<br><br>//Generates GoL draw calls for any kind of 3D primitive.<br>class FGoLMeshProcessor final : public FMeshPassProcessor<br>{<br>public:<br><br>    FMeshPassProcessorRenderState PassDrawState;<br><br>    FGoLMeshProcessor(const FScene* scene, const FSceneView* view,<br>                      ERHIFeatureLevel::Type featureLevel,<br>                      FMeshPassDrawListContext* commandsOutput,<br>                      FBlendStateRHIRef blendState)<br>        : FMeshPassProcessor(scene, featureLevel, view, commandsOutput)<br>    {<br>        PassDrawState.SetBlendState(blendState);<br>        PassDrawState.SetDepthStencilState(<br>            TStaticDepthStencilState&lt;false, CF_DepthNearOrEqual&gt;::GetRHI()<br>        );<br>    }<br><br>    void AddMeshBatch(const FMeshBatch&amp; batch, uint64 batchElementMask,<br>                      const FPrimitiveSceneProxy* proxy,<br>                      int32 staticMeshID,<br>                      FRHITexture* prevState,<br>                      FRHISamplerState* prevStateSampler)<br>    {<br>        //Get the first usable Material in the chain,<br>        //    starting at the batch&#39;s desired Material<br>        //    and ending at the Default Material.<br>        const FMaterialRenderProxy* fallbackMat = nullptr;<br>        const auto&amp; resource =<br>            batch.MaterialRenderProxy-&gt;GetMaterialWithFallback(<br>                FeatureLevel, fallbackMat<br>            );<br>        const auto&amp; materialProxy = fallbackMat ?<br>                                      *fallbackMat :<br>                                      *batch.MaterialRenderProxy;<br>        <br>        //Compile our shaders against<br>        //    the batch&#39;s Material and Vertex-Factory.<br>        TMeshProcessorShaders&lt;FGoLMeshVS, FGoLMeshPS&gt; shaderRefs;<br>        {<br>            FMaterialShaderTypes shaderTypes;<br>            shaderTypes.AddShaderType&lt;FGoLMeshVS&gt;();<br>            shaderTypes.AddShaderType&lt;FGoLMeshPS&gt;();<br><br>            FMaterialShaders materialShaders;<br>            verify(resource.TryGetShaders(<br>                shaderTypes,<br>                batch.VertexFactory-&gt;GetType(),<br>                materialShaders<br>            ));<br><br>            materialShaders.TryGetVertexShader(shaderRefs.VertexShader);<br>            materialShaders.TryGetPixelShader(shaderRefs.PixelShader);<br>        }<br><br>        //Configure per-element settings.<br>        FGoLMeshShaderElementData elementData;<br>        elementData.InitializeMeshMaterialData(<br>            ViewIfDynamicMeshCommand, proxy, batch, staticMeshID, false<br>        );<br>        //Set our shader parameters.<br>        elementData.PreviousStateTex = prevState;<br>        elementData.PreviousStateSampler = prevStateSampler;<br><br>        //Generate the draw calls for this batch.<br>        const FMeshDrawingPolicyOverrideSettings overrides =<br>            ComputeMeshOverrideSettings(batch);<br>        BuildMeshDrawCommands(<br>            batch, batchElementMask, proxy,<br>            materialProxy, resource, PassDrawState,<br>            MoveTemp(shaderRefs),<br>            ComputeMeshFillMode(resource, overrides),<br>            ComputeMeshCullMode(resource, overrides),<br>            FMeshDrawCommandSortKey::Default, EMeshPassFeatures::Default,<br>            elementData<br>        );<br>    }<br>    <br>    //The usual &#39;AddMeshBatch()&#39; will not be used; instead<br>    //    we will use the above alternative with more parameters.<br>    virtual void AddMeshBatch(const FMeshBatch&amp; batch,<br>                              uint64 batchElementMask,<br>                              const FPrimitiveSceneProxy* proxy,<br>                              int32 staticMeshID) override {<br>        check(false);<br>    }<br>};</pre><p>Then go into the SVE’s render callback, right after Simulate and before Display, and add this mesh pass:</p><pre>//Draw our mesh pass into the sim state.<br>RDG_EVENT_SCOPE(graph, &quot;GoL: Mesh passes (%i primitives)&quot;,<br>                Pass-&gt;GetComponentData_RenderThread().Num());<br>{<br><br>FScene* renderScene = nullptr;<br>if (view.Family != nullptr &amp;&amp; view.Family-&gt;Scene != nullptr)<br>    renderScene = view.Family-&gt;Scene-&gt;GetRenderScene();<br><br>//We want to use the scene&#39;s depth-texture for our mesh pass,<br>//    however the Game of Life state texture exists on its own<br>//    rather than being a subset of a larger render target,<br>//    and also uses a lower resolution than the viewport.<br>//To fix this, we need to resample the depth buffer.<br>FRDGTextureRef depthBuffer = inputs.SceneTextures-&gt;GetContents()<br>                                -&gt;SceneDepthTexture;<br>if (view.ViewRect.Min != FIntPoint::ZeroValue ||<br>    depthBuffer-&gt;Desc.Extent != viewData.SimState-&gt;GetSizeXY())<br>{<br>    auto resampledDepthBufferDesc = depthBuffer-&gt;Desc;<br>    resampledDepthBufferDesc.Extent = viewData.SimState-&gt;GetSizeXY();<br>    FRDGTextureRef resampledDepthBuffer = graph.CreateTexture(<br>        resampledDepthBufferDesc, TEXT(&quot;GoL_ResampledSceneDepth&quot;)<br>    );<br>    <br>    EGP::AddDownsampleDepthPass(<br>        graph, view,<br>        FScreenPassTexture{ depthBuffer, view.ViewRect },<br>        FScreenPassRenderTarget{ resampledDepthBuffer,<br>                                 ERenderTargetLoadAction::ENoAction },<br>        EDownsampleDepthFilter::Checkerboard<br>    );<br>    depthBuffer = resampledDepthBuffer;<br>}<br><br>auto nextSimStateRDG = RegisterExternalTexture(<br>    graph, viewData.SimBuffer,<br>    TEXT(&quot;GoL_NextState&quot;)<br>);<br><br>//Set up the RDG configuration of the pass.<br>auto* passParams = graph.AllocParameters&lt;FGoLMeshPassParameters&gt;();<br>passParams-&gt;View = view.ViewUniformBuffer;<br>passParams-&gt;Scene = GetSceneUniformBufferRef(graph, view);<br>passParams-&gt;PrevState =<br>    graph.CreateSRV(FRDGTextureSRVDesc{ simStateRDG });<br>passParams-&gt;RenderTargets[0] = FRenderTargetBinding{<br>    nextSimStateRDG,<br>    ERenderTargetLoadAction::ELoad<br>};<br>passParams-&gt;RenderTargets.DepthStencil = {<br>    depthBuffer,<br>    ERenderTargetLoadAction::ELoad,<br>    FExclusiveDepthStencil::DepthRead_StencilNop<br>};<br><br>//Dispatch the draw calls.<br>AddCopyTexturePass(graph, simStateRDG, nextSimStateRDG);<br>AddSimpleMeshPass(graph, passParams, renderScene, view, nullptr,<br>                  RDG_EVENT_NAME(&quot;GoLMeshes&quot;),<br>                  FIntRect{ FIntPoint::ZeroValue,<br>                            simStateRDG-&gt;Desc.Extent },<br>                  [&amp;](FDynamicPassMeshDrawListContext* output)<br>{<br>    //Define one mesh processor for each blend mode.<br>    FGoLMeshProcessor meshProcessorAlpha{<br>        renderScene, &amp;view, view.FeatureLevel, output,<br>        TStaticBlendState&lt;CW_RGBA, BO_Add,<br>                          BF_SourceAlpha, BF_InverseSourceAlpha<br>                         &gt;::GetRHI()<br>    };<br>    FGoLMeshProcessor meshProcessorAdditive{<br>        renderScene, &amp;view, view.FeatureLevel, output,<br>        TStaticBlendState&lt;CW_RGBA, BO_Add, BF_One, BF_One&gt;::GetRHI()<br>    };<br>    FGoLMeshProcessor meshProcessorMultiply{<br>        renderScene, &amp;view, view.FeatureLevel, output,<br>        TStaticBlendState&lt;CW_RGBA, BO_Add,<br>                          BF_DestColor, BF_Zero<br>                         &gt;::GetRHI()<br>    };<br><br>    //For every scene primitive tagged with our component...<br>    ForEachComponent_RenderThread([&amp;](<br>                     const UGoLComponent&amp; component,<br>                     const FGoLPrimitiveRenderSettings&amp; componentSettings,<br>                     const UPrimitiveComponent&amp; primitive,<br>                     const FPrimitiveSceneProxy&amp; primitiveProxy<br>                    ) {<br>        //Pick the appropriate MPP for our blend mode.<br>        FGoLMeshProcessor* componentProcessor;<br>        switch (componentSettings.BlendMode)<br>        {<br>            case EGoLMeshBlendModes::Alpha:<br>                componentProcessor = &amp;meshProcessorAlpha;<br>            break;<br>            case EGoLMeshBlendModes::Additive:<br>                componentProcessor = &amp;meshProcessorAdditive;<br>            break;<br>            case EGoLMeshBlendModes::Multiply:<br>                componentProcessor = &amp;meshProcessorMultiply;<br>            break;<br>            default: check(false); return;<br>        }<br>        <br>        //... and for every renderable mesh-batch within that component...<br>        EGP::ForEachBatch(view, &amp;primitiveProxy,<br>                          [&amp;](const FMeshBatch&amp; batch, uint64 mask,<br>                              const auto* sceneProxy,<br>                              int staticMeshIdIfApplicable)<br>        {<br>            //...draw that batch.<br>            componentProcessor-&gt;AddMeshBatch(<br>                batch, mask, sceneProxy, staticMeshIdIfApplicable,<br>                viewData.SimState,<br>                TStaticSamplerState&lt;SF_Bilinear,<br>                                    AM_Clamp, AM_Clamp<br>                                   &gt;::GetRHI());<br>        });<br>    });<br>});<br><br>//Swap &#39;previous&#39; and &#39;next&#39; textures.<br>std::swap(viewData.SimBuffer, viewData.SimState);<br>simStateRDG = nextSimStateRDG;<br><br>}</pre><p>And that’s it! You should be able to see your 3D scene affect the Game of Life now. Congrats on making it to the end of this series!</p><h3>Code</h3><p>The mesh pass and Bonus Render Effect (BRE for short) is added in the <em>part/7</em> branch:</p><p><a href="https://github.com/heyx3/UnrealExtendedGraphicsProgrammingDemo/tree/part/7">heyx3/UnrealExtendedGraphicsProgrammingDemo at part/7</a></p><h3>Details</h3><h4>Unanswered Questions</h4><p>Despite all my research there are many things I’m left wondering. If you know, please reach out to me (or comment on this article) so I can get these questions answered!</p><ol><li>How can I iterate over all visible mesh batches for a given FViewInfo?</li><li>Is it feasible to include a Landscape in our custom mesh pass? How do I get the landscape components and iterate over their mesh batches?</li><li>Is it possible at all to bind RDG resources (textures, buffers) to a mesh-material shader and/or mesh pass processor?</li><li>Is there some way of managing external per-viewport data that I missed?</li><li>How do I fix the problem with my shaders not being initially compiled, causing the Initialize shader to run with the Default Material instead?</li><li>If any Epic graphics programmer is reading this, please for the love of God clean up your shaders! I get ~30,000 warnings when cooking,  which makes it impossible to look for warnings in my own shaders.</li></ol><h4>UE::MeshPassUtils::Dispatch</h4><p>It appears there’s a small utility in the engine to dispatch mesh-material compute shaders without all the rigamarole of a Mesh-Pass Processor. It’s only used in the engine for volumetric rendering, but looks very useful for anybody doing 3D compute work! You can find it in <em>Renderer/Public/MeshPassUtils.h</em>.</p><h4>Mesh Pass Processors</h4><p>You may notice that the mesh pass processor has a virtual AddMeshBatch(…), which our demo did not use because we wanted to pass some custom parameters in. This virtual function will not be called anywhere in your mesh pass, and may as well not exist. I suspect it is vestigial, or only relevant for the official built-in passes.</p><p>The function BuildMeshDrawCommands(…), which you call within AddMeshBatch(…), is a template. However it is <em>not</em> defined anywhere in the class’s header. It’s contained in a <em>.inl</em> file, and you have to add #include “Runtime/Renderer/Public/MeshPassProcessor.inl” in your own cpp or you’ll get a linker error about the function not having a definition. It’s not unheard of to use <em>.inl</em> files in C++ to separate template implementations from the rest of a header, but I’ve never seen a setup that requires users to include the file themselves in every cpp that calls it! Usually it’s included at the bottom of the header.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3500d4b8195" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Graphics Programming in Unreal, part 6]]></title>
            <link>https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-6-5477dbb64608?source=rss-384faa1a8ea4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5477dbb64608</guid>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[graphics-programming]]></category>
            <category><![CDATA[technical-art]]></category>
            <category><![CDATA[unreal-engine-5]]></category>
            <dc:creator><![CDATA[William Mishra-Manning]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 17:29:24 GMT</pubDate>
            <atom:updated>2026-04-13T03:11:50.978Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a seven-part article series.</p><p>Part 1: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-1-10488f2e17dd">Introduction</a><br>Part 2: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-2-abf8237491c1">Rendering Abstractions (RHI, RDG) and Threading</a><br>Part 3: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-3-f37f4d4407d7">Scenes. Views, and SceneViewExtension</a><br>Part 4: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-4-c89d6fb98b59">Global Shaders</a><br>Part 5: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-5-ea988fd1034e">Simple Material Shaders</a><br><strong>Part 6: Advanced Material Shaders</strong><br>Part 7: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-7-d3500d4b8195">Mesh-Material Shaders and Mesh Passes</a></p><h3><strong>Advanced Material Shaders</strong></h3><p>In the last article we rebuilt the Game-of-Life effect using Material shaders instead of Global shaders, so that most of the effect behavior can be controlled by tech-artists in a special Material. However, the graph for this material is pretty hacky:</p><ol><li>Post-process Materials only have 3 scalar outputs (Emissive RGB) which is extremely limiting.</li><li>We didn’t provide any special inputs to the Material graph apart from the Sim State texture.</li><li>We had to tack a strange switch statement onto the end of the graph to do different things for different passes.</li></ol><p>In this article we’ll add custom Material inputs and outputs, greatly expanding the flexibility and ease-of-use for artists playing with our custom effect.</p><h3>Theory</h3><h4>Custom Material Inputs</h4><p>I alluded to custom inputs several times in the previous article. It’s actually pretty easy to implement!</p><ul><li>Just before your shader includes Material code, add some static<em> </em>global variables for your inputs and a preprocessor token to hint that they exist.<br>–The token is needed because each Material gets compiled against nearly <em>every </em>shader in its domain, including the one that renders the Material preview, so there will be shaders that use your graph without defining your globals.</li><li>As soon as possible, especially before your shader executes any Material output pins (Get Emissive Color, Get Opacity, etc), make sure to set those globals.</li><li>Expose them to the Material graph using a Material Function asset, containing a custom HLSL node that reads and returns their values. This node uses the above preprocessor token, returning stub values if running within a different shader.</li></ul><h4>Custom Material Outputs</h4><p>Custom outputs are defined as a new UCLASS() inheriting from UMaterialExpressionCustomOutput. They, along with Material Function assets, are the <strong>only</strong> extension you can make to Material graphs without modifying the engine. If you try inheriting from other node classes you’ll get linker errors.</p><p>A custom output node looks exactly like the standard Material outputs with a beige title bar. There are several built-in examples you may have seen already, such as Strata and Landscape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*1W_OwmC4yNHIL7sTCwjq8Q.png" /><figcaption>A custom output from our Xray renderer at work</figcaption></figure><p>Each new output node can apply to a <em>single </em>shader frequency, so you usually want about one per Material shader. Do the following to configure it assuming you have a hard-coded set of simple output pins (for more complex cases look at the base class and all the examples in-engine):</p><p>For convenience, give it the UCLASS<em> </em>properties CollapseCategories, HideCategories=Object.</p><p>Also give it a DisplayName, which appears in the popup menu when selecting a Material node.</p><p>Define each of your output pins as fields:</p><pre>UPROPERTY(meta=(RequiredInput=true))<br>FExpressionInput MyPin;</pre><p>The name of the graph pin comes from the name of the field. If RequiredInput is true, users are forced to write to this pin whenever the node exists.</p><p>If you want the pin to provide a fallback textbox, for the user to enter a constant value, add a companion field:</p><pre>UPROPERTY(meta=(OverridingInputProperty=MyPin))<br>float MyPinF;</pre><p>Define any other UPROPERTY fields you want. Properties marked with EditAnywhere will appear in the node’s Details panel.</p><p>Within an #if WITH_EDITOR block, override the following functions from the UMaterialExpression interface:</p><ul><li>void GetCaption(TArray&lt;FString&gt;&amp; output) const : generates the title of this node as it should appear in the graph.</li><li>int32 GetNumOutputs() const : tells the shader compiler how many outputs pins you have.</li><li>EShaderFrequency GetShaderFrequency() : tells the shader compiler which frequency these outputs are used in (compute, pixel, vertex, etc).</li><li>int32 Compile(FMaterialCompiler* compiler, int32 pinIdx) : generates code for the given output pin. This function is covered in detail below.</li></ul><p>Override the following functions (<em>not</em> within an #if WITH_EDITOR block) from the UMaterialExpressionCustomOutput interface:</p><ul><li>FString GetFunctionName() const : a prefix that is used in the shader to query your outputs; it must be a legal HLSL token and probably shouldn’t start with an underscore to be safe. This prefix is covered in detail below.</li><li>FString GetDisplayName() const : I can’t figureo ut where this name actually appears, but it doesn’t need to be a valid HLSL token. You can just return the same value as in GetCaption() or DisplayName.</li></ul><p>The Compile function is very important, but not too complicated. Generally you check whether the pin is set, compile it if so, and otherwise fall back to a constant value or omit the pin entirely. Here is a sample from our own X-ray renderer, which offers two output pins:</p><pre>int32 codeID;<br>if (pinIdx == 0)<br>{<br>    codeID = LbufferOverridePin.IsConnected() ?<br>                 LbufferOverridePin.Compile(compiler) :<br>                 INDEX_NONE;<br>}<br>else if (pinIdx == 1)<br>{<br>    codeID = SurfaceThickeningDropoffPin.IsConnected() ?<br>                 SurfaceThickeningDropoffPin.Compile(compiler) :<br>                 compiler-&gt;Constant(SurfaceThickeningDropoffConst);<br>}<br>else //Unknown pin idx<br>{<br>    codeID = INDEX_NONE;<br>}<br>return compiler-&gt;CustomOutput(this, pinIdx, codeID);</pre><p><strong><em>NOTE: </em></strong><em>even if the pin isn’t set to anything, we still want to call </em><em>compiler-&gt;CustomOutput(…), passing it </em><em>INDEX_NONE for the output value. This generates shader code to indicate the pin is empty.</em></p><p>Once the above is in place, the compiler will start generating new Material code in <em>all </em>shaders. New preprocessor tokens tell whether each of our output pins are written to, and new functions tell us how to compute them. This is where GetFunctionName() comes in; for example if it returns TEXT(“MyCustomOuts”) then you will have access to the following:</p><ul><li>One preprocessor token per output pin, telling you whether that pin has a value — HAVE_MyCustomOuts0, HAVE_MyCustomOuts1, etc.</li><li>A function you can call to execute the pin, IF it has a value — MyCustomOuts0(matParameters), MyCustomOuts1(matParameters), etc.</li></ul><p>Here is some shader code from our X-ray render effect:</p><pre>//Did the Material provide an override for the L-buffer value?<br>#if HAVE_GetXrayPixelOutput0<br>    outLbuffer = GetXrayPixelOutput0(materialParameters);<br>//If not, then compute it the standard way. <br>#else<br>    outLbuffer = length(input.WorldPosition.xyz) * (isFrontFace ? -1 : 1);<br>#endif</pre><h3>Demo</h3><p>Let’s start with custom inputs.</p><h4>Custom Inputs</h4><p>Of all our shaders only <em>Simulate</em> really has extra data we could give to the Material Graph, namely the current cell state and the neighboring cell states.</p><p>All our Material shaders already define a preprocessor token to indicate which one is being compiled. Let’s add static globals alongside them in <em>Simulate</em>:</p><pre>//At the top of Simulate.usf:<br><br>#include &quot;/EGP/ScreenPass/pre.ush&quot;<br><br>#define GOL_PASS_SIMULATE 1<br>//Custom Material inputs!<br>static float MaterialDeltaSeconds;<br>static float2 MaterialNeighborStates[9];<br><br>#include &quot;/EGP/ScreenPass/post.ush&quot;<br><br>...<br><br>//In the main function, just after setting up ‘matInputs’ and ‘matParams’,<br>//    and after sampling our neighborhood of 9 cells ‘prevStates’:<br>MaterialDeltaSeconds = DeltaSeconds; <br>for (int i = 0; i &lt; 9; ++i)<br>    MaterialNeighborStates[i] = prevStates[i];<br>//Now when we invoke Material output pins, they can read those globals.</pre><p>Next add a Material Function asset which reads those globals. Since the shader and effects code is all in a plugin, <em>GOL_Demo/</em>, this asset will go in the plugin content folder <em>GOL_Demo/Content</em>. Plugin content folders aren’t visible in the editor by default, but they always exist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sd8s_YOI5PZsd9oPjrJNlA.png" /><figcaption>Pay attention to the asset settings on the left too!</figcaption></figure><blockquote>(I just noticed the above screenshot screws up the last two outputs, but from their names you should be able to infer what I meant)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*OPtmBBFZOCz635ydEFSAQg.png" /><figcaption>The Custom HLSL code that reads our inputs. Also provided below.</figcaption></figure><pre>#if defined(GOL_PASS_SIMULATE)<br>    deltaSeconds = MaterialDeltaSeconds;<br>    ourState = MaterialNeighborStates[4];<br><br>    neighborPopulationCount = 0;<br>    averageLivingNeighborState = 0;<br>    for (int i = 0; i &lt; 9; ++i)<br>        if (i != 4)<br>        {<br>            float2 n = MaterialNeighborStates[i];<br>            neighborPopulationCount +=n.x;<br>            averageLivingNeighborState += n.y * step(0.5, n.x);<br>        }<br>    averageLivingNeighborState /= max(1.0, neighborPopulationCount);<br><br><br>#else<br>    //Stub values for other shaders<br>    deltaSeconds = 0.001;<br>    ourState = float2(1.0, 0.85);<br>    neighborPopulationCount = 3;<br>    averageLivingNeighborState = 0.5;<br>#endif<br><br>return 0; //value not actually used</pre><p>Now you can drop this input into your graph and use it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nCwsePw2e2WQJ1FrlPcHfg.png" /><figcaption>With ‘Expose to Library’ checked, the MaterialFunction shows up in the context menu</figcaption></figure><h4>Custom Outputs: Init shader</h4><p>Outputs are more complicated than inputs. To reiterate, we are replacing that hacky switch statement into Emissive Color, with totally separate output nodes per shader.</p><p>Start with the simplest case, <em>Init</em>. We need one required output for the discrete state, and one optional output for the continuous state which defaults to the discrete value.</p><pre>//In a C++ header: <br><br>#include &quot;Materials/MaterialExpressionCustomOutput.h&quot;<br><br>UCLASS(CollapseCategories, HideCategories=Object,<br>       DisplayName=&quot;GoL Outputs: Init&quot;)<br>class GOL_DEMO_API UMaterialExpressionGoLInitOutputs<br>    : public UMaterialExpressionCustomOutput<br>{<br>    GENERATED_BODY()<br>public:<br><br>    //Automatically snapped to 0 or 1.<br>    UPROPERTY(meta=(RequiredInput=true))<br>    FExpressionInput InitialBinaryState;<br><br>    //If not set, defaults to the binary state value<br>    //    (before it&#39;s snapped to 0 or 1).<br>    UPROPERTY(meta=(RequiredInput=false))<br>    FExpressionInput InitialContinuousState;<br> <br>    virtual FString GetFunctionName() const override {<br>        return TEXT(&quot;GoL_Outputs_Init_&quot;);<br>    }<br>    virtual FString GetDisplayName() const override {<br>        return TEXT(&quot;GoL Outputs: Init&quot;);<br>    }<br><br>    #if WITH_EDITOR<br>        virtual void GetCaption(TArray&lt;FString&gt;&amp; output) const override {<br>            output.Add(TEXT(&quot;Game of Life Outputs: Init pass&quot;));<br>        }<br>        virtual int32 GetNumOutputs() const override { return 2; }<br>        virtual EShaderFrequency GetShaderFrequency() override {<br>            return SF_Pixel;<br>        }<br>        virtual int32 Compile(class FMaterialCompiler*,<br>                              int32 pinIdx) override;<br>    #endif<br>};<br><br><br>...<br><br><br>//In a C++ cpp file:<br><br>#include &quot;MaterialCompiler.h&quot;<br><br>#if WITH_EDITOR<br>int32 UMaterialExpressionGoLInitOutputs::Compile(FMaterialCompiler* compiler,<br>                                                 int32 pinIdx)<br>{<br>    int32 codeID;<br>    if (pinIdx == 0)<br>    {<br>        codeID = InitialBinaryState.IsConnected() ?<br>                     InitialBinaryState.Compile(compiler) :<br>                     INDEX_NONE;<br>    }<br>    else if (pinIdx == 1)<br>    {<br>        //The default behavior is controlled in the shader, not here<br>        codeID = InitialContinuousState.IsConnected() ?<br>                     InitialContinuousState.Compile(compiler) :<br>                     INDEX_NONE;<br>    }<br>    else<br>    {<br>        codeID = INDEX_NONE;<br>    }<br>    return compiler-&gt;CustomOutput(this, pinIdx, codeID);<br>}<br>#endif<br><br><br>...<br><br><br>//In Init.usf, replace the code that reads from Material Emissive pin<br>//    with this:<br><br>//Read the starting state from the Material.<br><br>//  1. The &quot;discrete state&quot; output.<br>#if HAVE_GoL_Outputs_Init_0<br>    newState.x = GoL_Outputs_Init_0(matParams);<br>#else<br>    //The first pin must be set,<br>    //    but unrelated post-process Materials will compile without it,<br>    //    so this branch happens sometimes and we&#39;ll use a dummy value.<br>    newState.x = 0;<br>#endif<br><br>//  2. The &quot;continuous state&quot; output.<br>#if HAVE_GoL_Outputs_Init_1<br>    newState.y = HAVE_GoL_Outputs_Init_1(matParams);<br>#else<br>    //If not set, the pin defaults to the other one&#39;s value.<br>    newState.y = newState.x;<br>#endif<br><br>//Sanitize the inputs from the Material.<br>newState.x = step(0.5, SafeSaturate(newState.x));<br>newState.y = SafeSaturate(newState.y);</pre><p>Finally, go into the Material and use these new output pins instead of the switch statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*9pKopmECFSe4OrPWJLZK_w.png" /></figure><p>Run the demo and see that the effect is unchanged.</p><h4>Custom Outputs: Display shader</h4><p>It’s actually quite natural for Display to output to the Emissive Color pin, since this shader does exactly the same thing as a real post-process Material! So let’s plug it directly into Emissive Color.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*UeWiw1wbcOEVtRpSkYAcnw.png" /><figcaption>Delete the switch node entirely; only Display writes to Emissive Color now.</figcaption></figure><p>This does mean we have less control over our Material preview. If your project ends up with many different effect Materials, it can be nice to clearly indicate which is which by writing a specific color in the Material Preview, so you may want to bring that switch node back.</p><p>More importantly, we broke the Simulate pass. Let’s fix that and finish this article.</p><h4>Multi-stage Inputs and Outputs: Simulate shader</h4><p>What’s interesting about the Simulate pass is that it involves a <em>sequence</em> of decisions: read the neighboring cells, decide on the discrete state, compute a speed for the continuous state, then apply that speed towards the discrete state. To give maximum control to the Material graph, we will split the inputs and outputs for this shader into several stages.</p><ol><li>Read neighboring cells and decide whether ours is living or dead.<br>–<strong>Inputs</strong>: cell states (already provided in the Material Function we created earlier)<br>–<strong>Outputs: </strong>several Game of Life thresholds — underpopulation, ideal population, and overpopulation.</li><li>Given our new alive/dead discrete state, decide on the new continuous state.<br>–<strong>Inputs: </strong>the previous inputs, plus the new discrete state for our cell, and the associated severityT value computed in the shader.<br>–<strong>Outputs: </strong>the new continuous state for our cell</li></ol><p>This setup means we need more inputs coming in from a second Material Function, for our second stage. We also need two different output nodes for each stage’s output.</p><p>In a C++ header, add the two new output nodes:</p><pre>UCLASS(CollapseCategories, HideCategories=Object,<br>       DisplayName=&quot;GoL Outputs: Simulate (pt 1)&quot;)<br>class GOL_DEMO_API UMaterialExpressionGoLSimulate1Outputs<br>    : public UMaterialExpressionCustomOutput<br>{<br>    GENERATED_BODY()<br>public:<br><br>    UPROPERTY(meta=(RequiredInput=false),<br>              DisplayName=&quot;Threshold: Underpopulated&quot;)<br>    FExpressionInput ThresholdTooFew;<br>    UPROPERTY(meta=(OverridingInputProperty=ThresholdTooFew))<br>    float ThresholdTooFewConst = 2.0f;<br> <br>    UPROPERTY(meta=(RequiredInput=false),<br>              DisplayName=&quot;Threshold: Ideal&quot;)<br>    FExpressionInput ThresholdResurrect;<br>    UPROPERTY(meta=(OverridingInputProperty=ThresholdResurrect))<br>    float ThresholdResurrectConst = 2.5f;<br> <br>    UPROPERTY(meta=(RequiredInput=false),<br>              DisplayName=&quot;Threshold: Overpopulation&quot;)<br>    FExpressionInput ThresholdTooMany;<br>    UPROPERTY(meta=(OverridingInputProperty=ThresholdTooMany))<br>    float ThresholdTooManyConst = 3.0f;<br> <br>    virtual FString GetFunctionName() const override {<br>        return TEXT(&quot;GoL_Outputs_Simulate_Pt1_&quot;);\<br>    }<br>    virtual FString GetDisplayName() const override {<br>        return TEXT(&quot;GoL Outputs: Simulate (part 1)&quot;);<br>    }<br><br>    #if WITH_EDITOR<br>        virtual void GetCaption(TArray&lt;FString&gt;&amp; output) const override {<br>            output.Add(TEXT(&quot;Game of Life Outputs: “<br>                              “Simulate pass (part 1)&quot;));<br>        }<br>        virtual int32 GetNumOutputs() const override { return 3; }<br>        virtual EShaderFrequency GetShaderFrequency() override {<br>            return SF_Compute;<br>        }<br>        virtual int32 Compile(FMaterialCompiler*, int32 pinIdx) override;<br>    #endif<br>};<br><br>UCLASS(CollapseCategories, HideCategories=Object,<br>       DisplayName=&quot;GoL Outputs: Simulate (pt 2)&quot;)<br>class GOL_DEMO_API UMaterialExpressionGoLSimulate2Outputs<br>    : public UMaterialExpressionCustomOutput<br>{<br>    GENERATED_BODY()<br>public:<br><br>    //If not provided, the continuous state will match the discrete one.<br>    UPROPERTY(meta=(RequiredInput=false))<br>    FExpressionInput ContinuousValue;<br> <br>    virtual FString GetFunctionName() const override {<br>        return TEXT(&quot;GoL_Outputs_Simulate_Pt2_&quot;); }<br>    virtual FString GetDisplayName() const override {<br>        return TEXT(&quot;GoL Outputs: Simulate (part 2)&quot;);<br>    }<br><br>    #if WITH_EDITOR<br>        virtual void GetCaption(TArray&lt;FString&gt;&amp; output) const override {<br>            output.Add(TEXT(&quot;Game of Life Outputs: “<br>                              “Simulate pass (part 2)&quot;));<br>        }<br>        virtual int32 GetNumOutputs() const override { return 1; }<br>        virtual EShaderFrequency GetShaderFrequency() override {<br>            return SF_Compute;<br>        }<br>        virtual int32 Compile(FMaterialCompiler*, int32 pinIdx) override;<br>    #endif<br>};</pre><p>Implement them in a cpp file:</p><pre>if WITH_EDITOR<br>int32 UMaterialExpressionGoLSimulate1Outputs::Compile(FMaterialCompiler* compiler,<br>                                                      int32 pinIdx)<br>{<br>    int32 codeID;<br>    auto doPin = [&amp;](int32 i, FExpressionInput&amp; pin, float* fallback)<br>    {<br>       if (pinIdx != i)<br>          return false;<br>       <br>       if (pin.IsConnected())<br>          codeID = pin.Compile(compiler);<br>       else if (fallback)<br>          codeID = compiler-&gt;Constant(*fallback);<br>       else<br>          codeID = INDEX_NONE;<br>       return true;<br>    };<br><br>    if (!doPin(0, ThresholdTooFew, &amp;ThresholdTooFewConst) &amp;&amp;<br>        !doPin(1, ThresholdResurrect, &amp;ThresholdResurrectConst) &amp;&amp;<br>        !doPin(2, ThresholdTooMany, &amp;ThresholdTooManyConst))<br>    {<br>       codeID = INDEX_NONE;<br>    }<br>    return compiler-&gt;CustomOutput(this, pinIdx, codeID);<br>}<br>int32 UMaterialExpressionGoLSimulate2Outputs::Compile(FMaterialCompiler* compiler,<br>                                                      int32 pinIdx)<br>{<br>    int32 codeID;<br>    auto doPin = [&amp;](int32 i, FExpressionInput&amp; pin, float* fallback)<br>    {<br>       if (pinIdx != i)<br>          return false;<br>       <br>       if (pin.IsConnected())<br>          codeID = pin.Compile(compiler);<br>       else if (fallback)<br>          codeID = compiler-&gt;Constant(*fallback);<br>       else<br>          codeID = INDEX_NONE;<br>       return true;<br>    };<br><br>    if (!doPin(0, ContinuousValue, nullptr))<br>    {<br>       codeID = INDEX_NONE;<br>    }<br>    return compiler-&gt;CustomOutput(this, pinIdx, codeID);<br>}<br>#endif</pre><p>And finally, update <em>Simulate.usf </em>to invoke the Material in stages.</p><pre>//Near the top, where we define Material inputs:<br><br>//Stage 1<br>static float MaterialDeltaSeconds;<br>static float2 MaterialNeighborStates[9];<br><br>//Stage 2<br>static float MaterialNewDiscreteValue;<br>static float MaterialDiscreteSeverityT;<br><br><br>...<br><br><br>//At the point where we read the Material Emissive pin,<br>//    replace it and all following code with this.<br><br>//Run stage 1 of the Material graph&#39;s logic.<br>MaterialDeltaSeconds = DeltaSeconds;<br>for (int i = 0; i &lt; 9; ++i)<br>    MaterialNeighborStates[i] = prevStates[i];<br>float thresholdTooFew =<br>    #if HAVE_GoL_Outputs_Simulate_Pt1_0<br>        GoL_Outputs_Simulate_Pt1_0(matParams)<br>    #else<br>        2.0<br>    #endif<br>;<br>float thresholdResurrect =<br>    #if HAVE_GoL_Outputs_Simulate_Pt1_1<br>        GoL_Outputs_Simulate_Pt1_1(matParams)<br>    #else<br>        2.5<br>    #endif<br>;<br>float thresholdTooMany =<br>    #if HAVE_GoL_Outputs_Simulate_Pt1_2<br>        GoL_Outputs_Simulate_Pt1_2(matParams)<br>    #else<br>        3<br>    #endif<br>;<br>//Count the number of living neighbors surrounding us.<br>float neighborStrength = 0;<br>const float maxStrength = 8.0;<br>for (int i = 0; i &lt; 9; ++i)<br>    if (i != ourIdx)<br>        neighborStrength += prevStates[i].x;<br>//Apply the usual Game of Life rules to our cell,<br>//    dying/living/resurrecting based on living neighbor count.<br>//Also calculate a &quot;severity&quot; estimating the strength of the pull towards that value.<br>float targetValue, severityT;<br>if (neighborStrength &lt; thresholdTooFew)<br>{<br>    //Die off, from underpopulation.<br>    targetValue = 0;<br>    severityT = 1.0 - (neighborStrength / thresholdTooFew);<br>}<br>else if (neighborStrength &lt; thresholdResurrect)<br>{<br>    //Maintain current living status, from a normal population.<br>    targetValue = prevStates[ourIdx].x;<br>    severityT = 1.0;<br>}<br>else if (neighborStrength &lt;= thresholdTooMany)<br>{<br>    //Come alive, from an ideal population.<br>    targetValue = 1;<br>    severityT = (neighborStrength - thresholdResurrect) /<br>                max(0.0001, thresholdTooMany - thresholdResurrect);<br>}<br>else<br>{<br>    //Die, from overpopulation.<br>    targetValue = 0;<br>    severityT = (neighborStrength - thresholdTooMany) /<br>                max(0.0001, maxStrength - thresholdTooMany);<br>}<br><br>//Run stage 2 of the Material graph&#39;s logic to pick a continuous value.<br>MaterialNewDiscreteValue = targetValue;<br>MaterialDiscreteSeverityT = severityT;<br>float smoothValue =<br>    #if HAVE_GoL_Outputs_Simulate_Pt2_0<br>        saturate(GoL_Outputs_Simulate_Pt2_0(matParams))<br>    #else<br>        targetValue<br>    #endif<br>;<br><br>//Output the result.<br>NextSimStateTex[pixel] = float2(targetValue, smoothValue);</pre><p>All that’s left is to update the assets. Rename the existing simulation input Material Function to be “part 1”, and add a corresponding “part 2”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*AMNJbJUBLSzIZt4ztPjxkQ.png" /><figcaption>Code available below</figcaption></figure><pre>#if defined(GOL_PASS_SIMULATE)<br>    discreteValue = MaterialNewDiscreteValue;<br>    severityT = MaterialDiscreteSeverityT;<br><br>#else<br>    //Stub values for other shaders<br>    discreteValue = 0;<br>    severityT = 0.5;<br>#endif<br>return 0; //Return value isn’t actually used</pre><p>Finally, go back to the Material and use these custom outputs. Below is a graph that reproduces the original behavior.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fimgur.com%2FB3HMGKb&amp;type=text%2Fhtml&amp;schema=imgur&amp;display_name=Imgur&amp;src=https%3A%2F%2Fimgur.com%2FB3HMGKb%2Fembed%3Fpub%3Dtrue%26ref%3Dhttps%253A%252F%252Fembed.ly%26w%3D900" width="900" height="551" frameborder="0" scrolling="no"><a href="https://medium.com/media/60e5733ed5439792feb9ffac01e63865/href">https://medium.com/media/60e5733ed5439792feb9ffac01e63865/href</a></iframe><h4>Playing with the Material</h4><p>You can get very nice visuals by lowering the speed when animating towards a dead state, leaving ghostly trails on the screen.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fimgur.com%2FeqTDjcs&amp;type=text%2Fhtml&amp;schema=imgur&amp;display_name=Imgur&amp;src=https%3A%2F%2Fimgur.com%2FeqTDjcs%2Fembed%3Fpub%3Dtrue%26ref%3Dhttps%253A%252F%252Fembed.ly%26w%3D900" width="900" height="562" frameborder="0" scrolling="no"><a href="https://medium.com/media/5997bb38c5aaf3663dea89fc0bbb23db/href">https://medium.com/media/5997bb38c5aaf3663dea89fc0bbb23db/href</a></iframe><p>Let’s add screen-space animated noise to one of the parameters to get a little more variety in the ghost trails.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fimgur.com%2FitoI3mv&amp;type=text%2Fhtml&amp;schema=imgur&amp;display_name=Imgur&amp;src=https%3A%2F%2Fimgur.com%2FitoI3mv%2Fembed%3Fpub%3Dtrue%26ref%3Dhttps%253A%252F%252Fembed.ly%26w%3D900" width="900" height="640" frameborder="0" scrolling="no"><a href="https://medium.com/media/762df1b00fc6264c3df2e521875cdcdf/href">https://medium.com/media/762df1b00fc6264c3df2e521875cdcdf/href</a></iframe><p>If you want to see the effect of using different thresholds, here’s a graph that varies the Underpopulation and Overpopulation thresholds with screen UV, and the Resurrection threshold in between them over time. The released demo uses this graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ob4-XYRS-OUpwVJcZmpzlQ.png" /></figure><p>From here, the sky’s the limit! If your focus is on screen-space and compute shaders then you can consider this the end of the series. However the next article will show how to make a 3D scene pass, drawing actors into our simulation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*5NLn6ZZZEqPJ0fsaA66BzQ.png" /><figcaption>An overview of the final Material graph, with each pass neatly organized</figcaption></figure><h3>Code</h3><p>The Material shaders are upgraded in the <em>part/6 </em>branch:</p><p><a href="https://github.com/heyx3/UnrealExtendedGraphicsProgrammingDemo/tree/part/6">heyx3/UnrealExtendedGraphicsProgrammingDemo at part/6</a></p><h3>Details</h3><p>I can think of several improvements to increase the artists’ control over the Game of Life effect. I’ll leave them as exercises for the reader:</p><ul><li>Offer extra sim state textures that Materials can use however they want throughout each pass. For example, the artist could decide to use one channel to store each cell’s time since it was last alive. Add fields to the pass object to let artists configure the existence/format of those extra textures.</li><li>Provide more high-level settings in the custom pass object, such as the blend mode used for the Display shader.</li><li>Provide a parameter in the custom pass object to change the destination of the Display shader. Write to G-buffer targets like Base Color or Metallic instead of the final color!</li><li>Provide an option to compute the state texture’s mips before Display and/or Simulate, so that the artist can do more interesting things with clusters of cells.</li></ul><p>Custom output nodes seem capable of all sorts of tricks. For example you could have a dynamic number of output pins based on some UPROPERTY data. You can also apparently override CompilePreview() to compile your outputs differently for the Material preview vs the game world. The class UMaterialExpressionPhysicalMaterialOutput looks like a good example for more complex behaviors.</p><p><a href="https://www.youtube.com/watch?v=arunX2eeakk">My distortion effect in <em>Leave Them Behind</em></a><em> </em>actually has <strong>six</strong> shader stages: two simpler shaders, a final simulation shader with three stages, then the display shader. The HLSL and Material Functions for that third shader look heinous, but the Material graph is still easy to read because the steps happen in a clear order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0AjvnbYKa6AbvhRDjqSusw.png" /><figcaption>The simulation shaders for DisortionFX</figcaption></figure><p>Material code does not cache the results of custom output pins, which means you can invoke the same pin more than once while changing your input globals to get different results! This allows you to define loops in your effect code, where your shader controls the outside and the Material controls the inside. I can think of at least one creative use for this feedback loop, which will be included in the next/final version of the demo project as a bonus effect. This trick does <em>not</em> work with built-in output pins like Emissive Color.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5477dbb64608" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Graphics Programming in Unreal, part 5]]></title>
            <link>https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-5-ea988fd1034e?source=rss-384faa1a8ea4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea988fd1034e</guid>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[technical-art]]></category>
            <category><![CDATA[unreal-engine-5]]></category>
            <category><![CDATA[graphics-programming]]></category>
            <dc:creator><![CDATA[William Mishra-Manning]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 17:25:35 GMT</pubDate>
            <atom:updated>2025-11-11T18:32:07.958Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a seven-part article series.</p><p>Part 1: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-1-10488f2e17dd">Introduction</a><br>Part 2: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-2-abf8237491c1">Rendering Abstractions (RHI, RDG) and Threading</a><br>Part 3: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-3-f37f4d4407d7">Scenes. Views, and SceneViewExtension</a><br>Part 4: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-4-c89d6fb98b59">Global Shaders</a><br><strong>Part 5: Simple Material Shaders</strong><br>Part 6: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-6-5477dbb64608">Advanced Material Shaders</a><br>Part 7: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-7-d3500d4b8195">Mesh-Material Shaders and Mesh Passes</a></p><h3>Basic Material Shaders</h3><p>This article will explain how to replace Global Shaders, hand-coded from beginning to end by the graphics programmer, with Material Shaders which can inject code from a tech artist’s Material graph.</p><p>We’ll only get Material Shaders working at a basic level, by hacking on existing Material graph nodes. The next article will expand to arbitrary custom input and output nodes.</p><h3>Theory</h3><h4>All about Materials</h4><p>What are Materials, really? At first blush people see them as a fancy editor for making shaders. However, this doesn’t quite fit — Unreal has dozens of render passes that a surface Material can participate in, each with its own shader; plus who-knows-how-many offscreen shaders under the hood of Lumen and Nanite that are all doing totally different things with your object. Meanwhile Epic reserves the right to add new fancy render passes in the future, with new shaders which your Material must seamlessly integrate with somehow.</p><p>The reality is that Materials are one part of the <em>configuration</em> of a shader. They configure “how to compute properties” — how to calculate Base Color, Roughness, Metallic, World Position Offset, etc. They also have tons of meta-configuration for the lighting model, blend mode, culling, and so on to inform render passes of how they want to be used. Shaders, on the other hand, are the things which take a Material, execute its relevant output pins to get specific values like Base Color or Opacity, and then calculate a specific output using those values.</p><p><strong>Materials themselves do not know or care </strong>how to write to the G-buffer, or how motion vectors will be encoded, or how to read from Lumen data structures, or any other input/output stuff. They only know how to describe the thing they’re rendering.</p><p>So what are Materials really? <strong>They are a common language for the tech-artist to provide code and data to the graphics programmer.</strong></p><h4>Speaking the Language</h4><p>The Material language has multiple “dialects”, in the form of different <em>Domains</em>. Each domain provides a different set of output pins and draw settings. Post-Process domain Materials only have a Color pin, while Surface domain Materials have tons of physically-based output pins and lots of settings related to the lighting model.</p><p>The graphics programmer picks a target Material domain for their shader, executes whatever Material output pins they care about in that domain, then calculates whatever final outputs they need for their pass. The Material is none the wiser about how it was used.</p><p>You can also extend this language with custom input and output nodes for the Material graph — without changing any engine code! However we will wait to cover this until the next article. For now, we’ll settle for the simple yet hacky approach of interpreting standard pins as custom pass outputs.</p><h4>Why Bother?</h4><p>The separation between shaders and Materials is hugely advantageous because it decouples fast-iterating tech art work from dense engineer work. Compare it to Unity’s URP, where a custom Shaderlab shader needs to provide one pass for every render feature that the engine might ask it to participate in. If an engineer adds a new render feature to the game, the tech artist needs to go back and incorporate that feature’s passes into all their existing shaders/Materials.</p><p>Back in the days of Unity’s legacy BiRP you could write a single “surface shader” which described an object’s physical properties and left the hard lighting details to the engine; Unreal’s Materials are like surface shaders but far more generalized. You can, for example, build a Compute Shader which takes most of its logic from the Material graph. Shaders become more like a framework for artists to play in than a specific effect.</p><h4>Implementing Material Shaders</h4><p>For now we’ll focus on screen-space and compute work, because rendering 3D scene geometry requires the much more complex <em>Mesh-Material</em> <em>Shaders</em>. The final article in this series will cover those.</p><p>Creating a Material Shader is extremely similar to creating a Global Shader. Here is how you can upgrade a Global to Material:</p><ul><li>Make your class inherit from FMaterialShader<em> </em>rather than FGlobalShader, and update the various macro invocations accordingly.</li><li>Change SHADER_USE_PARAMETER_STRUCT(FMyShader, FGlobalShader) to SHADER_USE_PARAMETER_STRUCT_WITH_LEGACY_BASE(FMyShader, FMaterialShader). This tells Unreal not to worry when some shader parameters are missing from your parameter struct (because the Material instance has parameters of its own). If you don’t do this then you get a harmless-but-annoying assert failure whenever the shader is compiled.</li><li>Replace all calls to the global SetShaderParameters(…) with some new global helper functions, SetShaderParametersMixed[VS|CS|PS|etc](…). This new helper will call the original <em>and</em> call your shader’s inherited member function SetParameters(…), which uploads all the Material parameters. If you don’t do this then your user’s Materials will see all their params set to default/garbage values!</li><li>If you followed the previous article about Global Shaders, then you never called SetShaderParameters(…) manually in the first place. Most draw operations can be done by calling Unreal’s helper functions, and nearly all those helper functions conveniently call SetShaderParameters(…) for you. Unfortunately, now that you are replacing those calls with SetShaderParametersMixed[X](…), you need to change how you use these helper functions. Look for new overloads which take a “setup lambda”. This is where they previously called SetShaderParameters(…), and where you are meant to call SetShaderParametersMixed[X](…).</li><li>Instead of extracting your global shader from the global shader-map, extract your Material shader from a specific Material’s shader-map. There is a complicated snippet to extract Material shaders, which my library simplifies into EGP::FindMaterialShaders_RenderThread(…).</li><li>Inject each Material’s code into your shader file with #include “/Engine/Generated/Material.ush”. To help your IDE see some of the code that Unreal generates for Materials, I highly recommend this intellisense trick which works in both Visual Studio and Jetbrains Rider:</li></ul><pre>#if defined(__INTELLISENSE__) || defined(__RESHARPER__)<br>    //The Material template file is malformed<br>    // but IDE&#39;s can parse it well enough!<br>    #include &quot;/Engine/Private/MaterialTemplate.ush&quot;<br>#else<br>    //In the real shader compiler, use the real Material code.<br>    #include &quot;/Engine/Generated/Material.ush&quot;<br>#endif</pre><p><strong><em>NOTE: </em></strong><em>This include statement is where you can inject new input nodes into Material graphs. We will cover the technique in the next article but the gist is to define some static globals right before the </em><em>#include, write to those globals before invoking Material code, then create a Material Function asset which reads from those globals using a Custom HLSL node.</em></p><p><strong><em>UPDATE</em></strong><em>: I just learned something important that cost me a lot of time at work! I already mentioned that new shaders have to be defined in a module loaded on</em>PostConfigInit<em>. If you fail to respect this, Unreal normally logs an error on startup…but only for Global Shaders. If you load a Material Shader at the wrong phase, then it silently propagates until you go to run a standalone build and get sporadic crashes about missing shader-maps.</em></p><h4>Dispatching Material Shaders</h4><p>The process of invoking Material code in a shader varies a lot by the shader’s frequency (vertex/pixel/compute), the Material domain, and especially whether it’s a Mesh-Material shader.</p><p>For non-3D work I recommend setting your Material shaders up like the engine’s post-process shader, operating on materials in the Post-Process domain. This domain comes with helpful infrastructure, like special input nodes that expose multiple textures.</p><p>It requires a lot of boilerplate to set up, but my library handles all of it for you within the header <em>EGP_PostProcessMaterialShaders.h</em>. The rest of this article assumes you are using that approach (and see the next section for the HLSL side of it). If you want to go your own way, at least read through EGP’s relevant headers and shaders to understand what it’s doing first!</p><p>EGP offers two kinds of shader passes for post-process Materials: off-screen compute work, called a <em>Simulation</em> pass, and screen-space compute/pixel work, called a <em>Screen-Space</em> pass. The difference is that Simulation passes run in a vacuum, without Viewport data. To execute a shader using either of these pass types, do the following:</p><ol><li>Have your shader inherit from one of our custom FMaterialShader<em> </em>subtypes, EGP::FSimulationShader<em> </em>or EGP::FScreenSpaceShader.</li><li>Include an extra line in your parameter struct, either EGP_SIMULATION_PASS_MATERIAL_DATA() or EGP_SCREEN_SPACE_PASS_MATERIAL_DATA().</li><li>Define the inputs to the post-process Material graph by creating an instance of an “input” struct, either EGP::FSimulationPassMaterialInputs or EGP::FScreenSpacePassMaterialInputs.</li><li>Tell my library how to execute your pass by creating an instance of a “state” struct. Pick from one of the following types:<br>–For <strong>simulation passes</strong>, use EGP::FSimulationPassState. Work-group count can be given immediately, or deferred to a render-thread lambda executed right before dispatching the shader, or pulled from a GPU buffer (a.k.a. “indirect dispatch”).<br>–For <strong>screen-space passes that use a vertex+pixel shader</strong>, use EGP::FScreenSpacePassRenderState.<br>–For <strong>screen-space passes that use a compute shader</strong>, use EGP::FScreenSpacePassComputeState. Like with simulation passes, work-group count can be given in several ways.</li><li>Call a function to queue up the pass, and provide all this data to it. Either EGP::AddSimulationMaterialPass(…), EGP::AddScreenSpaceRenderPass(…), or EGP::AddScreenSpaceComputePass(…).</li></ol><p>Screen-space Render passes, which use a Vertex and Pixel shader, commonly need a different parameter struct for each shader. If you’re implementing both shaders yourself then make an overarching parameter struct which holds both structs nested inside it, and pass all three into the dispatch call. However in most cases you can use the built-in vertex shader EGP::FScreenSpaceRenderVS, and then your pixel shader’s param struct <strong>already is </strong>the overarching one. Extract the vertex shader params with &amp;pixelParams-&gt;ScreenSpacePassData.</p><p><strong><em>NOTE: </em></strong><em>Simulation passes conceptually do not have a viewport, but Unreal sadly requires that Material shaders have a view instance when setting up their parameters. So for now you must pass an </em><em>FViewInfo</em> <em>into </em><em>AddSimulationMaterialPass(…), which means there’s not much value to using Simulation passes over Screen-Space. Fixing this may require copying a bit of engine code and ripping out the viewport parts.</em></p><h4>Material Shader HLSL</h4><p>The way you actually execute a Material in HLSL varies based on many details. In any case, following my post-process Material workflow, you should put the following near the top of your shader:</p><pre>#include “/EGP/ScreenPass/pre.ush”<br>// (define any custom Material inputs here)<br>#include “/EGP/ScreenPass/post.ush”</pre><p>This will bring in all the post-process boilerplate and generated Material code.</p><p>The start of your main function will depend on the kind of shader you are writing. The ultimate goal is to fill in a “material inputs” struct and a “material parameters” struct; then you can call the Material’s generated functions to compute whatever output pins you want.</p><p>For a <strong>Simulation Compute</strong> shader, you have to provide a lot of the standard material inputs by hand:</p><pre>//Fabricate info that is normally computed from the viewport and VS.<br>uint2 viewportPixel = threadIdx.xy;<br>float2 uv = (float2(viewportPixel.xy) + 0.5) / float2(MyViewportSize); <br>float3 reportedWorldPos = float3((uv * 2) - 1, 0); <br>float reportedDepth = 0; <br><br>//Generate the Material structs.<br>FPixelMaterialInputs mInputs;<br>FMaterialPixelParameters mParams;<br>ScreenPassSetupCS(viewportPixel, uv, reportedWorldPos, reportedDepth,<br>                  mInputs, mParams);<br>//If you have custom material inputs, set them up here.<br><br>//Now we can invoke material code!</pre><p>For a <strong>Screen-Pass Compute</strong> shader, things are simpler because you can lean on the viewport data:</p><pre>uint2 pixel = threadIdx.xy;<br>FPixelMaterialInputs mInputs;<br>FPixelMaterialParameters mParams;<br>ScreenPassSetupCS(pixel, mInputs, mParams);<br>//If you have custom material inputs, set them up here.<br><br>//Now we can invoke material code!</pre><p>For a <strong>Screen-Pass Vertex</strong> shader, you should probably start by copying the contents of <em>ExtendedGraphicsProgramming/Shaders/ScreenPass/simple_vs.usf</em>. Material vertex shaders are pretty simple, and the only struct that needs to get filled in is FMaterialVertexParameters:</p><pre>float2 uv = …; //Probably coming from some vertex input<br>FTexCoordsVSToPS materialInterpolants; //If your PS is also MaterialShader<br>                                       //  then this should be a VS output<br><br>FMaterialVertexParameters mParams;<br>ScreenPassSetupVS(uv, mParams, materialInterpolants);<br>//If you have custom material inputs, set them up here.<br><br>//Now we can invoke material code!</pre><p>Finally, for a<strong> Screen-Pass Pixel</strong> shader you need those VS outputs to initialize the Material:</p><pre>in float4 svPos : SV_Position //Important builtin input<br>in FTexCoordsVSToPS materialInputsFromVS //Output of our Material VS<br><br>FPixelMaterialInputs matInputs;<br>FMaterialPixelParameters matParams;<br>ScreenPassSetupPS(svPos, materialInputsFromVS,<br>                  matInputs, matParams);<br>//If you have custom material inputs, set them up here.<br><br>//Now we can invoke material code!</pre><p>For a reference of what Material functions and data you can play with, check out the template file that’s used to generate them: <em>/Engine/Private/MaterialTemplate.ush</em>. For example, in a pixel or compute shader you can get the Emissive Color pin by calling GetMaterialEmissive(matInputs). Once we make custom output pins in the next article, you can check for those in a similar way.</p><h3>Demo</h3><p>We will convert 3 of our 4 shaders to Material shaders. For variety, we will also change our Simulate shader to be a Simulation compute pass instead of a pixel shader. It makes more sense as a Screen-Space compute pass since it has an associated viewport, but I want to show how to create a full variety of Material shader passes.</p><p><em>NOTE: When using DX12, I get a harmless warning popup that says some shader parameters of Simulate.usf are unbound. This doesn’t stop the effect from working, and I don’t see the warning with the Vulkan RHI, so I didn’t bother tracking down why this happens. But still you may want to switch to Vulkan for now, or remake the Simulate shader as a Screen-Space pass rather than a Simulation pass.</em></p><h4>Pass Object takes a Material</h4><p>To start, remove all previous parameters from our Pass object (initial noise seed and scale; simulation speed and acceleration). In place of that, add a new Material field and a render-thread copy of it.</p><pre>//Inside U_GoL_RenderPass:<br>public:<br>    UPROPERTY(BlueprintReadWrite, EditAnywhere)<br>    UMaterialInterface* EffectMaterial = nullptr;<br>private: <br>    // ReSharper disable once CppUE4ProbableMemoryIssuesWithUObject<br>    UMaterialInterface* effectMaterial_RenderThread = nullptr;<br>public:<br>    UMaterialInterface* GetEffectMaterial_RenderThread() const {<br>        check(IsInRenderingThread());<br>        return effectMaterial_RenderThread;<br>    }<br><br>//Inside U_GOL_RenderPass::Tick_GameThread(…):<br>    //Update the render-thread copies of our parameters.<br>    auto* matIn = EffectMaterial;<br>    auto* matOut = &amp;effectMaterial_RenderThread;<br>    ENQUEUE_RENDER_COMMAND(UpdateGoLParams)(<br>        [matIn, matOut](FRHICommandList&amp; cmds) {<br>            *matOut = matIn;<br>    });</pre><p>The last step is to feed a Material to this pass at runtime, but first we need some shaders for the Material to control!</p><h4>Initialization Shader</h4><p>Initialization is the simplest Material shader. Previously it generated discrete and continuous starting values using hard-coded noise, but now the Material Graph will feed initial values through the Emissive output’s Red and Green channels.</p><p>Update the shader file:</p><pre>//Init.usf:<br>#include &quot;/EGP/ScreenPass/pre.ush&quot;<br><br>//Hint to the Materials which shader we&#39;re running in.<br>#define GOL_PASS_INIT 1<br><br>#include &quot;/EGP/ScreenPass/post.ush&quot;<br><br>//To help intellisense see Material code,<br>//    use this snippet.<br>#if defined(__INTELLISENSE__) || defined(__RESHARPER__)<br> #include &quot;/Engine/Private/MaterialTemplate.ush&quot;<br>#endif<br><br>//We will use the standard VS for screen-space passes,<br>//    FScreenSpaceRenderVS.<br>//Our inputs come from there.<br>void Main(in FTexCoordsVSToPS materialInterpolants,<br>          in float4 svPos : SV_Position,<br>          out float2 newState : SV_Target0)<br>{<br>    //Set up the Material.<br>    FPixelMaterialInputs matInputs;<br>    FMaterialPixelParameters matParams;<br>    ScreenPassSetupPS(svPos, materialInterpolants,<br>                      matInputs, matParams);<br><br>    //Compute the Material’s Emissive Color pin<br>    //    and interpret it as our initial cell state.<br>    newState.xy = GetMaterialEmissive(matInputs).rg;<br><br>    //The first channel is supposed to be a discrete bool.<br>    newState.x = step(0.5, newState.x);<br>}</pre><p>Update the shader class:</p><pre>struct FGoLInitializePS : public EGP::FScreenSpaceShader<br>{<br>    DECLARE_EXPORTED_SHADER_TYPE(FGoLInitializePS, Material, )<br><br>    BEGIN_SHADER_PARAMETER_STRUCT(FParameters, )<br>       EGP_SCREEN_SPACE_PASS_MATERIAL_DATA()<br>       RENDER_TARGET_BINDING_SLOTS()<br>    END_SHADER_PARAMETER_STRUCT()<br>    SHADER_USE_PARAMETER_STRUCT_WITH_LEGACY_BASE(FGoLInitializePS,<br>                                                 EGP::FScreenSpaceShader)<br>};<br><br>IMPLEMENT_MATERIAL_SHADER_TYPE(, FGoLInitializePS,<br>                                 TEXT(&quot;/GameOfLife/Init.usf&quot;),<br>                                 TEXT(&quot;Main&quot;), SF_Pixel);</pre><p>And finally update the FGameOfLifeView constructor which invokes it:</p><pre>//The constructor’s new arguments:<br>FGameOfLifeView(FRDGBuilder&amp; graph,<br>                const FViewInfo&amp; view, const FIntRect&amp; viewportSubset,<br>                const UMaterialInterface* effectMaterial,<br>                const FSceneTextureShaderParameters&amp; sceneTextures);<br><br>...<br><br>//At the end of the constructor:<br><br>//Parameters for initialization<br>auto* initShaderParams = graph.AllocParameters&lt;FGoLInitializePS::FParameters&gt;();<br>initShaderParams-&gt;RenderTargets[0] = {<br>    simStateRDG,<br>    ERenderTargetLoadAction::ENoAction<br>};<br>EGP::FScreenSpacePassMaterialInputs postProcessMaterialInputs;<br>postProcessMaterialInputs.SceneTextures = sceneTextures;<br>postProcessMaterialInputs.TargetView = &amp;view;<br>postProcessMaterialInputs.OutputViewportData = FScreenPassTextureViewport{<br>    simStateRDG<br>};<br>postProcessMaterialInputs.InputViewportData = FScreenPassTextureViewport{<br>    view.ViewRect<br>};<br><br>//Default to opaque blending and no depth/stencil usage<br>EGP::FScreenSpacePassRenderState renderState{ };<br><br>//Dispatch the Material shader<br>EGP::AddScreenSpaceRenderPass&lt;EGP::FScreenSpaceRenderVS, FGoLInitializePS&gt;(<br>    graph, RDG_EVENT_NAME(&quot;GoL_Initialize&quot;),<br>    postProcessMaterialInputs, renderState,<br>    initShaderParams, effectMaterial,<br>    //Extract the specific VS and PS param structs<br>    &amp;initShaderParams-&gt;ScreenSpacePassData, initShaderParams<br>);<br><br>...<br><br>//In F_GOL_PassSVE::PrePostProcessPass_RenderThread(),<br>//    update our view-data getter:<br>auto&amp; viewData = Pass-&gt;PerViewData.DataForView(<br>    graph, view,<br>    //The below arguments get passed to constructor if this is a new view<br>    Pass-&gt;GetEffectMaterial_RenderThread(),<br>    GetSceneTextureShaderParameters(inputs.SceneTextures)<br>);</pre><p>Now the Material we give to the pass object in-game can control initialization! Before creating a Material though, we’ll add the other two shaders.</p><h4>Display Shader</h4><p>The process to convert this shader is very similar. Rather than computing the final color ourselves, we simply return the Material’s emissive color pin. We also need to provide the Material graph with the current sim state, so they can sample from it.</p><p>Update the shader code:</p><pre>//Display.usf<br><br>#include &quot;/EGP/ScreenPass/pre.ush&quot;<br>//Hint to Materials which shader we&#39;re running in.<br>#define GOL_PASS_DISPLAY 1<br>#include &quot;/EGP/ScreenPass/post.ush&quot;<br><br>float4 Main(in FTexCoordsVSToPS materialInterpolants,<br>            in float4 svPos : SV_Position) : SV_Target0<br>{<br>    //Set up the Material.<br>    FPixelMaterialInputs matInputs;<br>    FMaterialPixelParameters matParams;<br>    ScreenPassSetupPS(svPos, materialInterpolants, matInputs, matParams);<br><br>    //Let the Material decide how to sample and display the effect.<br>    return float4(GetMaterialEmissive(matInputs), 1.0);<br>}</pre><p>Conver the shader class:</p><pre>struct FGoLDisplayPS : public EGP::FScreenSpaceShader<br>{<br>  DECLARE_EXPORTED_SHADER_TYPE(FGoLDisplayPS, Material, )<br><br>  BEGIN_SHADER_PARAMETER_STRUCT(FParameters, )<br>    EGP_SCREEN_SPACE_PASS_MATERIAL_DATA()<br>    RENDER_TARGET_BINDING_SLOTS()<br>  END_SHADER_PARAMETER_STRUCT()<br>  SHADER_USE_PARAMETER_STRUCT_WITH_LEGACY_BASE(FGoLDisplayPS,<br>                                               EGP::FScreenSpaceShader)<br>};<br><br>IMPLEMENT_MATERIAL_SHADER_TYPE(, FGoLDisplayPS,<br>                                 TEXT(&quot;/GameOfLife/Display.usf&quot;),<br>                                 TEXT(&quot;Main&quot;), SF_Pixel);</pre><p>Update our helper function which dispatches the shader:</p><pre>static void RenderGoLState(FRDGBuilder&amp; graph, const FViewInfo&amp; view,<br>                           FRDGTextureRef simStateTex,<br>                           FRHIBlendState* blending,<br>                           const FRenderTargetBinding&amp; output,<br>                           const UMaterialInterface* material,<br>                           const FSceneTextureShaderParameters&amp; sceneTextures)<br>{<br>    auto* params = graph.AllocParameters&lt;FGoLDisplayPS::FParameters&gt;();<br>    params-&gt;RenderTargets[0] = output;<br><br>    //Provide the “sim state” texture as Post-Process Texture slot 0.<br>    EGP::FScreenSpacePassMaterialInputs inputs;<br>    inputs.Textures[0] = GetScreenPassTextureInput(<br>        FScreenPassTexture{ simStateTex },<br>        TStaticSamplerState&lt;SF_Bilinear, AM_Clamp, AM_Clamp&gt;::GetRHI()<br>    );<br>    //Provide other info about the viewport being drawn to.<br>    inputs.SceneTextures = sceneTextures;<br>    inputs.TargetView = &amp;view;<br>    inputs.InputViewportData = FScreenPassTextureViewport{<br>        inputs.Textures[0].Texture<br>    };<br>    inputs.OutputViewportData = FScreenPassTextureViewport{<br>        output.GetTexture(), view.ViewRect<br>    };<br><br>    //Configure the PSO for this pass.<br>    EGP::FScreenSpacePassRenderState state{ blending };<br><br>    //Dispatch.<br>    EGP::AddScreenSpaceRenderPass&lt;EGP::FScreenSpaceRenderVS,<br>                                  FGoLDisplayPS&gt;(<br>        graph, RDG_EVENT_NAME(&quot;GoL_Display&quot;),<br>        inputs, state, params, material,<br>        //Extract the specific VS and PS param structs:<br>        &amp;params-&gt;ScreenSpacePassData, params<br>    );<br>}</pre><h4>Simulation Shader</h4><p>This one will have more significant changes. Currently it runs in the pass object’s render-thread Tick, but for technical reasons we need View data when dispatching a Simulation material pass. We’ll move that code to the SVE, and the Tick function just accumulates delta-time in between render events.</p><p>Add a delta-time counter to the per-view data.</p><pre>//In FGameOfLifeView<br>float NextTickTime = 0;</pre><p>Update the old tick logic to increment this counter instead of running the Simulate shader.</p><pre>//In U_GOL_RenderPass::Tick_RenderThread:<br>PerViewData.ForEachView([&amp;](int viewID,<br>                            FGameOfLifeView&amp; view,<br>                            ERHIFeatureLevel::Type featureLevel) {<br>    view.NextTickTime += gameThreadDeltaSeconds;<br>});</pre><p>Update the shader code to be a Simulation Compute shader rather than a global pixel shader:</p><pre>//Simulate.usf<br><br>#include &quot;/EGP/ScreenPass/pre.ush&quot;<br>//Hint to Materials which shader we&#39;re running in.<br>#define GOL_PASS_SIMULATE 1<br>#include &quot;/EGP/ScreenPass/post.ush&quot;<br><br>float DeltaSeconds; <br>RWTexture2D&lt;float2&gt; NextSimStateTex;<br><br>//The input state texture is part of the Material configuration now;<br>//    it isn’t declared ourselves.<br>#define SimStateTex PostProcessInput_0_Texture<br><br>//The shader class will tell us what group size to use.<br>[numthreads(SIM_GROUP_SIZE_X, SIM_GROUP_SIZE_Y, SIM_GROUP_SIZE_Z)]<br>void Main(uint3 threadIdx : SV_DispatchThreadID)<br>{<br>    uint2 resolution;<br>    SimStateTex.GetDimensions(resolution.x, resolution.y);<br><br>    uint2 pixel = threadIdx.xy;<br>    float2 uv = (float2(pixel) + 0.5) / float2(resolution);<br>    if (any(pixel &gt;= resolution))<br>       return;<br><br>    //Set up the Material.<br>    FPixelMaterialInputs matInputs;<br>    FMaterialPixelParameters matParams;<br>    float3 fakeWorldPos = float3((uv * 2) - 1, 0);<br>    float fakeFragmentDepth = 0.0;<br>    ScreenPassSetupCS(pixel, uv, fakeWorldPos, fakeFragmentDepth,<br>                      matInputs, matParams);<br><br>    //Query the GoL rules from the Material,<br>    //    interpreting its three Emissive outputs<br>    //    as various living/dying thresholds.<br>    float3 matOutputs = GetMaterialEmissive(matInputs);<br>    const float ThresholdTooFew = matOutputs.x,<br>                ThresholdResurrect = matOutputs.y,<br>                ThresholdTooMany = matOutputs.z;<br>    const float OverallSpeed = 0.3;<br><br>    // (the core GoL logic is mostly unchanged and omitted here)<br><br>    NextSimStateTex[pixel] = float2(targetValue, smoothValue);<br>}</pre><p>Update the shader’s class accordingly.</p><pre>struct FGoLSimulateCS : public EGP::FSimulationShader<br>{<br>  DECLARE_EXPORTED_SHADER_TYPE(FGoLSimulateCS, Material, );<br>  static FIntVector3 GroupSize() { return { 8, 8, 1 }; }<br><br>  BEGIN_SHADER_PARAMETER_STRUCT(FParameters, )<br>    SHADER_PARAMETER(float, DeltaSeconds)<br>    SHADER_PARAMETER_RDG_TEXTURE_UAV(RWTexture2D&lt;float2&gt;,<br>                                     NextSimStateTex)<br>    EGP_SIMULATION_PASS_MATERIAL_DATA()<br>  END_SHADER_PARAMETER_STRUCT()<br>  SHADER_USE_PARAMETER_STRUCT_WITH_LEGACY_BASE(FGoLSimulateCS,<br>                                               EGP::FSimulationShader)<br><br>  //Feed the group size to the shader as a pre-processor define.<br>  //That way it isn’t hard-coded in two places.<br>  static void ModifyCompilationEnvironment(<br>                const FMaterialShaderPermutationParameters&amp; params,<br>                FShaderCompilerEnvironment&amp; env<br>              )<br>  {<br>    EGP::FSimulationShader::ModifyCompilationEnvironment(params, env);<br>    env.SetDefine(TEXT(&quot;SIM_GROUP_SIZE_X&quot;), GroupSize().X);<br>    env.SetDefine(TEXT(&quot;SIM_GROUP_SIZE_Y&quot;), GroupSize().Y);<br>    env.SetDefine(TEXT(&quot;SIM_GROUP_SIZE_Z&quot;), GroupSize().Z);<br>  }<br>};<br><br>IMPLEMENT_MATERIAL_SHADER_TYPE(, FGoLSimulateCS,<br>                                 TEXT(&quot;/GameOfLife/Simulate.usf&quot;),<br>                                 TEXT(&quot;Main&quot;),<br>                                 SF_Compute);</pre><p>Now rewrite the helper function that dispatches this shader.</p><pre>static void UpdateGoLState(FRDGBuilder&amp; graph, const FViewInfo&amp; view,<br>                           FRDGTextureRef currentSimState,<br>                           FRDGTextureRef nextSimState,<br>                           float deltaSeconds,<br>                           const UMaterialInterface* uMaterial)<br>{<br>    check(currentSimState-&gt;Desc.Extent == nextSimState-&gt;Desc.Extent);<br> <br>    //Provide the previous state to the material graph<br>    //    as Post-Process Texture 0.<br>    EGP::FSimulationPassMaterialInputs inputs;<br>    inputs.Textures[0] = GetScreenPassTextureInput(<br>        FScreenPassTexture{ currentSimState },<br>        TStaticSamplerState&lt;SF_Bilinear, AM_Clamp, AM_Clamp&gt;::GetRHI()<br>    );<br><br>    //Set up our non-Material shader params.<br>    auto* params = graph.AllocParameters&lt;FGoLSimulateCS::FParameters&gt;();<br>    params-&gt;DeltaSeconds = deltaSeconds;<br>    params-&gt;NextSimStateTex = graph.CreateUAV(nextSimState);<br><br>    //Calculate the group count.<br>    EGP::FSimulationPassState state;<br>    state.GroupCount.Set&lt;FIntVector3&gt;(<br>        FComputeShaderUtils::GetGroupCount(<br>            FIntVector3{ currentSimState-&gt;Desc.Extent.X,<br>                         currentSimState-&gt;Desc.Extent.Y,<br>                         1 },<br>            FGoLSimulateCS::GroupSize()<br>        )<br>    );<br><br>    //Dispatch.<br>    EGP::AddSimulationMaterialPass&lt;FGoLSimulateCS&gt;(<br>        graph, RDG_EVENT_NAME(&quot;GoL_Tick&quot;),<br>        inputs, state, view,<br>        params, uMaterial<br>    );<br>}</pre><p>Finally, in the SVE’s post-process callback, run a Simulate pass before Display.</p><pre>//For any time has passed on the game thread, tick this viewport&#39;s sim.<br>if (viewData.NextTickTime &gt; 0)<br>{<br>    auto nextSimStateRDG = RegisterExternalTexture(<br>        graph, viewData.SimBuffer,<br>        TEXT(&quot;GoL_NextState&quot;)<br>    );<br>    UpdateGoLState(<br>        graph, view,<br>        simStateRDG, nextSimStateRDG,<br>        viewData.NextTickTime, passMaterial<br>    );<br>    viewData.NextTickTime = 0;<br><br>    std::swap(viewData.SimBuffer, viewData.SimState);<br>    simStateRDG = nextSimStateRDG;<br>}</pre><h4>Create a pass Material</h4><p>Our code is fully converted, so let’s make a Material to drive the effect.</p><p><strong><em>NOTE: </em></strong><em>if the Material graph looks janky to you, that’s because it is! The next article will greatly improve this workflow.</em></p><ol><li>Open up the Unreal editor for the project and create a new Material. Set the domain type to Post-Process.</li><li>If you recall, each Material Shader defined a preprocessor token to tell us what pass is running — GOL_PASS_INIT, GOL_PASS_SIMULATE, and GOL_PASS_DISPLAY. We can take advantage of this in a Custom HLSL node to switch between different logic based on the pass we’re running:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9E51CpuK1Oqf_LOxMWFZ8Q.png" /><figcaption>Switching logic by shader stage</figcaption></figure><pre>//Source for the custom node:<br>#if defined(GOL_PASS_INIT)<br>    return ifInit;<br>#elif defined(GOL_PASS_SIMULATE)<br>    return ifSimulate;<br>#elif defined(GOL_PASS_DISPLAY)<br>    return ifDisplay;<br>#else<br>    //Material preview and other contexts<br>    return other;<br>#endif</pre><p>3. Create logic for each of the phases and plug them into the custom Switch node. The below graph recreates the original Global shader logic, with customizable parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DlPr_cEeRTBGYBGivmlhSA.png" /><figcaption>Initialize stage logic</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*LvATQZDjpawk2e0iXJayIQ.png" /><figcaption>Simulate stage logic</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MIqXgKTKzhLGJrtBFO-uvA.png" /><figcaption>Display stage logic</figcaption></figure><p>4. For easier tweaking, create a Material Instance from your Material.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*JOzlGSyof-eDqY9InkDclw.png" /><figcaption>Material Instance that recreates the Global shader logic</figcaption></figure><p>5. In the demo scene, set up the render pass to use the Material instance. As mentioned before, I do this setup in the level blueprint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*GBrLaAUg2KmI15IMpoVIpg.png" /><figcaption>The level blueprint in my demo scene</figcaption></figure><p>And that’s everything! Now you should be able to play with that Material instance, or underlying Material, and see immediate changes to the simulation — without even having to restart the game.</p><p>Feel free to play around with your new Material, but in the next article we’ll improve the UX a lot.</p><h4>Small Bug Workaround</h4><p>One problem with this demo is that the Material shaders, including <em>Initialize</em>, take a few frames to compile against the Material the first time they’re used. In the editor it’s no problem after your first run, but in standalone it can mean the initialize shader is executed with the Default Material, creating an empty initial state! To fix this I added the ability to re-run the Initialize shader at will, and had the demo’s Game Mode re-run initialization after a few seconds.</p><p>I’m sure there must be some elegant way to pre-compile the Material shaders, or even force the render code to wait for compilation before running <em>Initialize</em>, but I currently don’t know how, so this is good enough for demo purposes. If you really want to see how I implemented this check out the custom Game Mode and Player Controller blueprints, and the C++ function U_GOL_RenderPass::ReInitializeAllViews().</p><p>It’s possible this could be <a href="https://dev.epicgames.com/documentation/en-us/unreal-engine/pso-precaching-for-unreal-engine">fixed with PSO precaching</a>, but I haven’t looked into it.</p><h3>Code</h3><p>The Material shaders are added to the demo in the <em>part/5 </em>branch:</p><p><a href="https://github.com/heyx3/UnrealExtendedGraphicsProgrammingDemo/tree/part/5">heyx3/UnrealExtendedGraphicsProgrammingDemo at part/5</a></p><h3>Details</h3><p>EGP::FindMaterialShaders_RenderThread(…)<em> </em>will go through fallback Materials in case the one you provided doesn’t work (e.g. it doesn’t compile). In the worst-case it falls through to the universal Default Material for the domain you were using, which from my understanding is one with all settings left at defaults and all output pins not written to.</p><p>If you want to understand more about dispatching Material shaders, take a look under the hood of EGP::AddScreenSpaceRenderPass(…) and <em>Shaders/ScreenPass/pre.ush</em>. I like to think my code is pretty well-commented!</p><p>If you want to understand more about how Materials are invoked in HLSL, read <em>Shaders/ScreenPass/post.ush</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea988fd1034e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Graphics Programming in Unreal, part 4]]></title>
            <link>https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-4-c89d6fb98b59?source=rss-384faa1a8ea4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c89d6fb98b59</guid>
            <category><![CDATA[graphics-programming]]></category>
            <category><![CDATA[technical-art]]></category>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[unreal-engine-5]]></category>
            <dc:creator><![CDATA[William Mishra-Manning]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 17:23:37 GMT</pubDate>
            <atom:updated>2025-06-26T23:44:53.367Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a seven-part article series.</p><p>Part 1: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-1-10488f2e17dd">Introduction</a><br>Part 2: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-2-abf8237491c1">Rendering Abstractions (RHI, RDG) and Threading</a><br>Part 3: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-3-f37f4d4407d7">Scenes. Views, and SceneViewExtension</a><br><strong>Part 4: Global Shaders</strong><br>Part 5: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-5-ea988fd1034e">Simple Material Shaders</a><br>Part 6: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-6-5477dbb64608">Advanced Material Shaders</a><br>Part 7: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-7-d3500d4b8195">Mesh-Material Shaders and Mesh Passes</a></p><p>Finally it’s time for shaders! This article covers the simplest type of Unreal shader, while the next 3 get increasingly complex. This is also the last article in the series to contain a lot of information which can be found elsewhere on the internet.</p><h3>Global Shaders</h3><p>If you read <a href="https://dev.epicgames.com/documentation/en-us/unreal-engine/adding-global-shaders-to-unreal-engine">any other resources on custom Unreal shaders</a>, then you already know about Global Shaders. They’re pure text HLSL which come with an associated C++ class and need to be invoked by C++ code. They’re immediately compiled on engine startup, and can be recompiled within the editor by pressing “<strong><em>Ctrl+Shift+.</em></strong>”.</p><p>This article will go over them in more detail than any other resource I’ve found. It’s the longest article in the series, but sets the stage for the next 3. The <strong>Theory</strong> and especially <strong>Details</strong> sections are more of a reference than a tutorial, so you may want to start with the <strong>Demo</strong> section.</p><p>In subsequent articles we’ll upgrade to <em>Material Shaders</em>, which compile against a user Material; and add <em>Mesh-Material Shaders</em>, which compile against a Material <strong>and</strong> specific 3D primitive type.</p><h3>Theory</h3><p>All 3 shader types in Unreal (FGlobalShader, FMaterialShader and FMeshMaterialShader) inherit from <em>FShader </em>and share much of the same basic architecture. They do almost everything through <strong>shadowing </strong>— defining new functions, fields, or typedefs that hide the default ones inherited from FShader. This is one C++ alternative to object-oriented tricks like virtual functions. It works as long as the shader’s precise type is known at compile time, which is why many functions interacting with shaders are templated. FShader and its 3 child classes are an important reference for writing new shaders of any kind.</p><p>Global Shaders are the most straightforward. They have a specific type (Vertex, Fragment, Compute, etc.) which Unreal calls the <em>frequency</em>.<em> </em>They are implemented in an HLSL text file (Unreal uses the extension .ush for headers and .usf for implementations). Finally, they are connected to Unreal with a C++ class inheriting from FGlobalShader.</p><p>Global shaders are pretty easy to invoke too! You can dispatch it from literally anywhere with the help of ENQUEUE_RENDER_COMMAND().</p><h4>Permutations</h4><p>Global Shaders have multiple compiled variants, primarily based on your platform capabilities (SM5 vs SM6 vs ES3_1) and the current Quality Setting. However they can also define <em>permutations</em>. These are enum values, integer values, or bool flags that get fed into your shader as compile-time constants.</p><p>If your shader needs permutations then refer to the <strong>Details&gt;Permutations</strong> section at the bottom of this article for implementation details.</p><h4>Shader Maps</h4><p>A global <em>Shader Map</em> stores the set of all compiled variants of all global shaders, at <strong>one </strong>feature level. In other words there is one global shader map per feature level, which you can get with the function</p><pre>GetGlobalShaderMap(level)</pre><p>There is also a global variable for your machine’s max feature level, GMaxRHIFeatureLevel, leading to the tempting snippet</p><pre>GetGlobalShaderMap(GMaxRHIFeatureLevel)</pre><p>However in most cases you should pull the feature level from the view you are rendering to. In fact, views offer a convenient handle to the global shader map you should use when rendering to them: view.ShaderMap. here is the full snippet to retrieve the shader for a viewport, assuming you have no permutations (otherwise see <strong>Details&gt;Permutations</strong> below):</p><pre>TShaderMapRef&lt;FMyShader&gt; myShader{ view.ShaderMap };</pre><h4>HLSL</h4><p>To connect your shader class to an HLSL file implementing it, do the following:</p><ol><li>Put your shader code in a <em>.usf</em> file, within the shader folder we set up in part 1.</li><li>Inside the shader class, invoke the macro DECLARE_EXPORTED_SHADER_TYPE(T, Global, ), where T is your class. In the future when we define Material and Mesh-Material shaders, the second argument will be replaced with Material or MeshMaterial respectively. The third argument is an optional dll export token (like MYMODULE_API), if you want the class to be directly usable outside its module.<br>– There are several variants of this macro you can use instead which provide minor conveniences, like DECLARE_EXPORTED_GLOBAL_SHADER or DECLARE_SHADER_TYPE.</li><li>In a cpp file, invoke this macro:</li></ol><pre>IMPLEMENT_SHADER_TYPE(templateDecl, Class, VirtualShaderPath, MainFunction, Frequency)<br>//For example:<br>IMPLEMENT_SHADER_TYPE(, FMyNewVS, TEXT(“/Plugin/MyPlugin/myShader.usf”), TEXT(“MainVS”), SF_Vertex)</pre><p>– There are several variants of this macro you can use instead which provide minor conveniences, like IMPLEMENT_GLOBAL_SHADER or IMPLEMENT_MATERIAL_SHADER_TYPE.</p><p>4. The shader will be compiled as Unreal starts up, and any compilation errors will halt the startup process.</p><h4>Headaches</h4><p><strong><em>Important Notes!!! </em></strong><em>Unreal’s shader parser has a few bugs which will leave you banging your head against a wall for a few days if you don’t know about them.</em></p><p><strong>Never use the explicit </strong><strong>uniform keyword</strong> when declaring a parameter in HLSL, or UE’s shader compiler process will crash. uniform is already the default behavior when no keyword is provided, and you should always rely on that. Fortunately the other HLSL keywords like <em>static </em>work as expected.</p><p><strong>Never declare multiple uniforms in one statement</strong>. If you write float A, B; then Unreal will only see A and ignore B.</p><p><strong>Never add underscores to the front of your uniforms</strong>. This breaks the parser, we believe because it appends its own underscore and some shader compilers reserve double-underscored variables for internal use. This habit may be hard to break for those of you coming from Unity.</p><p>As mentioned in the Debugging section of the first article, <strong>DX12 will throw a very generic “invalid pipeline state” error if your vertex shader outputs don’t line up perfectly with your pixel shader inputs</strong>. Be careful when using your own pixel shader with a built-in vertex shader!</p><h4>Parameters</h4><p>Runtime parameters for your shader are normally defined with <em>parameter structs</em>.</p><ol><li>Use a special set of macros to define a struct whose fields are uploadable shader uniforms. This starts with BEGIN_SHADER_PARAMETER_STRUCT(structName, dllExportToken)<em> </em>and ends with END_SHADER_PARAMETER_STRUCT().</li><li>Inside your shader class, shadow the inherited typedef FParameters to point to that struct: using FParameters= structName;</li><li>Also inside your shader class, invoke the macro SHADER_USE_PARAMETER_STRUCT(FMyShaderClass, FGlobalShader).</li></ol><p>Within a parameter struct, you can add many kinds of data. Below is, to my knowledge, an exhaustive list of examples.</p><pre>BEGIN_SHADER_PARAMETER_STRUCT(FMyShaderParams, MY_MODULE_API)<br><br>//Add a single matrix.<br>//Must have in HLSL: float4x4 MyMatrix;<br>SHADER_PARAMETER(FMatrix44f, MyMatrix)<br>//Add an array of vectors.<br>//Must have in HLSL: uint4 MyUvecs[2];<br>SHADER_PARAMETER_ARRAY(FUintVector4, MyUvecs, [2])<br><br>//Add Sampleable textures and read-only buffers, a.k.a.<br>//   &quot;Shader Resource Views&quot;, or SRV&#39;s.<br>// * Here&#39;s a texture assuming you use this shader in an RDG pass,<br>//     requiring the HLSL: Texture2D&lt;float2&gt; MyTex;<br>SHADER_PARAMETER_RDG_TEXTURE_SRV(Texture2D&lt;float2&gt;, MyTex)<br>// * Here&#39;s a buffer assuming you use this shader outside an RDG pass<br>//     (or the buffer is always read-only so memory barriers don&#39;t matter),<br>//     requiring the HLSL: Buffer&lt;uint2&gt; MyUvecs2;<br>SHADER_PARAMETER_SRV(Buffer&lt;uint2&gt;, MyUvecs2)<br><br>//Add nonsampleable read-write textures, and read-write buffers, a.k.a.<br>//   &quot;Unordered Access Views&quot;, or UAV&#39;s.<br>// * If using an RDG pass you MUST declare them with RDG handles, like this<br>//     requiring the HLSL: RWTexture2D&lt;float4&gt; MyOutputTex;<br>SHADER_PARAMETER_RDG_TEXTURE_UAV(RWTexture2D&lt;float4&gt;, MyOutputTex)<br>// * If not using an RDG pass then you can store them as a plain RHI handle,<br>//     like this, requiring the HLSL: RWBuffer&lt;float&gt; MyOutputFloats;<br>SHADER_PARAMETER_UAV(RWBuffer&lt;float&gt; MyOutputFloats;<br><br>//Add sampler objects.<br>//   Requires the HLSL: SamplerState MySampler;<br>SHADER_PARAMETER_SAMPLER(SamplerState, MySampler)<br>//   Requires the HLSL: SamplerState MySamplers_0;<br>//                      SamplerState MySamplers_1;<br>//                      SamplerState MySamplers_2;<br>SHADER_PARAMETER_SAMPLER_ARRAY(SamplerState, MySamplers, [3])<br><br>//Add a reference to a global buffer.<br>//The struct referenced here is defined in VIEW_UNIFORM_BUFFER_MEMBER_TABLE,<br>//   partway down Engine/Public/SceneView.h, line 689 as of Unreal 5.3.<br>SHADER_PARAMETER_STRUCT_REF(FViewUniformShaderParameters, View)<br>// Example HLSL usage: float4x4 worldToView = View.TranslatedWorldToView;<br>// To set this parameter in the struct you provide a handle to the global buffer,<br>//     for example given your current View you can do:<br>//     params-&gt;View = currentView.ViewUniformBuffer;<br><br>//Paste another parameter struct into this one.<br>//The inner struct exists in C++, but<br>//    in HLSL the nested fields live next to our other ones.<br>SHADER_PARAMETER_STRUCT_INCLUDE(FNestedParamStruct, MyCppName)<br><br>//Nest another parameter struct within this one.<br>//The fields are nested both in C++, and in HLSL using a name prefix.<br>//This requires HLSL declarations of each field of the nested struct:<br>//   float NestedData_MyFloat; int NestedData_MyInts[2]; etc<br>SHADER_PARAMETER_STRUCT(FNestedParamStruct, NestedData)<br><br>//Add an array of some other parameter struct.<br>//This works similar to SHADER_PARAMETER_STRUCT, but also adding<br>//    the array index to the prefixed name of each field.<br>//This example requires HLSL declarations like so:<br>//    float MyStructs_0_MyFloat; int MyStructs_0_MyInts[2];<br>//    float MyStructs_1_MyFloat; int MyStructs_1_MyInts[2];<br>//    float MyStructs_2_MyFloat; int MyStructs_2_MyInts[2];<br>SHADER_PARAMETER_STRUCT_ARRAY(FNestedParamStruct, MyStructs, [3])<br><br>END_SHADER_PARAMETER_STRUCT()</pre><p>As mentioned above, most of the time you’re using an RDG to execute your shader and you should use the RDG declaration of textures/buffers rather than the standard RHI ones. When declared this way the parameter struct’s fields are an RDG handle rather than an RHI handle, allowing you to bind RDG temporary resources to them. This also tells the render graph that your pass uses those objects, which is especially important for objects that are written to in some passes and sampled from in others. The RDG issues memory barriers for all resources it knows about.</p><h4>Parameter Uploading</h4><p>To send a parameter struct to your shader, do one of the following:</p><ul><li>If working with a plain RHI command-list (usually not the case but you still need to know this), you can create the parameter struct anywhere, such as a local variable. Set its fields, then call the global helper function SetShaderParameters(cmds, shaderRef, shaderRef.GetPixelShader(), params). Replace GetPixelShader() with your own shader frequency.</li><li>If working with a higher-level RDG (usually the case), you should allocate the parameters within the graph using graph.AllocParameters&lt;FMyParamStruct&gt;(). This ensures that the parameter struct lives for the duration of the graph’s execution. Then you need to wait until execution time to call SetShaderParameters(…)<em>, </em>meaning you should call it within your AddPass(…) lambda. Luckily, in practice you will usually call global helper functions that wrap AddPass, such as AddDrawScreenPass(), and those usually call SetShaderParameters(…)<em> </em>for you. You also need to pass the struct, or an outer one that owns it, into AddPass(…) itself.</li></ul><p>In some cases your parameter struct will not be able to list <em>all</em> parameters for your shader. You may have parameters bound from external sources (Material shaders, covered in the next article, must generate and bind parameters from their Material), or you may inherit from a shader class which uses Legacy parameters (described below). Regardless of the reason, you need to tell Unreal to not freak out when your parameter struct is missing some uniforms, by replacing SHADER_USE_PARAMETER_STRUCT(…) with SHADER_USE_PARAMETER_STRUCT_WITH_LEGACY_BASE(…). If you forget to do this you will get an assert failure, however you can skip over it in the debugger and nothing bad should happen.</p><h4>Legacy Parameters</h4><p>There is an important “Legacy” alternative to parameter structs. It shows up in various engine shaders, and is <em>required </em>for Mesh-Material shaders. It involves declaring individual fields for each parameter within the shader class, then binding them manually in two different places.</p><p>We won’t need them until the article on Mesh-Material shaders, but it’s all over the engine code and I’ve described them below in the <strong>Details</strong> section.</p><h4>Workflow</h4><p>It’s common to hide the entire shader in a cpp file, and only expose a global function which invokes that shader the correct way. This is a form of encapsulation, making it impossible to misuse your shader. This convention also applies to Material and Mesh-Material shaders covered in later articles.</p><p>If you wish to expose your shader directly then make sure to declare the class in a header, and provide your DLL export token (e.x. MYMODULE_API) when invoking DECLARE_EXPORTED_SHADER_TYPE(…). Otherwise your users will get linker errors.</p><p>If you want to write a Vertex and Pixel shader pair that’s closely tied to each other, you can keep them in the same USF file with separate entry points (usually named MainVS and MainPS). In fact, any number of shader classes can reference the same USF file. There are built-in preprocessor flags telling your shader what frequency is compiling: VERTEXSHADER, PIXELSHADER, COMPUTESHADER, etc. You can also have your shader classes inject specific defines into the compilation environment by shadowing the inherited static function ModifyCompilationEnvironment(…).</p><h4>Built-in Parameters</h4><p>Many shaders throughout the engine reference data about the current viewport or current scene. A previous article mentioned how to add that into your own shader, but we will restate it here.</p><p><strong>View data </strong>can be referenced by adding SHADER_PARAMETER_STRUCT_REF(FViewUniformShaderParameters, View), and extracted from an <em>FViewInfo </em>with view.ViewUniformBuffer. The data provided by this structure can be found in the definition of VIEW_UNIFORM_BUFFER_MEMBER_TABLE, partway down <em>Engine/Public/SceneView.h</em>, line 689 as of Unreal 5.3. You can access the view data in your shader through the global View, however it’s recommended to invoke ResolvedView = ResolveView(); at the start of your shader and then reference the global ResolvedView<em> </em>instead. This will automatically handle stereo rendering cases (VR) for you, and nearly every Unreal shader starts with that statement.</p><p><strong>Scene data</strong> can be referenced by adding SHADER_PARAMETER_RDG_UNIFORM_BUFFER(FSceneUniformParameters, Scene), and extracted from an FViewInfo with view.GetSceneUniforms().GetBuffer(rdgInstance).</p><p><strong>G-buffer Textures </strong>are provided to you if you hook into the right place in the render pipeline (see Scene View Extensions in part 3), and you can add them to your shader parameter struct with SHADER_PARAMETER_RDG_UNIFORM_BUFFER( FSceneTextureShaderParameters, SceneTextures).</p><h3>Demo</h3><p>We are finally going to start on the effect described in the first article, by adding four global shaders to the project: one to initialize the Game of Life sim, one to resample the sim state when the player’s resolution/screen percentage changes, one to tick the sim, and one to display the sim state on the screen like a post-process effect.</p><p>These shaders will offer a few parameters to customize their behavior, which will be fed in from the controlling subsystem. In the next article we will remove the need to manually pass a bunch of parameters, by switching the three main shaders from Global to Material so that most parameters and logic will come from the Material itself.</p><p>The Game of Life is a discrete simulation, where each cell (pixel) is either alive or dead. We can represent this easily enough with a one-channel texture whose pixels are either 0 or 1. However to provide more interesting display options we’ll add a second channel whose values are continuous, constantly animating towards that binary value.</p><p>I also added a special actor to the demo scene which renders and displays a Scene Capture Component. This demonstrates that the effect automatically runs in every viewport like any other part of the renderer.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FbKIebry3qGI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DbKIebry3qGI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FbKIebry3qGI%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3681783d43ceb016e906d88c5aaae1d1/href">https://medium.com/media/3681783d43ceb016e906d88c5aaae1d1/href</a></iframe><p>As mentioned in the previous article, you need to make sure the pass gets created during gameplay. I do this in the level blueprint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*dTiK8t8aNRZ7wUAv4nYWcA.png" /><figcaption>Same as before, but without the stuff about randomly clearing render targets</figcaption></figure><h4>Sim State Data</h4><p>Each viewport will have its own Game of Life sim, so we need to manage persistent per-view data. Unreal has no easy way to know when a viewport is created or especially deleted, but my library has a class to deal with that for you. It automatically cleans up a viewport’s data after that viewport hasn’t been used for a certain number of frames. You can also mark a viewport to prevent automatic cleanup no matter how infrequently it’s used.</p><pre>//In the header:<br>struct GOL_DEMO_API FGameOfLifeView final : public F_EGP_ViewPersistentData<br>{<br>    static FRHITextureCreateDesc SimStateDesc(const FInt32Point&amp; viewportSize);<br>    <br>    //The simulation ping-pongs between two textures.<br>    TRefCountPtr&lt;FRHITexture2D&gt; SimState, SimBuffer;<br>    <br>    FGameOfLifeView(FRDGBuilder&amp; graph, const FViewInfo&amp; view,<br>                    const FIntRect&amp; viewportSubset);<br>    //Move constructor/assignment and destructor are handled automatically,<br>    //    thanks to the textures&#39; ref-counted pointer.<br>};<br><br>//In the cpp:<br>FRHITextureCreateDesc FGameOfLifeView::SimStateDesc(const FInt32Point&amp; viewportSize)<br>{<br>    //The sim looks pretty nice running at half-resolution.<br>    //This also cuts shader costs by 75%.<br>    auto texSize = viewportSize / 2;<br>   <br>    auto output = FRHITextureCreateDesc::Create2D(<br>       TEXT(&quot;GoL_State&quot;),<br>       texSize,<br>       PF_R8G8 //Two-channel unorm, 8 bits per channel<br>    );<br>    output.AddFlags(TexCreate_ShaderResource | TexCreate_UAV |<br>                    TexCreate_RenderTargetable);<br><br>    return output;<br>}<br>FGameOfLifeView::FGameOfLifeView(FRDGBuilder&amp; graph,<br>                                 const FViewInfo&amp; view,<br>                                 const FIntRect&amp; viewportSubset)<br>    : F_EGP_ViewPersistentData(graph, view, viewportSubset)<br>{<br>    auto desc = SimStateDesc(viewportSubset.Size());<br>    SimState = RHICreateTexture(desc);<br>    SimBuffer = RHICreateTexture(desc);<br>}</pre><p>Next we need to handle what happens when a player’s viewport gets resized. This is where we add our first, and simplest, shader.</p><pre>//In FGameOfLifeView:<br>virtual void Resample(FRDGBuilder&amp; graph, const FViewInfo&amp; view,<br>                      const FInt32Point&amp; oldResolution,<br>                      const FInt32Point&amp; newResolution,<br>                      const FInt32Point&amp; offsetDelta) override;<br><br>//In the cpp:<br>struct FGoLResamplePS : public FGlobalShader<br>{<br>    DECLARE_GLOBAL_SHADER(FGoLResamplePS); <br>    SHADER_USE_PARAMETER_STRUCT(FGoLResamplePS, FGlobalShader)<br>    <br>    //In practice most parameter structs are only used by one shader,<br>    //   so instead of a typedef you can directly define the struct<br>    //   within its shader class and name it FParameters.<br>    BEGIN_SHADER_PARAMETER_STRUCT(FParameters, )<br>       SHADER_PARAMETER_RDG_TEXTURE_SRV(Texture2D&lt;float2&gt;, InputTex)<br>       SHADER_PARAMETER_SAMPLER(SamplerState, InputSampler) <br>       RENDER_TARGET_BINDING_SLOTS()<br>    END_SHADER_PARAMETER_STRUCT()<br>};<br>IMPLEMENT_GLOBAL_SHADER(FGoLResamplePS, &quot;/GameOfLife/Resample.usf&quot;,<br>                        &quot;Main&quot;, SF_Pixel);<br>void FGameOfLifeView::Resample(FRDGBuilder&amp; graph, const FViewInfo&amp; view,<br>                               const FInt32Point&amp; oldResolution,<br>                               const FInt32Point&amp; newResolution,<br>                               const FInt32Point&amp; offsetDelta)<br>{<br>    //The sim state texture doesn&#39;t share viewport space<br>    //    like the main render-targets do, so we don&#39;t care<br>    //    about position changes -- only resolution changes.<br>    if (oldResolution == newResolution)<br>       return;<br><br>    //Get an RDG handle to the old state.<br>    auto oldState = SimState;<br>    auto oldStateRDG = RegisterExternalTexture(<br>                           graph, oldState,<br>                           TEXT(&quot;Previous_GoL_State&quot;)<br>                       );<br><br>    //Allocate the new resized state, and get an RDG handle to it.<br>    auto newDesc = SimStateDesc({ newResolution.X, newResolution.Y });<br>    SimState = RHICreateTexture(newDesc);<br>    SimBuffer = RHICreateTexture(newDesc);<br>    auto newStateRDG = RegisterExternalTexture(<br>                            graph, SimState,<br>                            TEXT(&quot;Next_GoL_State&quot;)<br>                       ); <br><br>    //NOTE: If the resolution change is more than 2x down or up<br>    //    then we will lose data; not a big deal for demo purposes<br>    //    but in real scenarios you may want to run several downscaling passes in a row.<br>    auto* params = graph.AllocParameters&lt;FGoLResamplePS::FParameters&gt;();<br>    params-&gt;InputTex = graph.CreateSRV(FRDGTextureSRVDesc{ oldStateRDG });<br>    params-&gt;InputSampler = TStaticSamplerState&lt;SF_Bilinear, AM_Clamp, AM_Clamp&gt;::GetRHI();<br>    params-&gt;RenderTargets[0] = { newStateRDG, ERenderTargetLoadAction::ENoAction };<br><br>    //Unreal&#39;s &quot;draw screen pass&quot; will by default:<br>    //    * Cover the whole screen using opaque blending<br>    //    * Use their own trivial Vertex Shader “FScreenPassVS”<br>    //This is perfect for our use-case.<br>    AddDrawScreenPass(<br>       graph, RDG_EVENT_NAME(&quot;ResizeGoLState&quot;), view,<br>       FScreenPassTextureViewport{ newStateRDG },<br>       FScreenPassTextureViewport{ oldStateRDG },<br>       TShaderMapRef&lt;FGoLResamplePS&gt;{ view.ShaderMap },<br>       params<br>    );<br>}</pre><p>If you try starting Unreal now, you’ll get an error that the shader file <em>Resample.usf</em> doesn’t exist. Add it to your plugin’s shader directory, <em>Shaders/Resample.usf</em>, containing the following code:</p><pre>#include &quot;/Engine/Private/Common.ush&quot;<br><br>//Parameters: <br>Texture2D&lt;float2&gt; InputTex;<br>SamplerState InputSampler; <br><br>//Implementation:<br>void Main(float4 pixelPos4 : SV_Position,<br>          //Input from FScreenPassVS:<br>          noperspective float4 uvAndScreenPos : TEXCOORD0,<br>          //Output to the sim state render target:<br>          out float2 newState : SV_Target0)<br>{<br>    newState = InputTex.SampleLevel(InputSampler, uvAndScreenPos.xy, 0);<br>}</pre><p>Finally, we need to use this data as part of our custom render pass object, U_GOL_RenderPass. Clear out its code from the previous article, which randomly cleared render targets, and add new code to track our sim state per-view.</p><pre>//In U_GOL_RenderPass:<br>T_EGP_PerViewData&lt;FGameOfLifeView&gt; PerViewData;<br>virtual void Tick_RenderThread(const FSceneInterface&amp; thisScene,<br>                               float gameThreadDeltaSeconds) override<br>{<br>    Super::Tick_RenderThread(thisScene, gameThreadDeltaSeconds);<br><br>    //Prune any viewport data that went unused for too many ticks.<br>    PerViewData.Tick();<br>}<br><br>//In U_GOL_RenderPass::PostRenderBasePassDeferred_RenderThread():<br>check(_view.bIsViewInfo);<br>auto&amp; view = reinterpret_cast&lt;FViewInfo&amp;&gt;(_view);<br>if (!Pass-&gt;ViewFilter-&gt;ShouldRenderFor(view))<br>    return;<br>//Get or create the GoL sim data for this view.<br>auto&amp; simData = Pass-&gt;PerViewData.DataForView(graph, view);<br>//Soon we will draw simData to the screen right here</pre><h4>Sim State Initialization</h4><p>Now we have sim data, but no initial values for the sim state. We’ll initialize it using Perlin-esque noise to decide whether each cell starts Alive (1) or Dead (0). This requires a new shader.</p><p>Add this code to your cpp file:</p><pre>struct FGoLInitializePS : public FGlobalShader<br>{<br>    DECLARE_GLOBAL_SHADER(FGoLInitializePS);<br><br>    BEGIN_SHADER_PARAMETER_STRUCT(FParameters, )<br>       SHADER_PARAMETER(float, Seed)<br>       SHADER_PARAMETER(float, NoiseScale) <br>       RENDER_TARGET_BINDING_SLOTS()<br>    END_SHADER_PARAMETER_STRUCT()<br>    SHADER_USE_PARAMETER_STRUCT(FGoLInitializePS, FGlobalShader)<br>};<br>IMPLEMENT_GLOBAL_SHADER(FGoLInitializePS, &quot;/GameOfLife/Init.usf&quot;, &quot;Main&quot;, SF_Pixel);</pre><p>and this HLSL code to <em>Shaders/Init.usf</em>:</p><pre>#include &quot;/Engine/Private/Common.ush&quot;<br><br>//Parameters:<br>float Seed;<br>float NoiseScale; <br><br>//Implementation:<br>void Main(float4 pixelPos4 : SV_Position,<br>          //Input from FScreenPassVS:<br>          noperspective float4 uvAndScreenPos : TEXCOORD0,<br>          //Output to the sim state render target:<br>          out float2 newState : SV_Target0)<br>{<br>    //Unreal&#39;s &#39;Random.ush&#39; gives us a lot of nice PRNG math,<br>    //    and has already been included through &#39;Common.ush&#39;.<br>    #define GOL_NOISE(scale, seed2) \<br>       GradientNoise3D_ALU(float3( \<br>           uvAndScreenPos.xy * NoiseScale * scale, \<br>           Seed + seed2 \<br>          ), false, 1.0)<br><br>    //Generate a random initial state.<br>    newState.y = (0.75 * GOL_NOISE(1.0, 0.0)) +<br>                 (0.20 * GOL_NOISE(2.0, 2.456)) +<br>                 (0.05 * GOL_NOISE(4.0, 1.8223));<br><br>    //The first channel is supposed to be a discrete bool.<br>    newState.x = step(0.5, newState.y);<br>}</pre><p>Before executing this shader, we need values for its parameters. Go to the pass object (U_GOL_RenderPass) and add some user-facing parameters:</p><pre>//Seed that&#39;s used when initializing the sim for a new viewport.<br>UPROPERTY(BlueprintReadWrite, EditAnywhere)<br>float NewViewportSeed = 1.432;<br><br>//The size of the sim’s initial noise for a new viewport.<br>UPROPERTY(BlueprintReadWrite, EditAnywhere)<br>float NewViewportNoiseScale = 10.0f;</pre><p>Were these any more complex than a float, we’d add Tick logic that safely uploads them into render-thread-only copies to prevent race conditions. That will happen with other parameters later on.</p><p>There is also normally a risk that the pass or subsystem gets destroyed in the game thread while its SVE is still trying to read these parameters on the render thread. However my library ensures this won’t happen, using <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-2-abf8237491c1">the fence logic covered in part 2</a>.</p><p>Finally, with all these pieces in place, we can add logic to run the initialization shader on every new viewport. Modify the constructor for FGameOfLifeView to take the parameters and invoke the shader:</p><pre>FGameOfLifeView::FGameOfLifeView(FRDGBuilder&amp; graph,<br>                                 const FViewInfo&amp; view,<br>                                 const FIntRect&amp; viewportSubset,<br>                                 float seed, float noiseScale)<br>    : F_EGP_ViewPersistentData(graph, view, viewportSubset)<br>{<br>    auto desc = SimStateDesc(viewportSubset.Size());<br>    SimState = RHICreateTexture(desc);<br>    SimBuffer = RHICreateTexture(desc);<br>    <br>    //Initialize the sim state using our pixel shader.<br>    auto simStateRDG = RegisterExternalTexture(graph, SimState,<br>                                               TEXT(&quot;GoL_InitialState&quot;));<br>    auto* initShaderParams = graph.AllocParameters&lt;FGoLInitializePS::FParameters&gt;();<br>    initShaderParams-&gt;Seed = seed;<br>    initShaderParams-&gt;NoiseScale = noiseScale;<br>    initShaderParams-&gt;RenderTargets[0] = {<br>        simStateRDG,<br>        //Previous RT contents are not needed<br>        ERenderTargetLoadAction::ENoAction<br>    };<br>    AddDrawScreenPass(<br>        graph, RDG_EVENT_NAME(&quot;GoL_Initialize&quot;), view,<br>        FScreenPassTextureViewport{ simStateRDG },<br>        FScreenPassTextureViewport{ simStateRDG-&gt;Desc.Extent },<br>        TShaderMapRef&lt;FGoLInitializePS&gt;{ view.ShaderMap },<br>        initShaderParams<br>    );<br>}</pre><p>These extra two constructor parameters must be passed in when we try to retrieve the view, in the SVE:</p><pre>//In U_GOL_RenderPass::PostRenderBasePassDeferred_RenderThread():<br>auto&amp; viewData = Pass-&gt;PerViewData.DataForView(<br>    graph, view,<br>    //If this is the first time encountering this view,<br>    //    the below arguments go into its constructor.<br>    //Dereferencing the Pass object within its SVE is OK!<br>    //Using game-thread-accessible data from the render-thread is also OK<br>    //    because they’re just cosmetic floats!<br>    Pass-&gt;NewViewportSeed, Pass-&gt;NewViewportNoiseScale<br>);</pre><p>With this in place, your project should automatically create a randomized Game of Life sim for each viewport in the running game. However, there’s no way to see this texture yet, and no logic to update it every frame.</p><h4>Display Shader</h4><p>Drawing the simulation on top of the screen could probably be accomplished with a normal Post-Process Material, but only with some annoying scripting to feed the sim state into the Material at runtime. It would also be tricky to support the effect appearing in more than one viewport. Finally, we couldn’t add the sim at more interesting stages such as drawing into the albedo right before lighting is calculated.</p><p>Instead we are going to set up our SVE to execute this new pass, just before the post-processing phase, writing to the Scene Color output. To start we need to update our module’s config, to include some header files related to post-processing.</p><pre>//In the module&#39;s .Build.cs file:<br>PrivateIncludePaths.AddRange(new string[] {<br>    System.IO.Path.Combine(GetModuleDirectory(&quot;Renderer&quot;), &quot;Private&quot;),<br>});</pre><p>Now let’s define the shader’s class in the cpp, with a helper function to invoke it:</p><pre>struct FGoLDisplayPS : public FGlobalShader<br>{<br>    DECLARE_GLOBAL_SHADER(FGoLDisplayPS);<br><br>    BEGIN_SHADER_PARAMETER_STRUCT(FParameters, )<br>       SHADER_PARAMETER_RDG_TEXTURE_SRV(Texture2D&lt;float2&gt;, SimState)<br>       SHADER_PARAMETER_SAMPLER(SamplerState, SimSampler)<br>       //To calculate UV in 0-1 space rather than the viewport&#39;s sub-set:<br>       SHADER_PARAMETER(FUint32Vector4, ViewportMinAndSize)<br>       RENDER_TARGET_BINDING_SLOTS()<br>    END_SHADER_PARAMETER_STRUCT()<br>    SHADER_USE_PARAMETER_STRUCT(FGoLDisplayPS, FGlobalShader)<br>};<br><br>IMPLEMENT_GLOBAL_SHADER(FGoLDisplayPS, &quot;/GameOfLife/Display.usf&quot;, &quot;Main&quot;, SF_Pixel);<br><br>//Helper function to assemble the GoL draw call.<br>static void RenderGoLState(FRDGBuilder&amp; graph, const FViewInfo&amp; view,<br>                           FRDGTextureRef simStateTex,<br>                           FRHIBlendState* blending,<br>                           const FRenderTargetBinding&amp; output)<br>{<br>    auto* params = graph.AllocParameters&lt;FGoLDisplayPS::FParameters&gt;();<br>    params-&gt;SimState = graph.CreateSRV(FRDGTextureSRVDesc{ simStateTex });<br>    params-&gt;SimSampler = TStaticSamplerState&lt;SF_Bilinear, AM_Clamp, AM_Clamp&gt;::GetRHI();<br>    params-&gt;ViewportMinAndSize = FUint32Vector4(<br>       view.ViewRect.Min.X, view.ViewRect.Min.Y,<br>       view.ViewRect.Width(), view.ViewRect.Height()<br>    );<br>    params-&gt;RenderTargets[0] = output;<br><br>    TShaderMapRef&lt;FGoLDisplayPS&gt; pixelShader{ view.ShaderMap };<br>    <br>    AddDrawScreenPass(<br>       graph, RDG_EVENT_NAME(&quot;GoL_Display&quot;), view,<br>       FScreenPassTextureViewport{ output.GetTexture() },<br>       FScreenPassTextureViewport{ simStateTex },<br>       //The overload that lets us pass a blend mode<br>       //   also requires that we pass a Vertex Shader.<br>       //This is the usual built-in screen pass VS.<br>       TShaderMapRef&lt;FScreenPassVS&gt;{ view.ShaderMap },<br>       pixelShader, blending, params<br>    );<br>}</pre><p>Next we’ll add the shader code, in <em>Shaders/Display.usf</em>.</p><pre>#include &quot;/Engine/Private/Common.ush&quot;<br><br>//Uniforms:<br>Texture2D&lt;float2&gt; SimState;<br>SamplerState SimSampler;<br>uint4 ViewportMinAndSize;<br><br>//Implementation:<br>float4 Main(in noperspective float4 uvAndScreenPos : TEXCOORD0,<br>            float4 pixelPos : SV_Position<br>           ) : SV_Target0<br>{<br>    //The UV from the vertex shader only covers a subset of the screen,<br>    //    for example in split-screen games.<br>    //But our sim state texture only contains pixels in that subset,<br>    //    so we want to use the full 0-1 UV space.<br>    float2 uv = (pixelPos.xy - float2(ViewportMinAndSize.xy)) /<br>                  float2(ViewportMinAndSize.zw);<br>    <br>    float2 currentState = SimState.SampleLevel(SimSampler, uv, 0);<br><br>    //As mentioned before there is an official discrete value in X<br>    //    and a continuous value in Y.<br>    //Create visual effects from both these values and mix together.<br>    float discreteEffectStrength = 0.3,<br>          totalEffectStrength = pow(max(currentState.x, currentState.y),<br>                                    0.3);<br>    float3 discreteEffect = currentState.x * float3(1, 0, 0),<br>           continuousEffect = pow(currentState.y, float3(3.0, 1.75, 1.0)),<br>           totalEffect = lerp(continuousEffect, discreteEffect, discreteEffectStrength);<br>    return float4(<br>        lerp(1.0, totalEffect, totalEffectStrength),<br>        1<br>    );<br>}</pre><p>You may be tempted to play with the display shader, and by all means — you can tweak the file then press “<strong>Ctrl+Shift+.</strong>” in the editor to quickly recompile it. But don’t forget that it gets much easier to play with after we convert these to Material shaders in the next article!</p><p>Finally we need to update the SVE to invoke the shader. Replace its “post-deferred” virtual function with the “pre-postprocess” one:</p><pre>void F_GOL_PassSVE::PrePostProcessPass_RenderThread(FRDGBuilder&amp; graph,<br>                                                    const FSceneView&amp; _view,<br>                                                    const FPostProcessingInputs&amp; inputs)<br>{<br>    check(_view.bIsViewInfo);<br>    auto&amp; view = reinterpret_cast&lt;const FViewInfo&amp;&gt;(_view);<br>    <br>    //Get or create the per-view data.<br>    auto&amp; viewData = Pass-&gt;PerViewData.DataForView(<br>       graph, view,<br>       Pass-&gt;NewViewportSeed, Pass-&gt;NewViewportNoiseScale<br>    ); <br><br>    //Draw the sim onto the scene color texture. <br>    auto simStateRDG = RegisterExternalTexture(graph, viewData.SimState,<br>                                               TEXT(&quot;GoL_State&quot;));<br>    RenderGoLState(<br>       graph, view, simStateRDG,<br>       //Use Multiply blending.<br>       TStaticBlendState&lt;CW_RGBA, BO_Add, BF_DestColor, BF_Zero&gt;::GetRHI(),<br>       {<br>           inputs.SceneTextures-&gt;GetContents()-&gt;SceneColorTexture,<br>           //We&#39;re blending on top of the current scene color,<br>           //    so make sure its existing contents are Loaded when bound.<br>           ERenderTargetLoadAction::ELoad<br>       }<br>    );<br>}</pre><p>With all of this written, you should be able to see a cloudy noise overlaid on the screen when you press Play.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1AvjkBCxPOOhb9IeeOD6dg.png" /></figure><p>You should also change your screen percentage during play to verify that the Resample shader works as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*yRGiJ8PnU3V0o8wnioJAuw.png" /><figcaption>Be aware, you can only change the percentage during PIE for some reason.</figcaption></figure><h4>Simulation</h4><p>The fourth and final shader will run one iteration of the Game of Life on our viewports’ state textures. Don’t worry if you don’t know the actual algorithm; the math isn’t as important as the general idea of making an animated, persistent render effect.</p><p>In the header, define some sim parameters.</p><pre>USTRUCT(BlueprintType)<br>struct GOL_DEMO_API FGameOfLifeSettings<br>{<br>  GENERATED_BODY()<br>public:<br><br>  UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(ClampMin=0))<br>  float OverallSpeed = 2.0f;<br>  UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(ClampMin=0))<br>  float MinSpeed = 0.3f;<br>  UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(ClampMin=0))<br>  float AccelerationExponent = 1.0f;<br>};</pre><p>In your pass object, provide those parameters to the user.</p><pre>UPROPERTY(BlueprintReadWrite, EditAnywhere)<br>FGameOfLifeSettings SimSettings;</pre><p>In your cpp file, set up and invoke a Simulate shader.</p><pre>struct FGoLSimulatePS : public FGlobalShader<br>{<br>  DECLARE_GLOBAL_SHADER(FGoLSimulatePS);<br><br>  BEGIN_SHADER_PARAMETER_STRUCT(FParameters, )<br>    SHADER_PARAMETER_RDG_TEXTURE_SRV(Texture2D&lt;float2&gt;, PreviousState)<br>    SHADER_PARAMETER(float, DeltaSeconds)<br><br>    //Sim control parameters:<br>    SHADER_PARAMETER(float, OverallSpeed)<br>    SHADER_PARAMETER(float, MinSpeed)<br>    SHADER_PARAMETER(float, AccelerationExponent)<br> <br>    RENDER_TARGET_BINDING_SLOTS()<br>  END_SHADER_PARAMETER_STRUCT()<br>  SHADER_USE_PARAMETER_STRUCT(FGoLSimulatePS, FGlobalShader)<br>};<br>IMPLEMENT_GLOBAL_SHADER(FGoLSimulatePS, &quot;/GameOfLife/Simulate.usf&quot;, &quot;Main&quot;, SF_Pixel);</pre><pre>static void UpdateGoLState(FRDGBuilder&amp; graph,<br>                           ERHIFeatureLevel::Type featureLevel,<br>                           FRDGTextureRef currentSimState,<br>                           FRDGTextureRef nextSimState,<br>                           float deltaSeconds,<br>                           const FGameOfLifeSettings&amp; settings)<br>{<br>  //The shader assumes input and output are the same size.<br>  check(currentSimState-&gt;Desc.Extent == nextSimState-&gt;Desc.Extent);<br> <br>  auto* params = graph.AllocParameters&lt;FGoLSimulatePS::FParameters&gt;();<br>  params-&gt;PreviousState = graph.CreateSRV(FRDGTextureSRVDesc{ currentSimState });<br>  params-&gt;DeltaSeconds = deltaSeconds;<br>  params-&gt;OverallSpeed = settings.OverallSpeed;<br>  params-&gt;MinSpeed = settings.MinSpeed;<br>  params-&gt;AccelerationExponent = settings.AccelerationExponent;<br>  params-&gt;RenderTargets[0] = { nextSimState, ERenderTargetLoadAction::ENoAction };<br><br>  auto* shaderMap = GetGlobalShaderMap(featureLevel);<br>  AddDrawScreenPass(<br>    graph, RDG_EVENT_NAME(&quot;GoL_Tick&quot;), featureLevel,<br>    FScreenPassTextureViewport{ nextSimState },<br>    FScreenPassTextureViewport{ nextSimState-&gt;Desc.Extent },<br>    TShaderMapRef&lt;FGoLSimulatePS&gt;{ shaderMap },<br>    params<br>  );<br>}</pre><p>In a new file <em>Shaders/Simulate.usf</em>, add the shader code.</p><pre>#include &quot;/Engine/Private/Common.ush&quot;<br><br>//Basic parameters<br>float DeltaSeconds;<br>Texture2D&lt;float2&gt; PreviousState;<br><br>//User-controlled parameters<br>float OverallSpeed;<br>float MinSpeed;<br>float AccelerationExponent;<br><br>//The Main function directly returns the new state.<br>float2 Main(in noperspective float4 uvAndScreenPos : TEXCOORD0,<br>            float4 pixelPos : SV_Position<br>           ) : SV_Target0<br>{<br>  uint2 stateSize;<br>  PreviousState.GetDimensions(stateSize.x, stateSize.y);<br><br>  //Sample the neighboring cell states.<br>  float2 prevStates[9];<br>  int2 ourPixel = int2(pixelPos.xy);<br>  const int ourIdx = 4;<br>  for (int x = -1; x &lt;= 1; ++x)<br>    for (int y = -1; y &lt;= 1; ++y)<br>    {<br>      int2 globalIdx = ourPixel + int2(x, y);<br>      int localIdx = (x + 1) + ((y + 1) * 3);<br>      bool inbounds = all(bool4(globalIdx &gt;= 0,<br>                                globalIdx &lt; stateSize);<br>      prevStates[localIdx] = inBounds ?<br>        PreviousState[globalIdx] :<br>        float2(0, 0);<br>    }<br><br>  //Count the number of living neighbors.<br>  float neighborStrength = 0;<br>  const float maxStrength = 8.0;<br>  for (int i = 0; i &lt; 9; ++i)<br>    if (i != ourIdx)<br>      neighborStrength += prevStates[i].x;<br><br>  //Apply the usual Game of Life rules to our cell,<br>  //  dying/living/resurrecting based on living neighbor count.<br>  //Also calculate a &quot;severity&quot; estimating the strength<br>  //  of the pull towards the new state.<br>  float targetValue, severityT, speedScale;<br>  const float ThresholdTooFew = 2,<br>              ThresholdResurrect = 2.5,<br>              ThresholdTooMany = 3;<br>  if (neighborStrength &lt; ThresholdTooFew)<br>  {<br>    //Die off, from underpopulation.<br>    targetValue = 0;<br>    severityT = 1.0 - (neighborStrength / ThresholdTooFew);<br>    speedScale = 1.0;<br>  }<br>  else if (neighborStrength &lt; ThresholdResurrect)<br>  {<br>    //Maintain current living status, from a normal population.<br>    targetValue = prevStates[ourIdx].x;<br>    severityT = 1.0;<br>    speedScale = 1.0;<br>  }<br>  else if (neighborStrength &lt;= ThresholdTooMany)<br>  {<br>    //Come alive, from an ideal population.<br>    targetValue = 1;<br>    severityT = (neighborStrength - ThresholdResurrect) /<br>                  max(0.0001, ThresholdTooMany - ThresholdResurrect);<br>    speedScale = 1.0;<br>  }<br>  else<br>  {<br>    //Die, from overpopulation.<br>    targetValue = 0;<br>    severityT = (neighborStrength - ThresholdTooMany) /<br>                  max(0.0001, maxStrength - ThresholdTooMany);<br>    speedScale = 1.0;<br>  }<br>  severityT = pow(saturate(severityT),<br>                  1.0 / max(0.00001, AccelerationExponent));<br><br>  //Now that we know our new discrete state,<br>  //    update our continuous state accordingly.<br>  float smoothValue = prevStates[ourIdx].y;<br>  float frameSpeed = DeltaSeconds *<br>                     max(MinSpeed, speedScale * severityT * OverallSpeed),<br>        frameVelocity = frameSpeed * sign(targetValue - smoothValue);<br>  if (distance(smoothValue, targetValue) &lt; frameSpeed)<br>    smoothValue = targetValue;<br>  else<br>    smoothValue += frameVelocity;<br><br>  return float2(targetValue, smoothValue);<br>}</pre><p>In our render pass object, execute the sim tick for each viewport.</p><pre>void U_GOL_RenderPass::Tick_RenderThread(const FSceneInterface&amp; thisScene, float gameThreadDeltaSeconds)<br>{<br>  //These two lines should already exist<br>  Super::Tick_RenderThread(thisScene, gameThreadDeltaSeconds);<br>  PerViewData.Tick();<br><br>  //Run our &quot;simulate&quot; shader on all viewports.<br>  FRDGBuilder graph{ FRHICommandListImmediate::Get(),<br>                     RDG_EVENT_NAME(&quot;UpdateAllGoLViewports&quot;) };<br>  //the sim settings struct is POD, and its values are cosmetic,<br>  //    so there is no need to avoid race conditions<br>  //    by keeping a separate render-thread copy.<br>  auto simSettings = SimSettings;<br>  PerViewData.ForEachView([&amp;](int viewID, FGameOfLifeView&amp; view,<br>                              ERHIFeatureLevel::Type featureLevel) {<br>    UpdateGoLState(<br>      graph, featureLevel,<br>      RegisterExternalTexture(graph, view.SimState,<br>                              TEXT(&quot;GoL_PrevState&quot;)),<br>      RegisterExternalTexture(graph, view.SimBuffer,<br>                              TEXT(&quot;GoL_NextState&quot;)),<br>      gameThreadDeltaSeconds,<br>      simSettings<br>    );<br>    std::swap(view.SimBuffer, view.SimState);<br>  });<br>  graph.Execute();<br>}</pre><p>That’s it! Now the Game of Life simulation should run as soon as you start running the game, and look like the animation at the top of this Demo section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gqRWf2ITfKIs_HNqNqticg.png" /><figcaption>A screenshot after some shader and parameter tweaks</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0GWT5xlk1KN8N5hFLXZtpg.png" /><figcaption>Each viewport gets its own effect, subject to the pass object’s <strong>ViewFilter</strong></figcaption></figure><p>If you add the following line in your pass’s Init function, you can see that the effect only applies to the player’s view and not to Scene Capture Components:</p><pre>ViewFilter-&gt;FilterByPlayerIdx(0);</pre><h3>Code</h3><p>The global shaders are added to the demo in the <em>part/4 </em>branch:</p><p><a href="https://github.com/heyx3/UnrealExtendedGraphicsProgrammingDemo/tree/part/4">heyx3/UnrealExtendedGraphicsProgrammingDemo at part/4</a></p><h3>Details</h3><h4>Permutations</h4><p>Shader permutations are created by defining special helper structs that represent each one, then shadowing the typedef FPermutationDomain to list those helper structs. For example:</p><pre>//Inside the shader class:<br><br>//The shader will either see<br>//    ‘#define PARALLAX_MAPPING 0’, or ‘#define PARALLAX_MAPPING 1’.<br>class FEnableParallaxMapping : SHADER_PERMUTATION_BOOL(“PARALLAX_MAPPING”);<br>//The shader will see ‘#define ITER_COUNT n’ where n is 0, 1, or 2.<br>class FIterationCount : SHADER_PERMUTATION_INT(“ITER_COUNT”, 3);<br><br>using FPermutationDomain = TShaderPermutationDomain&lt;<br>    FEnableParallaxMapping,<br>    FIterationCount<br>&gt;;</pre><p>An instance of FPermutationDomain<em> </em>can be converted to a unique ID and back again using domain.ToDimensionValueId(). Generally functions which take a permutation or permutation ID will default to 0 for shaders that don’t have any permutations.</p><p>To retrieve a specific permutation from a shader map, do this:</p><pre>FMyShaderPS::FPermutationDomain permutation;<br>permutation.Set&lt;FMyShaderPS::FEnableParallaxMapping&gt;(true);<br>permutation.Set&lt;FMyShaderPS::FIterationCount&gt;(1);<br>TShaderMapRef&lt;FMyShaderPS&gt; myShader{ view.ShaderMap, permutation };</pre><p>Once a shader has multiple permutation parameters it’s highly recommended to eliminate redundant ones by shadowing the static function RemapPermutation(...). For example, if permutation integer <em>A</em> only matters when permutation bool <em>B</em> is true, then RemapPermutation(...) should set <em>A</em> to a constant value when <em>B</em> is false. Anybody who’s made or played Unreal games knows how painful shader permutation compiling can be!</p><h4>The Shader Class</h4><p>Conventionally, shader classes are suffixed based on the kind of shader they are — VS, PS, CS, etc.</p><p>Some other static shader functions you can shadow are:</p><ul><li><strong>static bool ShouldCompilePermutation(const FGlobalShaderPermutationParameters&amp; permutation)</strong> decides whether your shader should be compiled in a particular environment. For example your shader may require the SM6 shader model, or the Metal graphics API, or editor-only data. If you have custom shader permutations, then you could also check them here to reduce the number of shaders in your game.</li><li>s<strong>tatic void ModifyCompilationEnvironment(const FShaderPermutationParameters&amp; permutation, FShaderCompilerEnvironment&amp; env)</strong> can customize the compilation environment for your shader. Add virtual include paths, <em>#define</em> preprocessor tokens, enable specific compiler flags (see <em>ECompilerFlags</em>), and more.</li><li><strong>static bool ValidateCompiledResult(EShaderPlatform platform, const FShaderParameterMap&amp; parameters, TArray&lt;FString&gt;&amp; outErrorMessages)</strong> lets you return false and generate error messages if something is wrong with your shader’s inputs and outputs, for example if it tries to read from an input that you know won’t exist in the places you invoke it. This one is very situational.</li></ul><p>The empty parameters you see in shader class macros are for one of two purposes:</p><ul><li>Template arguments, in case your shader class is templated.</li><li>Your DLL export statement (like MYMODULE_API), in case you want the shader to be used by outsiders. If you don’t want that then it’s recommended to keep the shader entirely inside a cpp file.</li></ul><p>It seems possible to write Global or Material shaders that do simple 3D scene drawing, instead of the much more complex Mesh-Material shaders which draw the “mesh batches” contained in drawable components. For in-engine examples of simple 3D rendering see FDeferredDecalVS (a global shader) and its partner FDeferredDecalPS<em> </em>(a Material shader).</p><h4>Legacy shader parameters (the alternative to parameter structs)</h4><p>This is how to define and upload shader parameters without the use of an FParameters<em> </em>struct.</p><p><strong>Fields</strong></p><p>When you used a parameter struct, its fields were being automatically bound through the inherited field FShader::Bindings. Now we will supplant this with individual binding fields for each parameter. All shader parameters must be declared as a field, in one of the following ways based on their type:</p><pre>LAYOUT_FIELD(FShaderParameter, MyNormalParam);<br>LAYOUT_FIELD(FShaderResourceParameter, MySrvOrUavOrSamplerParam);<br>LAYOUT_FIELD(FShaderUniformBufferParameter, MyNestedParamStruct);<br>LAYOUT_FIELD(FShaderUniformBufferParameter, MyGlobalBufferRef);</pre><p><em>Note that </em><em>FShaderUniformBufferParameter</em> <em>can represent both persistent global uniform buffers, and local/short-term ones (effectively pasting in the contents of a parameter struct). There is a slight difference in how each gets uploaded, mentioned below.</em></p><p>Next define constructors for your shader that tie those fields to HLSL parameters. With parameter structs these constructors had been generated for you, inside SHADER_USE_PARAMETER_STRUCT. When binding parameters you should describe them as “optional” or “mandatory”, describing whether it’s an error for the parameter to be missing from the shader.</p><pre>FMyShaderPS() = default;<br>FMyShaderPS(const ShaderMetaType::CompiledShaderInitializerType&amp; initializer)<br>    : FGlobalShader(initializer) //Or whatever your parent type is<br>{<br>    MyNormalParam.Bind(<br>        initializer.ParameterMap,<br>        TEXT(“MyFloat”), //The name in HLSL<br>        SPF_Mandatory //We know the float exists in our shader<br>    );<br>    MySrvOrUavOrSamplerParam.Bind(<br>        initializer.ParameterMap,<br>        TEXT(“MyOutputTex”), //The name in HLSL<br>        SPF_Mandatory //The output of this shader is important!<br>    );<br>    MyNestedParamStruct.Bind(<br>        Initializer.ParameterMap,<br>        //Get the HLSL name of the buffer<br>        FSomeParamStruct::FTypeInfo::GetStructMetadata()<br>            -&gt;GetShaderVariableName()<br>    );<br>    MyGlobalUniformBuffer.Bind(<br>        Initializer.ParameterMap,<br>        //Get the HLSL name of the buffer<br>        FSomeGlobalUniformBuffer::FTypeInfo::GetStructMetadata()<br>            -&gt;GetShaderVariableName()<br>    );<br>}</pre><p><strong>Upload</strong></p><p><em>TL;DR The basic workflow for dispatching a compute shader using legacy parameter fields should look like below. Other shader types work very similarly, just with more extraneous details like binding vertex/index buffers. The interesting part for us is lines 2 and 4, which you can read through to see how they unpack boilerplate and interact with your shader class.</em></p><pre>SetComputePipelineState(cmdList, shaderRef.GetComputeShader());<br>SetShaderParametersLegacyCS(cmdList, shaderRef, params…)<br>DispatchComputeShader(cmdList, shaderRef,<br>                      groupSizeX, groupSizeY, groupSizeZ);<br>UnsetShaderParametersLegacyCS(cmdList, shaderRef);</pre><p>To store the parameters for upload, grab a memory block from the RHI command-list with</p><pre>auto&amp; parameterMemory = cmds.GetScratchShaderParameters();</pre><p>Call global functions which write into this memory — primarily SetShaderValue(…), SetShaderValueArray(…), SetSRVParameter(…), SetUAVParameter(…), and SetUniformBufferParameter[Immediate](…). These functions will take your memory block, one of your binding fields defined above, and the new value for that field.</p><p>After that’s done, upload all your parameters to your shader on the GPU with</p><pre>cmds.SetBatchedShaderParameters(shaderRHIHandle, parameterMemory)</pre><p>Now you can execute your shader!</p><p><strong><em>NOTE</em></strong><em>: </em><em>SetUniformBufferParameterImmediate is for one-off buffer structs that you allocated for this draw call, while </em><em>SetUniformBufferParameter is for persistent/global buffers. In some cases the engine doesn’t appear to explicitly call </em><em>SetUniformBufferParameter, and I haven’t figured out why yet…perhaps the RDG steps in to handle it for you?</em></p><p><strong><em>NOTE:</em></strong><em> With both kinds of uniform buffers (immediate and persistent), rather than taking the binding field directly, Unreal code usually gets the binding with</em> <em>myShader-&gt;GetUniformBufferParameter&lt;FMyBufferStruct&gt;(). I don’t know why, or what happens if you pass the binding field directly instead.</em></p><p>When you need to upload params to more than one shader (e.g. VS and PS), you can reuse the parameter memory block. Just make sure to call parameterMemory.Reset() in-between them. This is already called automatically each time you retrieve the memory block from the command-list.</p><p><strong>Implement </strong><strong>SetParameters()</strong></p><p>To remove boilerplate and chances for error, there is a common convention to keep the parameter fields private and define a public member function named SetParameters which sets all of them at once. Then you can call the global functions<em> </em>SetShaderParametersLegacy[PS|VS|CS|etc](cmdList, shaderRef, args…) which handles most of the boilerplate and offers a very simplified and safe interface for configuring your shader. This is especially valuable if your shader is exposed in a header for others to use.</p><p><strong><em>NOTE:</em></strong><em> Some engine shader classes also have an old deprecated </em><em>SetParameters implementation with a different signature; ignore those in favor of the convention described above.</em></p><p>Finally, after execution it’s important to unbind all your SRV and UAV resources. Fortunately the syntax is extremely similar to binding them: get a memory block with</p><pre>auto&amp; unbindingMemory = cmds.GetScratchShaderUnbinds();</pre><p>and make calls to UnsetSRVParameter(…) and UnsetUAVParameter(…), then finalize it with</p><pre>cmds.SetBatchedShaderUnbinds(shaderRHIHandle, unbindingMemory);</pre><p>Just like the convention of defining SetParameters and calling SetShaderParametersLegacy[PS|VS|CS|etc], there is an identical convention for unbinding resources: define UnsetParameters(…) for your class and then you can call UnsetShaderParametersLegacy[PS|VS|CS|etc].</p><p><strong><em>NOTE:</em></strong><em> It seems there are places in the engine which use legacy parameter code, but don’t unset their SRV’s and UAV’s afterwards. Perhaps because they’re inside an RDG pass which is already aware of those resources? More research is needed.</em></p><p>Notably, the SetParameters(…) convention is not used for Mesh-Material shaders. These have a slightly different workflow involving per-primitive “elements” which hold your parameters.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c89d6fb98b59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Graphics Programming in Unreal, part 3]]></title>
            <link>https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-3-f37f4d4407d7?source=rss-384faa1a8ea4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f37f4d4407d7</guid>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[unreal-engine-5]]></category>
            <category><![CDATA[graphics-programming]]></category>
            <category><![CDATA[technical-art]]></category>
            <dc:creator><![CDATA[William Mishra-Manning]]></dc:creator>
            <pubDate>Tue, 24 Jun 2025 17:09:09 GMT</pubDate>
            <atom:updated>2025-11-05T18:35:36.025Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a seven-part article series.</p><p>Part 1:<a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-1-10488f2e17dd"> Introduction</a><br>Part 2: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-2-abf8237491c1">Rendering Abstractions (RHI, RDG) and Threading</a><br><strong>Part 3: Scenes. Views, and SceneViewExtension</strong><br>Part 4: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-4-c89d6fb98b59">Global Shaders</a><br>Part 5: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-5-ea988fd1034e">Simple Material Shaders</a><br>Part 6: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-6-5477dbb64608">Advanced Material Shaders</a><br>Part 7: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-7-d3500d4b8195">Mesh-Material Shaders and Mesh Passes</a></p><h3>Scenes and Views</h3><p>The last step before we start writing our own render passes is to understand how Unreal organizes scene and view data. The major data types are listed here from outermost to innermost: Scene, Scene Renderer, View Family, and View.</p><p>We also need to go over per-view data management and <em>Scene-View Extensions</em>, which are custom hooks into the render pipeline. They are the building blocks of a custom render pass!</p><h3>Theory</h3><h4>Scene</h4><p>FSceneInterface, and its concrete child FScene, are the render-thread equivalent of a UWorld. They hold a list of the world’s render-related components (meshes, decals, lights, etc.), with their associated proxies which are periodically updated and batched.</p><p>The concrete FScene<em> </em>also contains numerous collections and GPU resources needed to render the world. For example, it holds the directional lights data in the array DirectionalLights. It also owns an instance of the inner struct FGPUScene, which contains the GPU-side buffers.</p><h4>Scene Renderer</h4><p>An FSceneRenderer<em> </em>is a short-term object, allocated to render a single frame of a scene. It owns a group of view-families and views (see below). I have not directly interacted with this type, but it’s there.</p><h4>View Family</h4><p>An FSceneViewFamily<em> </em>represents a single configured viewport (player view, Scene Capture Component, etc), rendering to either the screen or a texture. In practice it is one of two child types:</p><ul><li>FSceneViewFamilyContext for short-term uses, like one-off renders or screen-space calculations. In the latter case it also uses the simplest base class for its views, FSceneView.</li><li>FViewFamilyInfo for significant rendering work in a real scene.</li></ul><p>Its most important fields are:</p><ul><li>RenderTarget, the target to render into (presumably nullptr if rendering to the screen)</li><li>Scene, the scene being viewed</li><li>Views, an array of owned views into the scene (see below).</li></ul><p>View families can be created and released at will; the operation doesn’t look cheap to me but there are many examples of them being constructed as local variables for quick screen-space calculations. Examples of classes which create or own view families:</p><ul><li>A player’s HUD actor, AHUD</li><li>The game’s UViewportClient (a singleton except in special editor cases)</li><li>Any FSceneRenderer instances (see above).</li></ul><h4>View</h4><p>An FSceneView<em> </em>is a specific point-of-view for a View Family to render from. I am not sure yet exactly why a view-family would have multiple views, but it’s possible this is for offscreen effects which come from derived POV’s (like cascaded shadow maps and planar reflections), as well as VR which must display two points of view.</p><p>Like view-families themselves, many view instances in a program are just short-term stubs for doing screen-space calculations. If a view is actually used for rendering, then it’s usually the child class FViewInfo. Renderable views also, as far as I can tell, always need an associated state object FSceneViewState. This state is sometimes referred to by its base class FSceneViewStateInterface.</p><p>Any time you have an FSceneView in your rendering pass, it’s most likely a full FViewInfo. You can unpack it with the following snippet:</p><pre>const FSceneView&amp; view = ...; //Get a view somehow<br>if (view.bIsViewInfo)<br>{<br>    const auto&amp; asViewInfo = static_cast&lt;const FViewInfo&amp;&gt;(view);<br>    ... //Use the view-info<br>}<br>else<br>{<br>    //It&#39;s some other kind of view type.<br>    checkf(false, TEXT(&quot;Unexpected kind of scene-view!&quot;));<br>}</pre><h4>Custom Per-View Resources</h4><p>When doing custom render passes, you may need persistent resources for each viewport that uses the pass. There is a class which appears to support this, ISceneViewFamilyExtentionData (sic), however it’s half-baked and does not work as of 5.3. UE 5.5 has some other interesting things but has not appeared to solve this problem for external users of the engine. Therefore we need our own system for tracking persistent resources per-view.</p><p>Fortunately, my library offers a utility for this! T_EGP_PerViewData, which will be used in the next article.</p><h4>GPU Buffers of Scene/View Data</h4><p>Countless engine shaders reference data about the view and/or scene they are rendering inside. Shaders are explained more in part 4, but I will say here that you can add some common global buffers to your shader’s <em>parameter struct</em> with this snippet:</p><pre>//Necessary headers:<br>#include &quot;Runtime/Renderer/Private/SceneRendering.h&quot;<br><br>//In the parameter struct (see Part 4 of this series):<br>    // Tons of camera data, including matrices<br>    SHADER_PARAMETER_STRUCT_REF(FViewUniformShaderParameters, View)<br>    // Scene color, scene depth, G-buffer data, and more,<br>    //    depending on where in the pipeline your shader executes<br>    SHADER_PARAMETER_RDG_UNIFORM_BUFFER(FSceneTextureShaderParameters, SceneTextures)<br>    // Provides the data in FGPUSceneResourceParameters<br>    SHADER_PARAMETER_RDG_UNIFORM_BUFFER(FSceneUniformParameters, Scene)<br>    // Not sure exactly what it provides, but is popular/maybe-required<br>    //    in MeshMaterial shaders (perhaps LOD data, Instancing, or Nanite).<br>    // However it can also be null I think?<br>    SHADER_PARAMETER_STRUCT_INCLUDE(FInstanceCullingDrawParams, InstanceCullingDrawParams)<br><br>//In the setup for your RDG pass:<br>const FViewInfo&amp; view = ...; //Got a view somehow<br>const FSceneTextureShaderParameters&amp; sceneTextures = ...; //Got the main pass’s outputs somehow<br>auto* params = graph.AllocParameters&lt;FMyShaderParams&gt;(); //The shader parameter struct<br>params-&gt;View = view.ViewUniformBuffer;<br>params-&gt;Scene = view.GetSceneUniforms().GetBuffer(graph);<br>params-&gt;SceneTextures = sceneTextures;<br>params-&gt;InstanceCullingDrawParams = nullptr; //Frankly not sure how to get this one,<br>                                             //  apart from the very specific workflow of mesh passes<br>                                             //  covered in part 7</pre><h4>Scene-View Extensions and Custom Passes</h4><p>While ENQUEUE_RENDER_COMMAND() is very useful, it doesn’t allow you to change how a scene is rendered. To hook into the render pipeline you need to define and manage your own FSceneViewExtension.</p><p>Many of the details of this process are covered for you by my library, <em>ExtendedGraphicsProgramming </em>or “EGP” for short. See the <strong>Details</strong> section for under-the-hood info. Assuming you’ll use my library, define a new class inheriting from T_EGP_RenderPassSceneViewExtension&lt;P&gt;. The template parameter should be another custom object you define, inheriting from U_EGP_RenderPass, which holds the global parameters for your pass. It’s recommended to define these parameters as UPROPERTY’s so that your pass can be configured in Blueprints if desired. If any properties are more than POD, they should probably have separate game-thread and render-thread copies.</p><p>The SVE base class offers various virtual functions that hook into the Render Thread while it’s rendering each viewport. Each callback is for a specific phase of the render pipeline and provides you with an RDG to write commands into. It also provides data specific to each phase; for example PrePostProcessPass_RenderThread will provide you with all the usual inputs to a post-process Material while PostRenderBasePassDeferred_RenderThread will provide you with references to the G-buffer for both reading and<em> </em>writing.</p><p>Your custom U_EGP_RenderPass<em> </em>object will belong to a single World, managed through my plugin’s subsystem U_EGP_RenderPassSubsystem. You can create or retrieve the pass with</p><pre>auto* myPass = GetWorld()<br>                   -&gt;GetSubsystem&lt;U_EGP_RenderPassSubsystem&gt;()<br>                   -&gt;GetPass&lt;UMyRenderPass&gt;(bCreateIfNotExisting)</pre><p>The pass object can override various events, including tick functions in both Game and Render thread. The tick functions will run once per frame, no matter how many views there are.</p><p>Your pass object is required to at least implement InitThisPass_GameThread(…), to return a constructed instance of your SVE. SVE’s must be created by invoking</p><pre>FSceneViewExtensions::NewExtension&lt;FMySVE&gt;(args...)</pre><p>This function will pass all arguments into your SVE’s constructor. Refer to the engine for examples of how to define an SVE.</p><h3>Demo</h3><p>For this entry we’ll set up a scene-view extension using my library and have it randomly clear the albedo g-buffer texture to a solid color, similar to the last demo. The color can optionally be forced through C++/Blueprints, using parameters that are periodically uploaded to the Render Thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*sRgGogkrhUDHxowBRICpaQ.png" /><figcaption>The demo scene with its albedo cleared to Cyan</figcaption></figure><p>First declare your new custom pass in a header:</p><pre>#include &quot;EGP_CustomRenderPasses.h&quot;<br><br>UCLASS(BlueprintType)<br>class GOL_DEMO_API U_GOL_RenderPass : public U_EGP_RenderPass<br>{<br>    GENERATED_BODY()<br><br>public:<br>    UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(InlineEditConditionToggle))<br>    bool ForceColor = false;<br>    UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(EditCondition=&quot;ForceColor&quot;))<br>    FLinearColor ForcedColor = { 1, 0, 1, 1 };<br><br>    TOptional&lt;FLinearColor&gt; GetClearColor_RenderThread() const<br>    {<br>       check(IsInRenderingThread());<br>       return color_renderThread;<br>    }<br><br>protected:<br>    virtual TSharedRef&lt;F_EGP_RenderPassSceneViewExtension&gt;<br>                 InitThisPass_GameThread(UWorld&amp; thisWorld) override;<br>    virtual void Tick_GameThread(UWorld&amp; thisWorld, float deltaSeconds) override;<br><br>private:<br>    TOptional&lt;FLinearColor&gt; color_renderThread;<br>};</pre><p>Also declare the scene-view extension that executes the pass:</p><pre>struct GOL_DEMO_API F_GOL_PassSVE<br>    : public T_EGP_RenderPassSceneViewExtension&lt;U_GOL_RenderPass&gt;<br>{<br>    //Re-use the parent constructor (which takes a pointer to the pass).<br>    using T_EGP_RenderPassSceneViewExtension::T_EGP_RenderPassSceneViewExtension;<br><br>    //Apply our effect immediately after the deferred pass,<br>    //    before lighting is computed.<br>    virtual void PostRenderBasePassDeferred_RenderThread(<br>       FRDGBuilder&amp; graph, FSceneView&amp; view,<br>       const FRenderTargetBindingSlots&amp; renderTargets,<br>       TRDGUniformBufferRef&lt;FSceneTextureUniformParameters&gt; sceneTextures<br>    ) override;<br>};</pre><p>Finally, define both of these objects in a cpp file.</p><pre>#include &quot;GOL_RenderPass.h&quot;<br>#include &quot;RenderGraphUtils.h&quot;<br><br>TSharedRef&lt;F_EGP_RenderPassSceneViewExtension&gt; U_GOL_RenderPass::<br>    InitThisPass_GameThread(UWorld&amp; thisWorld)<br>{<br>    //By default, only apply this pass to the first player-controller’s view.<br>    ViewFilter-&gt;FilterByPlayerIdx(0);<br>    <br>    return FSceneViewExtensions::NewExtension&lt;F_GOL_PassSVE&gt;(this);<br>}<br>void U_GOL_RenderPass::Tick_GameThread(UWorld&amp; thisWorld, float deltaSeconds)<br>{<br>    //Pick the new clear color (or null to not clear this frame).<br>    TOptional&lt;FLinearColor&gt; newClearColor;<br>    if (ForceColor || FMath::FRand() &lt; 0.09f)<br>    {<br>       newClearColor = (ForceColor ?<br>                      ForcedColor :<br>                      FLinearColor{ FMath::FRand(), FMath::FRand(), FMath::FRand() });<br>    }<br>    <br>    //Copy the color and field pointer into a lambda and send that lambda to the render thread.<br>    //This prevents race conditions from corrupting that color value.<br>    auto* outputPtr = &amp;color_renderThread;<br>    auto updateClearColor = [outputPtr, newClearColor](FRHICommandListImmediate&amp;) {<br>       *outputPtr = newClearColor;<br>    };<br>    ENQUEUE_RENDER_COMMAND(UpdateClearColor)(MoveTemp(updateClearColor));<br>}<br><br>void F_GOL_PassSVE::PostRenderBasePassDeferred_RenderThread(<br>    FRDGBuilder&amp; graph, FSceneView&amp; view,<br>    const FRenderTargetBindingSlots&amp; renderTargets,<br>    TRDGUniformBufferRef&lt;FSceneTextureUniformParameters&gt; sceneTextures<br>) {<br>    auto tryClearColor = Pass-&gt;GetClearColor_RenderThread();<br>    auto sceneColor = renderTargets.Output[0].GetTexture();<br><br>    if (tryClearColor.IsSet() &amp;&amp; sceneColor != nullptr)<br>        AddClearRenderTargetPass(graph, sceneColor, *tryClearColor);<br>}</pre><p>Lastly we need to ensure the pass is created by calling (either in C++ or Blueprints):</p><pre>U_EGP_RenderPassSubsystem::GetPass(U_GOL_RenderPass::StaticClass(), true);</pre><p>I did it in the demo level’s Level Blueprint, and also forced it to always use Cyan:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*HTsXjqqFVoFEquTuPVethw.png" /><figcaption>Create the pass on level start, and force it to use Cyan</figcaption></figure><p>When you press Play you should see the opaque parts of the screen flicker in Cyan. Below is what it looks like with ‘Force Color’ turned off.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FKdqBfnehJXo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKdqBfnehJXo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FKdqBfnehJXo%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e26b3fc6e9d3f0050b29fd5fe24eb6d7/href">https://medium.com/media/e26b3fc6e9d3f0050b29fd5fe24eb6d7/href</a></iframe><h3>Code</h3><p>The SVE is added to the demo repo in the <em>part/3</em> branch:</p><p><a href="https://github.com/heyx3/UnrealExtendedGraphicsProgrammingDemo/tree/part/3">heyx3/UnrealExtendedGraphicsProgrammingDemo at part/3</a></p><h3>Details</h3><h4>Per-View Resource Management</h4><p>My library manages custom per-view resources by performing three things:</p><ul><li>Lazy-initialization of the data each time a new view is found</li><li>Resampling of the data whenever the screen resolution changes</li><li>Automatic cleanup of the data after a certain number of frames, because I can’t for the life of me find any way to know when a view has officially been destroyed.</li></ul><p>Views and view-families are recreated each frame, so you can’t index the data by pointer! Instead use their persistent ID:</p><pre>auto viewID = view.State-&gt;GetViewKey();</pre><h4>Scene/View workflows</h4><p>Many of the basic scene/view functions are in the renderer module object itself <em>(</em>gettable with GetRendererModule()). For example check out CreateAndInitSingleView(…) or AllocateViewState(…). You likely won’t ever need to call these functions but reading them can help you understand how the various responsibilities of the rendering module are organized.</p><p>It’s not stated explicitly anywhere, but based on engine code I believe you are supposed to create new SVE’s on the Game Thread only. If your subsystem is the sole owner of an SVE through a TSharedPtr&lt;&gt;, you can prematurely kill the SVE with myPtr.Reset().</p><p>Implementing a 3D scene pass in an SVE is complicated, even with the help of my library, and won’t be covered until the 7th and final article in this series. You first need to be comfortable with how Unreal does shaders.</p><p>Your SVE can override functions to hook into various phases in the rendering of any and all viewports. <strong>In the editor this includes thumbnails and Material previews</strong>, so be careful! If your render pass does extreme things then it’s recommended to add custom predicates to the array IsActiveThisFrameFunctions, to be selective about where it executes. You can examine the current view for its player-index, camera Actor, or Render-Target, and accordingly decide whether to execute on that view.</p><h4>Setting up an SVE without my library</h4><p>Your SVE’s constructor should take a const FAutoRegister&amp;, an empty type that only exists as a label, followed by any custom arguments you want to pass to it on initialization. Then you must create it by calling</p><pre>//On the game thread:<br>TSharedPtr&lt;FMySVE, ESPMode::ThreadSafe&gt; mySVE =<br>    FSceneViewExtensions::NewExtension&lt;FMySVE&gt;(constructorArg2, constructorArg3, …)</pre><p>The easiest way to manage its lifetime is through a World Subsystem (Unreal’s solution for per-world singletons), creating your extension at the start of the world and owning the shared pointer so that the SVE automatically unregisters and destructs when the subsystem is destroyed.</p><p>With this setup your subsystem should manage all the data related to rendering, including game-thread UPROPERTY’s that upload themselves to the render-thread on Tick, while the SVE simply pulls that render-thread data as needed.</p><p><strong><em>Warning: </em></strong><em>If your SVE is destroyed when your subsystem is destroyed, be wary of race conditions from the SVE accessing subsystem parameters! My library adds a GPU fence to subsystem destruction which hangs until all pass objects and SVE’s have cleaned themselves up.</em></p><p>SVE’s actually live at global/engine scope, so if you go with the above method you also need to add new conditions to the inherited field IsActiveThisFrameFunctions to only be active within its owning World. You can add any other conditions you want to that field, such as only enabling at run-time or never enabling for little thumbnail preview editor worlds.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f37f4d4407d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Graphics Programming in Unreal, part 2]]></title>
            <link>https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-2-abf8237491c1?source=rss-384faa1a8ea4------2</link>
            <guid isPermaLink="false">https://medium.com/p/abf8237491c1</guid>
            <category><![CDATA[unreal-engine-5]]></category>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[technical-art]]></category>
            <category><![CDATA[graphics-programming]]></category>
            <dc:creator><![CDATA[William Mishra-Manning]]></dc:creator>
            <pubDate>Tue, 24 Jun 2025 17:07:41 GMT</pubDate>
            <atom:updated>2025-08-01T21:08:47.983Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a seven-part article series.</p><p>Part 1: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-1-10488f2e17dd">Introduction</a><br><strong>Part 2: Rendering Abstractions (RHI, RDG) and Threading</strong><br>Part 3:<a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-3-f37f4d4407d7"> Scenes. Views, and SceneViewExtension</a><br>Part 4: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-4-c89d6fb98b59">Global Shaders</a><br>Part 5: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-5-ea988fd1034e">Simple Material Shaders</a><br>Part 6: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-6-5477dbb64608">Advanced Material Shaders</a><br>Part 7: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-7-d3500d4b8195">Mesh-Material Shaders and Mesh Passes</a></p><h3>Threading, and Rendering Abstractions</h3><p>When doing graphics programming in Unreal, it helps to know how the different rendering abstractions are layered on top of each other. For example, what are RHI command lists and how do they relate to RDG instances? Aren’t they a bit redundant? What threads can you use an RHI command list on? And what’s with the “immediate” command lists?</p><p>I’ll go over the core abstraction layers at a high level so we won’t feel disoriented when dealing with them later. You may also reference <a href="https://dev.epicgames.com/documentation/en-us/unreal-engine/render-dependency-graph-in-unreal-engine">the official Unreal docs</a> for more details on the RDG layer.</p><p>I will also go over the multithreading design patterns in Unreal’s renderer. <a href="https://dev.epicgames.com/documentation/en-us/unreal-engine/threaded-rendering-in-unreal-engine">The official docs</a> have more details for you, but I have attempted to boil this down as much as possible to what’s essential.</p><h3>Theory</h3><h4>Threading</h4><p>Unreal rendering is highly threaded. Top-level render logic happens synchronously, on the special “Render Thread” (or “RT” for short). This is usually the only thread you’ll directly interact with. Intermediary work gets distributed among worker threads, and then the raw graphics API calls are executed on a special “RHI thread” which may actually be multiple threads if Unreal is using a modern API like Vulkan.</p><p>When debugging graphics stuff, the secondary threads can all be disabled through config files so that everything is synchronous on the Render Thread. See the first article in this series for how to modify config files for graphics debugging.</p><p>You can queue up code to run on the RT, from <em>anywhere </em>(including the RT itself), by calling:</p><pre>ENQUEUE_RENDER_COMMAND(MyCommandsNameForDebugging)(myLambda)</pre><p>The lambda takes one argument, of type FRHICommandList (more on that later).</p><p>It’s very important for your lambda to capture most of its data by copy, because there can be frames of lag between when a command is queued up and when it executes. Any local variables it captured are certainly cleaned up and gone by the time it runs! Even the owning UObject may have been garbage-collected before the command executes (ways to prevent this are explained below).</p><p>While you can set up draw calls and compute shaders to run from ENQUEUE_RENDER_COMMAND, they could only operate on off-screen data so it’s more commonly used to just pass data into the Render Thread.</p><p><em>In practice most rendering work will be within Scene View Extensions, covered in the next article.</em></p><h4>Proxies</h4><p>Multithreading bugs are a nightmare, so great pains are taken to separate game-thread logic (like AActor, UActorComponent, and UWorld) from render-thread logic. You must understand and follow these conventions in your own graphics code.</p><p>Every object that participates in rendering (mesh, material, component, world, etc) has a corresponding <em>proxy</em> struct that is not UObject, not garbage-collected, and contains very simple data. In fact it’s usually completely disconnected from its owning UObject. The render thread should only concern itself with proxies and not the original objects, to prevent race conditions — especially in case the original UObject gets destroyed! Any object that has a presence in the Render Thread will usually do the following:</p><ol><li>Store its proxy as a private field</li><li>Offer a public getter for the proxy that checks IsInRenderThread()</li><li>Periodically update the proxy with ENQUEUE_RENDER_COMMAND()</li><li>Set up an FRenderCommandFence when dying to ensure the proxy never gets used after death (see below for more details).</li></ol><p><em>Many proxies keep a </em>Debug <em>pointer to their owning game object for convenience.</em></p><p>It’s important to understand what purpose a C++ lambda serves in ENQUEUE_RENDER_COMMAND(). Your new proxy data should be captured and owned by the lambda, safely carrying it outside the lifetime of the calling function and into the rendering thread a frame or two in the future. Then during execution of the lambda, that captured copy can be moved into a more persistent render-thread-only variable which usually belongs to the UObject or its proxy.</p><p><strong><em>A note about performance</em></strong><em>: in the above workflow, proxy data is copied several times per shift to the Render-Thread. If it has a heap-allocated collection like </em>TArray<em>, then use </em>MoveTemp()<em> to avoid copies and ideally use </em><a href="https://www.unrealengine.com/en-US/blog/optimizing-tarray-usage-for-performance"><em>an inline allocator</em></a><em> to avoid heap usage altogether.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*AtH539vVXsC7CNaZTnWKtQ.png" /><figcaption>Diagram of a UObject’s render logic. The Destroy logic is explained below; ‘stopCommands’ is a stand-in for some kind of signal to your rendering code.</figcaption></figure><p>While it’s generally not safe to access a UObject from other threads without extra work you <em>can</em> always use its pointer, for example as a lookup key. After all, pointers are just integers with a fancy coat of paint (don’t tell a C++ expert I said that).</p><h4>UObjects on the Render Thread</h4><p>In practice you do often need to dereference certain UObjects on the Render Thread, for example any object that holds its own proxy. In those cases you need to make sure the UObject doesn’t get cleaned up by the GC (or killed, if it’s an actor/component) until the Render Thread knows to stop referencing it. <a href="https://georgy.dev/posts/avoid-gc-async/">Here is an external article about multithreaded cleanup</a>.</p><p>It’s recommended to use an FRenderCommandFence, for the Render Thread to acknowledge that the object is dying and then for the Game Thread to wait for that acknowledgement before finishing destruction. Refer to my UObject diagram above. In fact this is exactly why objects have separate BeginDestroy() and FinishDestroy() events with a bit of lag between them — start the fence on Begin and wait for the fence on Destroy.</p><p><em>If you’re thinking of using simple mutex locks, please don’t! It ruins the whole point of a multithreaded architecture, by forcing it to act single-threaded. The only acceptable uses for locking the render/game thread are in the editor or for special </em><strong><em>infrequent</em></strong><em> operations.</em></p><h4>Code Organization</h4><p>Outside of normal game logic, functions and variables should make it extremely clear when they’re meant to be called on a specific thread. If the function is for the render thread, suffix it with _RenderThread and add check(IsInRenderingThread()) on the first line. Similarly, for the game thread use _GameThread and check(IsInGameThread()). It’s not uncommon to have two versions of a variable or function, with each prefix.</p><p>Unfortunately not all rendering functions follow this convention, and you’ll have to check their documentation or source before calling them. It might be implicit based on their arguments, for example if they take an FRHICommandList or FRDGBuilder then they’re almost certainly meant for the render thread.</p><h3>Rendering Abstractions</h3><h4>RHI</h4><p>The term “RHI” stands for “Render Hardware Interface” and covers a specific graphics API such as DirectX12 or Vulkan. Each RHI also has a reported “feature level” indicating what broad capabilities it has. As of Unreal 5.3 the only meaningful feature levels are SM5 for older hardware, SM6 for newer hardware, and ES3_1 for mobile hardware.</p><p>You can think of low-level graphics calls as being split into three layers. From lowest to highest:</p><ul><li>RHI global function calls</li><li>RHI Command Lists</li><li>Render Dependency Graphs</li></ul><h4>Global RHI functions</h4><p><strong><em>TL;DR: </em></strong><em>In practice there is very little need to use this layer directly, except for a handful of commands and possibly for debugging/prototyping. Instead, to work at the RHI level you should use the next layer of abstraction: command-lists.</em></p><p>The lowest level of graphics programming in Unreal is to make your own draw/compute calls on the Render Thread, using the global functions found at the bottom of <em>/Engine/Source/Runtime/RHI/Public/RHICommandList.h</em>. For example, you can create a bare-bones texture object with RHICreateTexture(…).</p><p>One other global RHI function that I have actually used is RHICreateSamplerState, which makes a reference-counted handle to a sampler object. Higher abstractions don’t seem to have functions for creating/destroying these (except using compile-time-constant parameters), so my impression is that they are not expensive to create.</p><h4>RHI Command Lists</h4><p><strong><em>TL;DR: </em></strong><em>This is preferred to the previous layer (global function calls), and also gets used within RDG event callbacks. At worst their performance will be about the same as the global functions, and at best they will be better.</em></p><p>An FRHICommandList is a queue of draw calls and other state changes which will be executed asynchronously (meaning, at some point in the future within a frame or two). If your platform uses a multi-threaded rendering API like DirectX12 or Vulkan, those command-lists will be executed on multiple worker threads to minimize graphics driver overhead.</p><p>Along with the command list’s member functions there are quite a few global functions offered by Unreal to accomplish common tasks. For example, DrawClearQuad() sets up a draw call with an internal fragment shader that clears the current render target for you. You can also look inside the implementation of RDG global functions (see below) for examples of how to use command lists.</p><p>Usually you won’t create command-lists yourself (though it’s not hard, see the <strong>Details </strong>section), because they’re given to you by various rendering hooks. They are decentralized objects, with no singleton manager and no standard lifetime, however you can only execute them once each so they tend to live inside one frame.</p><p>If you’re already in the render thread then you can also grab a special singleton command list, of the child type FRHICommandListImmediate, which immediately executes each command rather than queueing them up. This type of command-list is also what you receive in your lambdas for ENQUEUE_RENDER_COMMAND(), presumably only for convenience since it’s already a singleton.</p><h4>Render Dependency Graph (RDG)</h4><p><strong><em>TL;DR: </em></strong><em>This is the layer you want to use, but within each RDG pass you will be given an RHI command list to work with.</em></p><p>An RDG (of the type FRDGBuilder) is a command-list on steroids. Each instance handles the allocation and destruction of temporary GPU resources <em>and</em> C++ objects, while executing the commands you give to it. They also optimize your graphics commands in numerous ways, such as pooling memory allocations, reordering draw calls, and pruning unused commands. An entire Unreal frame is built with a small number of RDG instances. Every RDG must run in the render-thread (because it runs on an immediate-mode command list), so either create and execute your own graph inside ENQUEUE_RENDER_COMMAND, or use the one that’s given to you in various render-thread callbacks covered in the next article.</p><p><strong>The first half</strong> of RDG’s existence is resource management. Any C++ objects you allocate with the functions graph.Alloc[X]() are guaranteed to live until the graph is done executing. Additionally any GPU resources you create within a graph will actually be created later, during execution, and then cleaned up immediately after they aren’t needed anymore. The handle to these resources is a special RDG stub, which can be unwrapped into a proper RHI handle <em>only during execution</em>.</p><p>You can register existing RHI resources with the graph, called “external” resources, by calling graph.RegisterExternal[X](…). This works even if the resource has already been registered with this graph by somebody else (despite engine code hinting otherwise).</p><p>On the other hand you can extract a temporary RDG resource into a permanent one with graph.Queue[X]Extraction(…).</p><p><strong>The second half</strong> of RDG is the ability to queue up GPU commands. All graphics operations in the graph are organized into <em>passes</em>. The simplest function you can call is graph.AddPass(...) which sets up render targets, issues resource memory barriers, and executes your own render-thread lambda. In order to know which resources your pass will use, AddPass() also takes a <em>shader parameter struct</em> (later articles will explain shaders) and assumes you use all of the RDG resources named in that struct. Listed below are all the ways you can extend a shader parameter struct to work with the RDG, though this might be confusing until you’ve written some Unreal shaders:</p><ul><li>Add the macro RENDER_TARGET_BINDING_SLOTS() to your parameter struct to give it a new field named RenderTargets. RDG will ensure that the settings you configure in this field (depth buffer, color buffers, etc) are bound right before your pass lambda is executed.</li><li>Replace the usual RHI texture and buffer parameters like SHADER_PARAMETER_TEXTURE(…), with their RDG equivalents like SHADER_PARAMETER_RDG_TEXTURE(…), to make RDG aware of the inputs and outputs of your pass. It’s especially important for mutable resources to be seen by the RDG, in order to schedule those passes in the correct order.</li></ul><p>There are many global functions provided by Unreal that perform common RDG tasks for you, usually named Add[X]Pass(…). For example AddCopyTexturePass(…), AddClearRenderTargetPass(…), AddSimpleMeshPass(…).</p><h3>Demo</h3><p>To illustrate use of some RHI commands, queued up from the game thread to the render thread, we will add a small demo Actor which manages a render target. That render target will be randomly cleared every so often to a new color.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FEISgGxTNsR4%3Ffeature%3Doembed%26autoplay%3D1&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEISgGxTNsR4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FEISgGxTNsR4%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/48981b46e5b9e5431844ac45aaf12822/href">https://medium.com/media/48981b46e5b9e5431844ac45aaf12822/href</a></iframe><p>Here is our actor’s declaration (not including the Blueprint to display the texture on a plane):</p><pre>#include “CoreMinimal.h”<br><br>UCLASS(BlueprintType)<br>class GOL_DEMO_API A_GOL_TestRHI : public AActor<br>{<br>    GENERATED_BODY()<br>public:<br>    <br>    UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient)<br>    UTextureRenderTarget2D* TestOutput = nullptr;<br>    <br>    A_GOL_TestRHI() { PrimaryActorTick.bCanEverTick = true; }<br>    <br>    virtual void BeginPlay() override;<br>    virtual void Tick(float deltaSeconds) override;<br>};</pre><p>And here is the definition:</p><pre>#include &quot;ClearQuad.h&quot;<br>#include &quot;Kismet/KismetRenderingLibrary.h&quot;<br><br>void A_GOL_TestRHI::BeginPlay()<br>{<br>    Super::BeginPlay();<br><br>    const int Resolution = 16;<br>    TestOutput = NewObject&lt;UTextureRenderTarget2D&gt;(this);<br>    TestOutput-&gt;ClearColor = FLinearColor::Transparent;<br>    TestOutput-&gt;InitCustomFormat(Resolution, Resolution,<br>                                 PF_R8G8B8A8, true);<br>}<br>void A_GOL_TestRHI::Tick(float deltaSeconds)<br>{<br>    Super::Tick(deltaSeconds);<br><br>    auto* resource = TestOutput-&gt;GetResource();<br>    auto* rhi = (resource == nullptr) ? nullptr : resource-&gt;GetTexture2DRHI();<br>    <br>    auto randF = []{ return FMath::FRandRange(0.0f, 1.0f); };<br>    if (rhi &amp;&amp; randF() &lt; 0.09f)    <br>    {<br>       FLinearColor clearColor{ randF(), randF(), randF(), 1 };<br><br>       ENQUEUE_RENDER_COMMAND(RandomizedClear)([rhi, clearColor](FRHICommandListImmediate&amp; cmds) {<br>          //NOTE: Clearing textures is a lot easier to do with RDG;<br>          //    this is just an illustrative example of RHI.<br>          <br>          //Start using the texture as a render target.<br>          cmds.Transition(FRHITransitionInfo{ rhi, ERHIAccess::Unknown, ERHIAccess::RTV });<br>          cmds.BeginRenderPass(FRHIRenderPassInfo{ rhi, ERenderTargetActions::DontLoad_Store },<br>                               TEXT(&quot;RandomizedClear&quot;));<br><br>          //Clear it to the random color.<br>          DrawClearQuad(<br>             cmds, true, clearColor,<br>             //No depth/stencil.<br>             false, 0, false, 0<br>          );<br><br>          //Clean up.<br>          cmds.EndRenderPass();<br>          cmds.Transition(FRHITransitionInfo{ rhi, ERHIAccess::RTV, ERHIAccess::SRVMask });<br>       });<br>    }<br>}</pre><h3>Code</h3><p>The demo RHI actor is added to the repo in the <em>part/2</em> branch.</p><p><a href="https://github.com/heyx3/UnrealExtendedGraphicsProgrammingDemo/tree/part/2">heyx3/UnrealExtendedGraphicsProgrammingDemo at part/2</a></p><h3>Details</h3><p>While RDG’s AddPass()<em> </em>takes a shader parameter struct, it does not upload that struct to the shader for you. That’s because AddPass() calls aren’t tied to any particular shader — it doesn’t know where to send them. However most of the global RDG helper functions take shaders, such as AddDrawScreenPass(), and they will also upload your parameter struct for you. The basic details of parameter uploading are covered in the fourth article.</p><p>Under the hood, global RHI functions will call virtual member functions on the abstract classes FDynamicRHI and IRHICommandContext. These contain the actual calls to Vulkan, DirectX, etc. On simple platforms (no multithreaded rendering) one class will inherit from both types; on more cutting-edge platforms the context is a separate object and not a singleton.</p><p>The standard command-list type is FRHICommandList, but there is a compute-only subset called FRHIComputeCommandList.</p><p>Anybody can construct command lists, queue up commands (synchronously, no multithreading within a single command-list), then dispatch it with FinishRecording(). After FinishRecording() you should not touch the object anymore. If you fail to call FinishRecording(), an internal assert will trip in the destructor to tell you about your bug.</p><p>Ostensibly you can create/use a command-list on any thread, especially given the existence of the helper struct FRHIAsyncCommandList, however Unreal crashed when I tried to use a command-list from the game thread. Maybe it’s a bug with DrawClearQuad(), or maybe Epic gave up on async command lists?</p><p>RDG’s, like command-lists, can be created and used manually on the render-thread. Construct one with an immediate-command-list, for example</p><pre>FRDGBuilder graph{ FRHICommandListImmediate::Get() };</pre><p>then queue up passes with it and call graph.Execute() to finish. In practice you won’t need to do this often; more individual RDG’s means less opportunity for pooling resources anyway!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abf8237491c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Graphics Programming in Unreal, part 1]]></title>
            <link>https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-1-10488f2e17dd?source=rss-384faa1a8ea4------2</link>
            <guid isPermaLink="false">https://medium.com/p/10488f2e17dd</guid>
            <category><![CDATA[graphics-programming]]></category>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[technical-art]]></category>
            <category><![CDATA[unreal-engine-5]]></category>
            <dc:creator><![CDATA[William Mishra-Manning]]></dc:creator>
            <pubDate>Tue, 24 Jun 2025 17:05:58 GMT</pubDate>
            <atom:updated>2025-07-01T17:08:56.752Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a seven-part article series.</p><p><strong>Part 1: Introduction</strong><br>Part 2: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-2-abf8237491c1">Rendering Abstractions (RHI, RDG) and Threading</a><br>Part 3: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-3-f37f4d4407d7">Scenes. Views, and SceneViewExtension</a><br>Part 4: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-4-c89d6fb98b59">Global Shaders</a><br>Part 5: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-5-ea988fd1034e">Simple Material Shaders</a><br>Part 6: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-6-5477dbb64608">Advanced Material Shaders</a><br>Part 7: <a href="https://medium.com/@manning.w27/advanced-graphics-programming-in-unreal-part-7-d3500d4b8195">Mesh-Material Shaders and Mesh Passes</a></p><h3>Empower Tech Artists with custom Material graphs and mesh passes</h3><p>Want to make this in Unreal?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q4XmV7weoy7Q9CLnjoL8bg.png" /><figcaption>A decently-realistic yet real-time Xray renderer, made for work</figcaption></figure><p>Or this?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*_94JPZ1fqHFYp44SSTARlA.png" /><figcaption>An object outline effect, controlled by the object’s own Material using extra outputs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GQnkbOv6uI5FJ1nZ81LMxg.png" /><figcaption>Another object in the same scene, rendering a very differently outline controlled by MaterialInstance</figcaption></figure><p>How about this?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FarunX2eeakk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DarunX2eeakk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FarunX2eeakk%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c75b9a84b1d09cdade5e0c4190c5c0f0/href">https://medium.com/media/c75b9a84b1d09cdade5e0c4190c5c0f0/href</a></iframe><p>These are all possible in Unreal 5.3, without modifying the engine. However you can’t easily do any of them with only Materials and Blueprints; most are complex multi-pass effects, with 3D mesh passes <em>and </em>custom screen passes <em>and </em>off-screen compute shaders. The Outline effect is easier, perhaps doable though BP and existing Materials, but is still clumsy to implement that way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T0mlX1KOcrobDNEI.PNG" /><figcaption>The Hiss, from the game Control, use a very complex effect where particles draw into a screen-space fluid simulation which is reprojected every frame as the camera moves. Can this be done in Unreal without modifying the engine?</figcaption></figure><p>Additionally, to enable fast iteration on the effects by artists, these custom passes are all driven by Materials with new kinds of input and output pins. There are no hard-coded parameters for programmers to feed into the shader by hand!</p><p>Don’t underestimate the power that Material integration gives a graphics programmer. With it you no longer have to make your own judgement calls on how to parameterize an effect for your artists, through HLSL then C++ then Blueprints/Reflection. Instead you can leverage the massive power and user-friendliness of Material graphs to let artists take ownership over those parameters and the logic that relates them. It provides an order-of-magnitude speedup to iterating on complex render effects.</p><p>Unfortunately all this architectural power is hidden under a morass of under-documented C++ code, <em>un</em>documented C++ code, countless interacting structs and classes, tricky threading concerns, and bewildering type names. Nothing I’ve seen on the internet gets further than making a screen-space Global Shader and maybe a Scene-View Extension to invoke it. I suspect the only people that know how to go further are AAA graphics programmers, Epic engineers, and now partially myself. For work and my own personal projects I’ve poured over Unreal rendering samples, plus the few docs they do have, to figure out custom mesh passes and Material integration. What I found is a hugely-customizable render pipeline, but only if you have a small novel’s worth of notes to reference as you work.</p><h3>Outline</h3><p>The goal of this series of articles is to provide three awesome things:</p><ul><li>A re-usable Unreal plugin that greatly simplifies screen-space/compute passes, 3D mesh passes, and Material integration.</li><li>A reference for all the information I’ve uncovered so far, and any questions I still have.</li><li>A demo of these features in action, which we build step by step.</li></ul><p>We are working in unreal 5.3, 5.4, or 5.5, and I assume you have the following knowledge already:</p><ul><li><strong>C++</strong>. Most of this code doesn’t interact with game logic or UObjects; it’s pure modern C++ within an enormous C++ environment. In particular you should understand move-semantics, lambdas, and lambda capturing, because they’re all vital tools for the next topic…</li><li><strong>Multithreading</strong>. Unreal uses numerous threads within its renderer, and you should be comfortable with multithreaded thinking. I <em>will</em> explain Unreal-specific concepts, conventions and design patterns. There is also a <a href="https://dev.epicgames.com/documentation/en-us/unreal-engine/threaded-rendering-in-unreal-engine">good official page on this topic</a>.</li><li><strong>Graphics Programming</strong>. Nothing Unreal specific! Just HLSL, the anatomy of a draw call, and the general nature/lifetime of graphics objects.</li><li><strong>Basic Unreal skills</strong>. I won’t waste time explaining the blueprints involved in making the demo, however the released project will contain it all if you don’t want to build it from scratch.</li></ul><p>Each article will be split into four sections:</p><ol><li><strong>Theory</strong>. A straightforward explanation of the topic.</li><li><strong>Demo</strong>. Applying the topic to a custom effect we build throughout the series.</li><li><strong>Code</strong>. A GitHub repo containing the demo code.</li><li><strong>Details</strong>. All the precise implementation details I’ve found and any outstanding questions I have.</li></ol><h3>Demo</h3><p>This is the final effect we are aiming for:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FpO8ziOCuwk0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpO8ziOCuwk0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FpO8ziOCuwk0%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/47f2d49b18355c98932fc24447d05d00/href">https://medium.com/media/47f2d49b18355c98932fc24447d05d00/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F3viEv-rT8s8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D3viEv-rT8s8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F3viEv-rT8s8%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fb60ca020dc02ec4c03a11b589b41e0/href">https://medium.com/media/0fb60ca020dc02ec4c03a11b589b41e0/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fas4XAPthJBM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Das4XAPthJBM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fas4XAPthJBM%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fa4884aef19430942ef018932b0efb5/href">https://medium.com/media/2fa4884aef19430942ef018932b0efb5/href</a></iframe><p>As you may notice, it’s a screen-space Game of Life — a very popular Cellular Automata simulation you can read about elsewhere — which is affected by meshes in the scene. I chose the Game of Life because it’s very simple to implement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*d97oT0wtv6hQATCJ.gif" /><figcaption>A plain example of the Game of Life, courtesy of Wikipedia</figcaption></figure><p>This effect requires four different passes: <em>Initialize </em>to set the initial state, a 3D <em>Mesh</em> pass to let meshes/primitives draw into the sim, a <em>Simulate</em> compute shader to update the sim, and a <em>Display </em>pixel shader to apply the sim to the screen. In the end, all 4 of them will be controlled by Materials. There will also be a small <em>Resample</em> shader to run whenever the player’s resolution changes (which actually happens very often in the editor, or when playing with quality settings).</p><p>The mesh pass will be controlled by each object’s own Material, while the screen passes are all controlled by one global Material. To give you an idea of where we are going, here is a preview of the final Material graph which drives the screen-space shaders for this effect. It has three different sub-graphs, one for each shader (Initialize, Simulate, Display), and offers many parameters which make it easy to iterate on it or to shift the behavior dynamically at runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5NLn6ZZZEqPJ0fsaA66BzQ.png" /><figcaption>The Game of Life effect’s main 3 shaders are driven by this material.</figcaption></figure><p>Here are some of the materials of objects participating in the mesh pass:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IbZoiZzoLE2Q7EeyXpyISA.png" /><figcaption>The rigged mesh has three segments, masked by vertex color. The head is masked with Blue, and drawn with a fresnel effect. The head also draws into the sim using that fresnel effect.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*5N89rz9qmdHrvccL4K3a5w.png" /><figcaption>The niagara particles draw into the sim with multiply blending (configured elsewhere), and either kill or revive cells based on which side of them is visible.</figcaption></figure><p>I will name this demo project “GoL” for “Game of Life”. So, let’s get a project set up for graphics programming!</p><h4>Setup</h4><p>Start with an empty Unreal C++ project. Drop in <a href="https://github.com/heyx3/ExtendedGraphicsProgramming">my reusable ExtendedGraphicsProgramming plugin</a>. Create your own new plugin (in the editor go to <em>Edit</em>&gt;<em>Plugins</em>, click the <em>+Add</em> button, and choose Blank Plugin) to hold the demo’s shaders and graphics code.</p><p>This plugin will need at least one module, of Type <em>Runtime</em> and LoadingPhase <em>PostConfigInit (</em>shaders must load in the <em>PostConfigInit</em> phase). The module will have some extra private dependencies on the engine modules <em>Projects</em>, <em>RenderCore</em>, <em>Renderer</em>, <em>RHICore</em>, and <em>RHI</em>.</p><p>The plugin should also contain at least one folder to hold your shaders, conventionally named <em>Shaders </em>and placed alongside <em>Source</em>. More complex plugins may want to separate them into <em>Shaders/Public</em> and <em>Shaders/Private</em>.</p><p>Finally we need to tell Unreal about our <em>Shaders</em> folder, by assigning it a virtual path that can be referenced in other shaders (and by Material graphs, in their Custom nodes). In your module’s startup code, call</p><pre>AddShaderSourceDirectoryMapping(virtualFolderPath, actualFolderPath)</pre><p>For example:</p><pre>AddShaderSourceDirectoryMapping(&quot;/MyShaders&quot;, &quot;C:/Users/manni/Documents/MyGame/Plugins/MyPlugin/Shaders&quot;)</pre><p>Obviously it’s not a great idea to use hard-coded paths, so instead we will ask Unreal for the local path to the plugin:</p><pre>#include “Interfaces/IPluginManager.h”<br>...<br>auto myPlugin = IPluginManager::Get().FindPlugin(<br>    TEXT(&quot;MyPlugin&quot;) //Your plugin’s name here<br>);<br>auto myShadersDir = FPaths::Combine(<br>    myPlugin-&gt;GetBaseDir(),<br>    TEXT(&quot;Shaders&quot;) //Relative to the plugin’s root folder<br>);<br>AddShaderSourceDirectoryMapping(&quot;/MyShaders&quot;, myShadersDir);</pre><p>Now Unreal will know about your folder when compiling shaders! You can add sub-folders, headers (.ush files), and actual shaders (.usf files) to that folder and reference them in other places using your virtual path. For example:</p><pre>#include &quot;/MyShaders/myHeader.ush&quot;</pre><h4>Debugging</h4><p>I highly recommend building the engine locally and targeting Debug Editor (not just DebugGame Editor). As you experiment you will probably cause crashes deep within the engine, and it really helps to be able to step through every layer of abstraction.</p><p>You should also prepare Unreal for graphics debugging by going into the engine’s <em>Config/ConsoleVariables.ini</em> file and enabling most of the graphics-related debug flags that you can find commented out there:</p><ul><li><em>r.ShaderDevelopmentMode=1</em></li><li><em>r.ShaderCompiler.EmitWarningsOnLoad=1 : </em>Unfortunately, this will spam <strong><em>tons</em></strong> of warnings for built-in shaders, so maybe just skip it.</li><li><em>r.RHICmdBypass=1</em> : This turns off low-level threading in the renderer for easier step-through debugging and tracing of crashes. To completely turn off threaded rendering, enable the next command as well. However it must be turned off at some point to test that your code is thread-safe! The next article will explain where exactly “RHI” fits in the rendering architecture.</li><li><em>r.RDG.ImmediateMode=1</em> : This turns off high-level threading in the renderer for easier step-through debugging and tracing of crashes. To completely turn off threaded rendering, enable the previous command as well. However it must be turned off at some point to test that your code is thread-safe! The next article will explain where exactly “RDG” fits in the rendering architecture.</li><li><em>r.RDG.Debug=1 </em>: This enables valuable render pipeline checks that would normally be skipped for performance.</li></ul><p>I also highly recommend getting <a href="https://renderdoc.org/">RenderDoc</a> and enabling its Unreal plugin for the project (already built into the engine). This lets you do awesome low-level debugging, like stepping through shaders. If you use this, then you should enable the following commands to make debugging in RenderDoc far easier:</p><ul><li><em>r.Shaders.Optimize=0</em></li><li><em>r.Shaders.Symbols=1</em></li><li><em>r.Shaders.ExtraData=1</em></li><li><em>r.Shaders.SkipCompression=1</em></li></ul><p>Finally, know how to switch between graphics API’s (which Unreal calls “RHI”s) in the project settings. In my experience each API reacts totally differently to the bugs I introduce, so I have to switch between them frequently to find one that allows me to start debugging. DX12 likes to throw a generic “failed to create GraphicsPipeline” error (in my experience it usually means vertex outputs didn’t match fragment inputs), or hang forever on a particular framebuffer function. Vulkan can crash in an opaque and confusing location deep in its RHI thread. DX11 tries really hard to paper over the problems in your code.</p><p>To change the default RHI, go into the project settings and just search for “RHI”. By default it’s set to “Default” but you can pick a specific one and then restart the editor. To see the current RHI in use, execute the console command r.RHI.Name and read the output in the console.</p><h4>Test Scene</h4><p>Create a scene with several different kinds of materials and primitives. My scene has the following variety of objects that will all participate in the effect:</p><ol><li>Static meshes with an animated material</li><li>Static meshes with multiple materials, and multiple LOD’s. The LOD’s are deliberately aggressive and ugly, to make it obvious which level is visible.</li><li>Niagara particles</li><li>Rigged “skeletal” meshes, animated procedurally with this snippet:</li></ol><pre>boneRot = rotMax * perlin(elapsedTime*C + uniqueId*D)</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FKZLvBOGGPhY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKZLvBOGGPhY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FKZLvBOGGPhY%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5395f874dc42e3692b384f967353a2f6/href">https://medium.com/media/5395f874dc42e3692b384f967353a2f6/href</a></iframe><p>Each of these will participate in the effect in its own way, demonstrating that our code works with virtually any type of Primitive Component.</p><h3>Code</h3><p>Part 1 of the demo can be found in the below repo, in the branch <em>part/1</em>. It holds my “Extended Graphics Programming” plugin as a git submodule.</p><p><a href="https://github.com/heyx3/UnrealExtendedGraphicsProgrammingDemo/tree/part/1">GitHub - heyx3/UnrealExtendedGraphicsProgrammingDemo: Demo code for the Extended Graphics Programming unreal plugin (also on github)</a></p><h3>Details</h3><p>No extra info for this first article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10488f2e17dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>