[UE5.1]Customノードが安定してきたので色々試した。

いろんな意味で成功はしなかったが、かなり成長した。

まず、こちらのサイトで

ここのサイトが唯一.ushファイルのincludeをうまくやっている。
// Copyright Epic Games, Inc. All Rights Reserved.

#include "KA_MatCustomNode.h"
#include "Modules/ModuleManager.h"

IMPLEMENT_PRIMARY_GAME_MODULE(FKA_MatCustomNode, KA_MatCustomNode, "KA_MatCustomNode" );

void FKA_MatCustomNode::StartupModule()
{
    FString ShaderDirectory = FPaths::Combine(FPaths::ProjectDir(), TEXT("Shader"));
    if (!AllShaderSourceDirectoryMappings().Contains("/Project"))
    {
        AddShaderSourceDirectoryMapping("/Project", ShaderDirectory);
    }
    FString EngineDirectory = FPaths::Combine(FPaths::EngineDir(), TEXT("Engine"));
    if (!AllShaderSourceDirectoryMappings().Contains("/Engine"))
    {
        AddShaderSourceDirectoryMapping("/Engine", EngineDirectory);
    }
}

void FKA_MatCustomNode::ShutdownModule()
{
}

/Project/ というパスを入力することでプロジェクトフォルダの/Shader/へのパスからインクルードできるようにしていたので

よくあるインクルードコードで

/Engine/というパスを入力する事で/Engine/のShaderをインクルードできるようにしてみた。↑のソースコード

ただ.ushからのインクルードは機能しないっぽい

別の話だが

https://zhuanlan.zhihu.com/p/100834351

で紹介されているコードは実際には動かなかったが動くようにした。

#pragma once
#include "CoreMinimal.h"
#include "HAL/IConsoleManager.h"
#include "RHI.h"
#include "ShaderParameters.h"
#include "Shader.h"
#include "HitProxies.h"
#include "RHIStaticStates.h"
#include "SceneManagement.h"
#include "Materials/Material.h"
#include "PostProcess/SceneRenderTargets.h"
#include "DBufferTextures.h"
#include "LightMapRendering.h"
#include "VelocityRendering.h"
#include "MeshMaterialShaderType.h"
#include "MeshMaterialShader.h"
#include "ShaderBaseClasses.h"
#include "FogRendering.h"
#include "TranslucentLighting.h"
#include "PlanarReflectionRendering.h"
#include "UnrealEngine.h"
#include "ReflectionEnvironment.h"
#include "Strata/Strata.h"
#include "OIT/OITParameters.h"
#include "VirtualShadowMaps/VirtualShadowMapArray.h"
#include "VolumetricCloudRendering.h"
#include "Nanite/NaniteMaterials.h"

/**
 * Scene renderer that implements a deferred shading pipeline and associated features.
 */
class FDeferredShadingSceneRenderer : public FSceneRenderer
{
public:

	void RenderMyMeshPass(FRHICommandListImmediate& RHICmdList, const TArrayView<const FViewInfo*> PassViews);
	EDepthDrawingMode EarlyZPassMode;

}

#include "RHICommandList.h"
#include "Shader.h"
#include "RHIStaticStates.h"


#include "MyGS.h"
//My VertexShader
class FMyGS_VS : public FGlobalShader
{
	DECLARE_SHADER_TYPE(FMyGS_VS, Global);

public:

	FMyGS_VS() {}
	FMyGS_VS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
		: FGlobalShader(Initializer)
	{

	}

	static void ModifyCompilationEnvironment(const FGlobalShaderPermutationParameters& Parameters, FShaderCompilerEnvironment& OutEnvironment)
	{

	}

	static bool ShouldCompilePermutation(const FGlobalShaderPermutationParameters& Parameters)
	{
		return IsFeatureLevelSupported(Parameters.Platform, ERHIFeatureLevel::SM5);
	}

	static bool ShouldCache(EShaderPlatform Platform)
	{
		return true;
	}

	virtual bool Serialize(FArchive& Ar) override
	{
		bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
		//Ar << ;
		return bShaderHasOutdatedParameters;
	}
	void SetParameters(FRHICommandList& RHICmdList, const FViewInfo& View)
	{
		FGlobalShader::SetParameters<FViewUniformShaderParameters>(RHICmdList, GetVertexShader(), View.ViewUniformBuffer);
	}
};

IMPLEMENT_SHADER_TYPE(, FMyGS_VS, TEXT("/Engine/Private/MyGS/MyGS.usf"), TEXT("MainVS"), SF_Vertex);


//My PixleShader
class FMyGS_PS : public FGlobalShader
{
	DECLARE_SHADER_TYPE(FMyGS_PS, Global);

public:

	FMyGS_PS() {}
	FMyGS_PS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
		: FGlobalShader(Initializer)
	{

	}

	static void ModifyCompilationEnvironment(const FGlobalShaderPermutationParameters& Parameters, FShaderCompilerEnvironment& OutEnvironment)
	{

	}

	static bool ShouldCompilePermutation(const FGlobalShaderPermutationParameters& Parameters)
	{
		return IsFeatureLevelSupported(Parameters.Platform, ERHIFeatureLevel::SM5);
	}

	static bool ShouldCache(EShaderPlatform Platform)
	{
		return true;
	}

	virtual bool Serialize(FArchive& Ar) override
	{
		bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
		//Ar << ;
		return bShaderHasOutdatedParameters;
	}
	void SetParameters(FRHICommandList& RHICmdList, const FViewInfo& View)
	{
		FGlobalShader::SetParameters<FViewUniformShaderParameters>(RHICmdList, GetVertexShader(), View.ViewUniformBuffer);
	}
};

IMPLEMENT_SHADER_TYPE(, FMyGS_PS, TEXT("/Engine/Private/MyGS/MyGS.usf"), TEXT("MainPS"), SF_Pixel);

//My Geomertry shader
class FMyGS_GS : public FGlobalShader
{
	DECLARE_SHADER_TYPE(FMyGS_GS, Global);

public:

	FMyGS_GS() {}
	FMyGS_GS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
		: FGlobalShader(Initializer)
	{

	}

	static void ModifyCompilationEnvironment(const FGlobalShaderPermutationParameters& Parameters, FShaderCompilerEnvironment& OutEnvironment)
	{

	}

	static bool ShouldCompilePermutation(const FGlobalShaderPermutationParameters& Parameters)
	{
		return IsFeatureLevelSupported(Parameters.Platform, ERHIFeatureLevel::SM5);
	}

	static bool ShouldCache(EShaderPlatform Platform)
	{
		return true;
	}

	virtual bool Serialize(FArchive& Ar) override
	{
		bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
		//Ar << ;
		return bShaderHasOutdatedParameters;
	}

	void SetParameters(FRHICommandList& RHICmdList, const FViewInfo& View)
	{
		FGlobalShader::SetParameters<FViewUniformShaderParameters>(RHICmdList, GetGeometryShader(), View.ViewUniformBuffer);
	}
};

IMPLEMENT_SHADER_TYPE(, FMyGS_GS, TEXT("/Engine/Private/MyGS/MyGS.usf"), TEXT("MainGS"), SF_Geometry);



class FDebugPane
{
public:

	FDebugPane();
	~FDebugPane();
	void FillRawData();
	void EmptyRawData();
	void Init();

	TArray<FVector> VerBuffer;
	TArray<uint16> InBuffer;

	uint32 Stride;

	bool Initialized;

	uint32 VertexCount;
	uint32 PrimitiveCount;

	FVertexBufferRHIRef VertexBufferRHI;
	FIndexBufferRHIRef IndexBufferRHI;

};
FDebugPane DebugMesh;

void FDeferredShadingSceneRenderer::RenderMyMeshPass(FRHICommandListImmediate& RHICmdList, const TArrayView<const FViewInfo*> PassViews)
{
	check(RHICmdList.IsOutsideRenderPass());

	TShaderMap<FGlobalShaderType>* ShaderMap = GetGlobalShaderMap(FeatureLevel);

	FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(RHICmdList);
	SceneContext.BeginRenderingSceneColor(RHICmdList, ESimpleRenderTargetMode::EExistingColorAndDepth, FExclusiveDepthStencil::DepthRead_StencilWrite, true);

	FGraphicsPipelineStateInitializer PSOInit;
	RHICmdList.ApplyCachedRenderTargets(PSOInit);

	PSOInit.RasterizerState = TStaticRasterizerState<FM_Wireframe, CM_None, false, false>::GetRHI();
	PSOInit.BlendState = TStaticBlendState<>::GetRHI();
	PSOInit.DepthStencilState = TStaticDepthStencilState<false, CF_GreaterEqual>::GetRHI();
	PSOInit.PrimitiveType = EPrimitiveType::PT_TriangleList;
	PSOInit.BoundShaderState.VertexDeclarationRHI = GetVertexDeclarationFVector3();

	TShaderMapRef<FMyGS_VS> Vs(ShaderMap);
	TShaderMapRef<FMyGS_PS> Ps(ShaderMap);
	TShaderMapRef<FMyGS_GS> Gs(ShaderMap);
	PSOInit.BoundShaderState.VertexShaderRHI = GETSAFERHISHADER_VERTEX(*Vs);
	PSOInit.BoundShaderState.PixelShaderRHI = GETSAFERHISHADER_PIXEL(*Ps);
	PSOInit.BoundShaderState.GeometryShaderRHI = GETSAFERHISHADER_GEOMETRY(*Gs);

	SetGraphicsPipelineState(RHICmdList, PSOInit);

	for (int i = 0; i < PassViews.Num(); ++i)
	{
		const FViewInfo* View = PassViews[i];

		if (DebugMesh.Initialized == false)
		{
			DebugMesh.Init();
		}
		RHICmdList.SetViewport(View->ViewRect.Min.X, View->ViewRect.Min.Y, 0.0f, View->ViewRect.Max.X, View->ViewRect.Max.Y, 1.0f);
		Gs->SetParameters(RHICmdList, *View);
		//Vs->SetParameters(RHICmdList, *View);

		RHICmdList.SetStreamSource(0, DebugMesh.VertexBufferRHI, 0);
		RHICmdList.DrawIndexedPrimitive(DebugMesh.IndexBufferRHI, PT_TriangleList, 0, DebugMesh.VertexCount, 0, DebugMesh.PrimitiveCount, 1);
	}
	SceneContext.FinishRenderingSceneColor(RHICmdList);
}

void FDebugPane::FillRawData()
{
	VerBuffer = {
		FVector(0.0f, 0.0f, 0.0f),
		FVector(100.0f, 0.0f, 0.0f),
		FVector(100.0f, 100.0f, 0.0f),
		FVector(0.0f, 100.0f, 0.0f)
	};

	InBuffer = {
		0, 1, 2,
		0, 2, 3
	};
}

FDebugPane::FDebugPane()
{
	Initialized = false;
}

FDebugPane::~FDebugPane()
{
	VertexBufferRHI.SafeRelease();
	IndexBufferRHI.SafeRelease();
}

void FDebugPane::EmptyRawData()
{
	VerBuffer.Empty();
	InBuffer.Empty();
}

void FDebugPane::Init()
{
	FillRawData();

	VertexCount = static_cast<uint32>(VerBuffer.Num());
	PrimitiveCount = static_cast<uint32>(InBuffer.Num() / 3);

	//GPU Vertex Buffer
	{
		TStaticMeshVertexData<FVector> VertexData(false);
		Stride = VertexData.GetStride();

		VertexData.ResizeBuffer(VerBuffer.Num());

		uint8* Data = VertexData.GetDataPointer();
		const uint8* InData = (const uint8*)&(VerBuffer[0]);
		FMemory::Memcpy(Data, InData, Stride * VerBuffer.Num());

		FResourceArrayInterface* ResourceArray = VertexData.GetResourceArray();
		FRHIResourceCreateInfo CreateInfo(ResourceArray);
		VertexBufferRHI = RHICreateVertexBuffer(ResourceArray->GetResourceDataSize(), BUF_Static, CreateInfo);
	}

	{
		TResourceArray<uint16, INDEXBUFFER_ALIGNMENT> IndexBuffer;
		IndexBuffer.AddUninitialized(InBuffer.Num());
		FMemory::Memcpy(IndexBuffer.GetData(), (void*)(&(InBuffer[0])), InBuffer.Num() * sizeof(uint16));

		// Create index buffer. Fill buffer with initial data upon creation
		FRHIResourceCreateInfo CreateInfo(&IndexBuffer);
		IndexBufferRHI = RHICreateIndexBuffer(sizeof(uint16), IndexBuffer.GetResourceDataSize(), BUF_Static, CreateInfo);
	}

	EmptyRawData();

	Initialized = true;
}

これでコンパイルは通る

また、別の話だが

これを移植しようとして

https://www.shadertoy.com/view/XsfGWN

コンパイルは通せた。

ちゃんと動かない。

const static float4 MyFloat = float4(1.0,0.0,0.0,1.0);

//const float uvScale = 1.0;
const float uvScale = 1.0;
//const float colorUvScale = 0.1;
const float colorUvScale = 1.0;
const float furDepth = 0.2;
const int furLayers = 64;
const float rayStep = 0.00625;
const float furThreshold = 0.4;
const float shininess = 50.0;
float iTime;

Texture2D<float4> Tex0;
Texture2D<float4> Tex1;
sampler Tex0Sampler;
sampler Tex1Sampler;

float2 UV;

//float3 blur = Texture2DSample(Tex0, Tex0Sampler, UV).rgb;

//bool intersectSphere(float3 ro, float3 rd, float r, out float t)
bool intersectSphere(float3 ro, float3 rd, float r,float t)
{
    //float t;
    float b = dot(-ro, rd);
	float det = b*b - dot(ro, ro) + r*r;
	if (det < 0.0) return false;
	det = sqrt(det);
	t = b - det;
	return t > 0.0;
}

float3 rotateX(float3 p, float a)
{
    float sa = sin(a);
    float ca = cos(a);
    return float3(p.x, ca*p.y - sa*p.z, sa*p.y + ca*p.z);
}
float3 rotateY(float3 p, float a)
{
    float sa = sin(a);
    float ca = cos(a);
    return float3(ca*p.x + sa*p.z, p.y, -sa*p.x + ca*p.z);
}

float2 cartesianToSpherical(float3 p)
{		
	float r = length(p);

	float t = (r - (1.0 - furDepth)) / furDepth;	
	p = rotateX(p.zyx, -cos(iTime*1.5)*t*t*0.4).zyx;	// curl

	p /= r;	
	float2 uv = float2(atan2(p.y, p.x), acos(p.z));

	//uv.x += cos(iTime*1.5)*t*t*0.4;	// curl
	//uv.y += sin(iTime*1.7)*t*t*0.2;
	uv.y -= t*t*0.1;	// curl down
	return uv;
}


//float furDensity(float3 pos, out float2 uv,Texture2D<float4> Tex0A,sampler Tex0ASampler)
float furDensity(float3 pos,float2 uv,Texture2D<float4> Tex0A,sampler Tex0ASampler,float2 UV0)
{
	uv = cartesianToSpherical(pos.xzy);	
	//float3 tex = Texture2DSample(Tex0,Tex0Sampler,uv*uvScale);
	float3 tex = Texture2DSample(Tex0A,Tex0ASampler,uv*uvScale);

	// thin out hair
	float density = smoothstep(furThreshold, 1.0, tex.x);
	
	float r = length(pos);
	float t = (r - (1.0 - furDepth)) / furDepth;
	
	// fade out along length
	float len = tex.y;
	density *= smoothstep(len, len-0.2, t);

	return density;	
}


// calculate normal from density
float3 furNormal(float3 pos, float density,Texture2D<float4> Tex0A,sampler Tex0ASampler,float2 UV0)
{
    float eps = 0.01;
    float3 n;
	float2 uv;
    n.x = furDensity( float3(pos.x+eps, pos.y, pos.z), uv ,Tex0A,Tex0ASampler,UV0) - density;
    n.y = furDensity( float3(pos.x, pos.y+eps, pos.z), uv ,Tex0A,Tex0ASampler,UV0) - density;
    n.z = furDensity( float3(pos.x, pos.y, pos.z+eps), uv ,Tex0A,Tex0ASampler,UV0) - density;
    return normalize(n);
}


//float3 furShade(Texture2D<float4> Tex1A,sampler Tex1ASampler,Texture2D<float4> Tex0A,sampler Tex0ASampler,float2 UV0)
float3 furShade(float3 pos, float2 uv, float3 ro, float density,Texture2D<float4> Tex1A,sampler Tex1ASampler,Texture2D<float4> Tex0A,sampler Tex0ASampler,float2 UV0)
{
    /*
    float2 iResolution = float2(2048,2048);
    float2 fragCoord = float2(640,360);
    
    float2 uv = fragCoord.xy / iResolution.xy;
	uv = uv*2.0-1.0;
	uv.x *= iResolution.x / iResolution.y;
    //uv =UV;
    
    float3 ro = float3(0.0, 0.0, 2.5);
	float3 rd = normalize(float3(uv, -2.0));
    float t2=1.0;
    float3 pos = ro + rd*t2;
    float density = furDensity(pos, uv,Tex0A,Tex0ASampler,UV0);
    */
    //----------------------------------------------------
	// lighting
	const float3 L = float3(0, 1, 0);
	float3 V = normalize(ro - pos);
	float3 H = normalize(V + L);

	float3 N = -furNormal(pos, density,Tex0A,Tex0ASampler,UV0);
	//float diff = max(0.0, dot(N, L));
	float diff = max(0.0, dot(N, L)*0.5+0.5);
	float spec = pow(max(0.0, dot(N, H)), shininess);
	
	// base color
	//float3 color = Texture2DSample(Tex1,Tex1Sampler, uv*colorUvScale).xyz;
	//float3 color = Texture2DSample(Tex1A,Tex1ASampler, UV0*colorUvScale).xyz;
	float3 color = Texture2DSample(Tex1A,Tex1ASampler, UV0*1.5).xyz;
    
	// darken with depth
	float r = length(pos);
	float t = (r - (1.0 - furDepth)) / furDepth;
	t = clamp(t, 0.0, 1.0);
	float i = t*0.5+0.5;
		
	//return color*diff*i + float3(spec*i,spec*i,spec*i);
    return color;
}	

float GetRandomNumber(float2 texCoord, int Seed)
{
    return frac(sin(dot(texCoord.xy, float2(12.9898, 78.233)) + Seed) * 43758.5453);
}

//float4 scene(float3 ro,float3 rd)
float4 scene(Texture2D<float4> Tex1A,sampler Tex1ASampler,Texture2D<float4> Tex0A,sampler Tex0ASampler,float2 UV0)
{
    float2 iResolution = float2(2048,2048);
    float2 fragCoord = float2(640,360);
    
    float2 uv = fragCoord.xy / iResolution.xy;
	uv = uv*2.0-1.0;
	uv.x *= iResolution.x / iResolution.y;
    uv=UV;
    float3 ro = float3(0.0, 0.0, 2.5);
	float3 rd = normalize(float3(uv, -2.0));
    
	//-------------------------------------------
	float3 p = float3(0.0,0.0,0.0);
	//const float r = 1.0;
	const float r = 1.1;
	float t=1.0;				  
	bool hit = intersectSphere(ro - p, rd, r, t);
	
	float4 c = float4(0.0,0.0,0.0,0.0);
    float4 sampleCol= float4(0.0,0.0,0.0,0.0);
    
    float rayStepA = furDepth*2.0 / float(furLayers);
    //float2 uv;
    float density;
    //float2 uv =float2(0.5,0.5);
	if (hit) {
		float3 pos = ro + rd*t;

		// ray-march into volume
		//for(int i=0; i<furLayers; i++) {
        for(int i=0; i<91; i++) {

			sampleCol.a = furDensity(pos, uv,Tex0A,Tex0ASampler,UV0)+0.5;
			//sampleCol.a = furDensity(pos, UV,Tex0A,Tex0ASampler,UV0)+0.5;
			//sampleCol.a = GetRandomNumber(UV,  5);
			//sampleCol.a = Texture2DSample(Tex0A,Tex0ASampler,UV*uvScale).y;
            
			//sampleCol.a = 1.0;
            density = sampleCol.a;
			if (sampleCol.a > 0.0) {
                sampleCol.rgb = furShade( pos,  uv,  ro, density, Tex1A, Tex1ASampler, Tex0A, Tex0ASampler, UV0);
                //sampleCol.rgb = furShade( pos,  UV,  ro, density, Tex1A, Tex1ASampler, Tex0A, Tex0ASampler, UV0);

				// pre-multiply alpha
				sampleCol.rgb *= sampleCol.a;
				c = c + sampleCol*(1.0 - c.a);
				if (c.a > 0.95) break;
			}
			
			pos += rd*rayStepA;
		}

	}
	
	return c;
	//return sampleCol;
}

/*
//float4 mainImage( out float4 fragColor, in float2 fragCoord )
//float4 mainImage(float2 fragCoord )
float4 mainImage( )
{
    //-----------------------------------------
    float2 iResolution = float2(256,256);
    float2 fragCoord = float2(256,256);
    float3 iMouse = float3(128,128,128);

	float2 uv = fragCoord.xy / iResolution.xy;
	uv = uv*2.0-1.0;
	uv.x *= iResolution.x / iResolution.y;
	
	float3 ro = float3(0.0, 0.0, 2.5);
	float3 rd = normalize(float3(uv, -2.0));
	
	float2 mouse = iMouse.xy / iResolution.xy;
	float roty = 0.0;
	float rotx = 0.0;
	if (iMouse.z > 0.0) {
		rotx = (mouse.y-0.5)*3.0;
		roty = -(mouse.x-0.5)*6.0;
	} else {
		roty = sin(iTime*1.5);
	}
	
    ro = rotateX(ro, rotx);	
    ro = rotateY(ro, roty);	
    rd = rotateX(rd, rotx);
    rd = rotateY(rd, roty);
	//--------------------------------------------------
    
    float2 iResolution = float2(256,256);
    float2 fragCoord = float2(256,256);
    
    float2 uv = fragCoord.xy / iResolution.xy;
	uv = uv*2.0-1.0;
	uv.x *= iResolution.x / iResolution.y;
    
    float3 ro = float3(0.0, 0.0, 2.5);
	float3 rd = normalize(float3(uv, -2.0));
    
	//fragColor = scene(ro, rd);
    //return fragColor;
    return scene(ro, rd);
}
*/

//float4 MyFunction(float2 UV,float iTime,Texture2D<float4> Tex0,Texture2D<float4> Tex1,sampler Tex0Sampler,sampler Tex1Sampler)
float4 MyFunction()

{
	return float4(0.0,1.0,0.0,1.0);
}

プロジェクトのダウンロード

https://drive.google.com/file/d/1RZ5TCEDluJOAzsGnDZp6nwCpN8u2we2U/view?usp=sharing

#UE4 #UE4Study 半径変更可能なRingをHLSLで描く #Shader #HLSL

Code : return MyFunction(texCoord,resolution,R);

OutputType: Float4

Inputs : texCoord,resolution,R,B

IncludeFilePath:/Project/Ring.usf

// ring
float centerR= length(p);//その座標の中心からの距離  中心が1 まわり0
float gradationOffset=R-centerR; //グラデーションをずらす。
float ring= abs(gradationOffset); //中心から距離が 0.5 となる場所ほど値を小さく
float t = B/ring;//見た目が天使の輪に見えるように係数をかける
//Ring.usf

//return MyFunction(texCoord,resolution,R,B);
float4 MyFunction(float2 texCoord,float2 resolution,float R,float B)
{
    // グラデーションのcenterをずらす
	float2 p = (texCoord.xy * 2.0 - resolution) / min(resolution.x, resolution.y);
	
    // ring
    float centerR= length(p);//その座標の中心からの距離  中心が1 まわり0
    float gradationOffset=R-centerR; //グラデーションをずらす。
    float ring= abs(gradationOffset); //中心から距離が 0.5 となる場所ほど値を小さく
    float t = B/ring;//見た目が天使の輪に見えるように係数をかける

    return float4(t,t,t, 1.0);;
}

参考

https://wgld.org/d/glsl/g004.html

#UE4 #UE4Study CostomノードのHLSLで円を描く三平方の定理で円を色分け

三平方の定理で円を色分け

Code: return MyFunction(texCoord,resolution,R,A,B);

OutputType:Float4

Inputs: texCoord,resolution,R,A,B

Input File Paths: /Project/Circle.usf

pow(V,2.0)でVの2乗って意味

https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-pow

つかわないでみた。

float R2=p.x*p.x+p.y*p.y;//三平方の定理


//Circle.usf

//return MyFunction(texCoord,resolution,R,A,B);
float4 MyFunction(float2 texCoord,float2 resolution,float R,float4 A,float4 B)
{
	
	float2 p = (texCoord.xy * 2.0 - resolution) / min(resolution.x, resolution.y);
	//return float3(p.x,p.y,1.0);
	
    //float R=0.5;

    //float4 c = float4(1.0,1.0,1.0,1.0);// baseColor
    float4 c =A;// baseColor
    float R2=p.x*p.x+p.y*p.y;//三平方の定理
    //if(pow(p.x,2.0) + pow(p.y,2.0) <= R){
    if(R2 <= R){
       // c = float4(0.0,0.0,0.0,0.0); //circleColor
        c = B;//circleColor
    }
    return c;
}

参考

UE4 Shader MaterialのCustomノードが進化してincludeFilePathでのファイル参照ができるようになっていた件

失敗1、2020年になってCustomノードが安定してきたみたいで

constで宣言しておくとそのままMyFloat使える

Codeにreturn MyFloat;で使える。

CodeにMyreturn MyFunction();で関数を呼び出せる。

const static float3 MyFloat = float3(1.0,0.0,0.0);

float3 MyFunction()
{
	return float3(0.0,1.0,0.0);
}

TestOutput1 = float3(0,0,1);
return 0.0;

Additional Output :TestOutput1

OutputType CMOT Float1

コンパイルされて自動生成されたHLSLコードの中身は

エラーコードで出てくるこれは

/Engine/Generated/Material.ush

マテリアルエディタのメニュー「ウインドウ>シェーダーコード>HLSL コード」を選択。

すると HLSL コードのウインドウが開き、コンパイルされた全マテリアルの内容が HLSL で表示される。

このプロジェクトの作り方は

【UE4】USF(Unreal Shader File) をすぐに始める環境設定 Project編さん

でのShaderフォルダの読み込み設定が必要だった。。50個ぐらいエラーがでるので見ない方がいいかも

今回はプロジェクト名は:Shader_MatCustomにしたよ

プロジェクト設定でCPP

Shader_MatCustom.h

// Copyright Epic Games, Inc. All Rights Reserved.

#pragma once

#include "CoreMinimal.h"

#include "Modules/ModuleManager.h"

class FShader_MatCustom : public IModuleInterface
{
public:
    virtual void StartupModule() override;
    virtual void ShutdownModule() override;


};

Shader_MatCustom.cpp

// Copyright Epic Games, Inc. All Rights Reserved.

#include "Shader_MatCustom.h"
#include "Modules/ModuleManager.h"

IMPLEMENT_PRIMARY_GAME_MODULE( FShader_MatCustom, Shader_MatCustom, "Shader_MatCustom" );//3つの書き換え


void FShader_MatCustom::StartupModule()
{
    FString ShaderDirectory = FPaths::Combine(FPaths::ProjectDir(), TEXT("Shader"));
    if (!AllShaderSourceDirectoryMappings().Contains("/Project"))
    {
        AddShaderSourceDirectoryMapping("/Project", ShaderDirectory);
    }

}

void FShader_MatCustom::ShutdownModule()
{
}

Shader_MatCustom.Build.cs

// Copyright Epic Games, Inc. All Rights Reserved.

using UnrealBuildTool;

public class Shader_MatCustom : ModuleRules  // ←クラス名リネーム
{
	public Shader_MatCustom(ReadOnlyTargetRules Target) : base(Target)  // ←クラス名リネーム
	{
		PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
	
		PublicDependencyModuleNames.AddRange(new string[] {  //改行して展開した。
			"Core",
			"CoreUObject",
			"Engine",
			"InputCore",
			"RenderCore",  // ←追記
			"RHI"         // ←あとで必要になるので追記(パス追加に関係ない)
		});

		PrivateDependencyModuleNames.AddRange(new string[] {  });



		// Uncomment if you are using Slate UI
		// PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });
		
		// Uncomment if you are using online features
		// PrivateDependencyModuleNames.Add("OnlineSubsystem");

		// To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true
	}
}

VSでビルドをしてコンパイル

Shaderフォルダ作成

マテリアル作成

CustomNode作成

MyShader.usf作成

IncludeFilePathに/Project/MyShader.usf

MyShader.usf

const static float3 MyFloat = float3(1.0,0.0,0.0);

float3 MyFunction()
{
	return float3(0.0,1.0,0.0);
}

やっとうまくいったので

C++サンプルプロジェクトは丸ごとだ。.slnも入ってるよ

https://drive.google.com/file/d/1-ClY_v2cudLARAkMmAfPGrAnFndNnWIX/view?usp=sharing

参照

キンアジさんのところで見つけてしまった。

UE4 ShaderReaderProで1000円で安定したHLSL環境を手に入れた

失敗1,CustomNodeはUE4が落ちまくる。

失敗2,ShaderReader(フリー版は動きもしなかったが)

失敗3,エンジンにインストールなので仕事で使えるか不明

ここに入っている

C:\Program Files\Epic Games\UE_4.26\Engine\Plugins\Marketplace\ShaderReaderPro

成功、ShaderReaderProで1000円で安定したHLSL環境を手に入れた

VSCodeを使うことになることは必須みたい。.usf拡張子の編集をするのでテキストハイライトの対応関係でそうなる。

これでやりたい放題HLSLが書けるかもしれない。まだこんだけ

1,float MyVer1;するだけで入力ピンがでる。

2,ファイル参照からHLSLデータが読み込める。

float MyVer1;
float MyVer2;
float MyVer3;
float MyVer4;
return float4(MyVer1,MyVer2,MyVer3,MyVer4);

BeaTeacherさんの動画

参考

https://wgld.WebGL 開発支援サイト wgld.org