[Maya] .offsetParentMatrixをスクリプトで取り扱う場合の研究

この関数を

import os
import stat
import maya.cmds as cmds
#import maya.OpenMaya as OpenMaya
import maya.api.OpenMaya as OpenMaya
def func_offsetParentMatrix(node,driver):
    mult = cmds.createNode("multMatrix")

    offset = matrix_to_list(
        OpenMaya.MMatrix(cmds.getAttr("{}.worldMatrix[0]".format(node)))
        * OpenMaya.MMatrix(cmds.getAttr("{}.matrix".format(node))).inverse()
        * OpenMaya.MMatrix(cmds.getAttr("{}.worldInverseMatrix[0]".format(driver)))
    )
    cmds.setAttr("{}.matrixIn[0]".format(mult), offset, type="matrix")

    cmds.connectAttr("{}.worldMatrix[0]".format(driver), "{}.matrixIn[1]".format(mult))

    parent = cmds.listRelatives(node, parent=True, path=True)
    if parent:
        cmds.connectAttr("{}.worldInverseMatrix[0]".format(parent[0]), "{}.matrixIn[2]".format(mult))

    cmds.connectAttr(
        "{}.matrixSum".format(mult), "{}.offsetParentMatrix".format(node)
    )
    
def matrix_to_list(mtx):
    lst=[]
    for row in range(0,4):
        for col in range(0,4):
            lst.append(mtx.getElement(row,col))
    return lst
    
def list_to_matrix(lst):
    mtx=OpenMaya.MMatrix(lst)
    # OpenMaya.MScriptUtil.createMatrixFromList(lst, mtx)
    return mtx

こう使った。

global proc Func_TEST_offsetParentMatrix_Proc(){    
    print("Func_TEST_offsetParentMatrix_Proc");
    spaceLocator -position -15.216 0.0 0.0 -name "calf_l_OffsetMatrix_locator_l" -absolute;
    func_offsetParentMatrix_Python_Proc("Dummy_calf_telescopic_l","calf_l_OffsetMatrix_locator_l");
}
    
global proc func_offsetParentMatrix_Python_Proc(string $node,string $driver){
    print("func_offsetParentMatrix");
    python("import func_offsetParentMatrix");
	python("import importlib");
	python("importlib.reload(func_offsetParentMatrix)");
    python("func_offsetParentMatrix.func_offsetParentMatrix('"+$node+"','"+$driver+"')");
}

参考

offsetParentMatrixの記事
https://www.chadvernon.com/blog/space-switching-offset-parent-matrix/

matrix_to_list
https://gist.github.com/rjmoggach/4ea80af3104a3517d3a2a46293acf043

Python3.11 で 簿記3級 の勉強

今回はPython3.11.5を使った。

https://www.python.org/downloads/windows/

python-3.11.5-amd64.exe

まあまあ時間かかる。。。。

システム環境変数追加なんで再起動して下さい。

F:\Python311に入れた

C:\Users\furcr>F:

F:>cd F:\Python311

F:\Python311>pip

動いたら

pip install pandas

動いたら

https://qiita.com/et47/items/ec05beb03c09d79a9f09

をやっていく

とりま


#仕訳をPandasのDataFrame形式で、仕訳帳 df_siwake に入力します。
#Siwakeクラスの関数 entry を呼び出すことで、df_siwakeに仕訳データの行を追加し、更新します。
#仕訳ルール①:借方(左側)、貸方(右側)に勘定科目と金額を記載する
#に従い、仕訳を入力するための空のDataFrameとして仕訳帳 df_siwake を作成します。


import pandas as pd
df_siwake = pd.DataFrame(index=[],columns=['仕訳番号', '日付', '借方科目', '借方金額', '貸方科目', '貸方金額'])
print("df_siwake= "+str(df_siwake))



#仕訳入力時に必ず貸借が一致していることにより、後ほど残高試算表を作るときにも、
#貸借金額が一致することが保証されます。

#そこで仕訳入力用のクラス Siwake を定義し、まずは①複合仕訳の入力に対応する形で
#関数 entry を定義します。

#※最終的には Siwake 内に②データ型チェック、③貸借一致チェックの関数を実装しますが、
#コードが長くなるため、末尾に補足として追記します。

class Siwake:
    def __init__(self):
        self.siwake_no = 0
        print("self.siwake_no= "+str(self.siwake_no))

    def entry(self, df, date, kari, kashi): 
        self.siwake_no += 1 # ...仕訳番号を更新
        print("self.siwake_no= "+str(self.siwake_no))

        for i in range(len(kari)): # ...複合仕訳に対応するため[借方科目、借方金額]の数だけループを回す                    
            kari_entry = pd.Series([self.siwake_no] + [date] + kari[i] + ["", 0], index=df.columns)          
            print("kari_entry= "+str(kari_entry))
            df = df._append(kari_entry, ignore_index=True)

        for i in range(len(kashi)): # ...複合仕訳に対応するため[貸方科目、貸方金額]の数だけループを回す                    
            kashi_entry = pd.Series([self.siwake_no] + [date] + ["", 0] + kashi[i], index=df.columns)
            print("kashi_entry= "+str(kashi_entry))
            df = df._append(kashi_entry, ignore_index=True)

        return df
        
siwake = Siwake()


#仕訳①:会社を設立
#現金1000を元手に会社を設立しました。
#この元手のことを資本金と呼び、仕訳は以下の通りです。
print(u"------------会社を設立-----------")
df_siwake = siwake.entry(df_siwake, 20200401,[['現金', 1000]],[['資本金', 1000]])
df_siwake[df_siwake['仕訳番号']==siwake.siwake_no]

#仕訳②:商品の仕入
#商品500を外部業者より仕入れました。
#仕訳は以下の通りです。
print(u"------------商品の仕入-----------")
df_siwake = siwake.entry(df_siwake, 20200402,[['商品', 500]],[['買掛金', 500]])
df_siwake[df_siwake['仕訳番号']==siwake.siwake_no]

#仕訳③:商品を売上
#仕入れた商品のうち200について、価格300で販売しました。
#売上についての仕訳は以下の通りです。
print(u"------------商品を売上-----------")
df_siwake = siwake.entry(df_siwake, 20200403,[['売掛金', 300]],[['売上', 300]])
df_siwake[df_siwake['仕訳番号']==siwake.siwake_no]

#仕訳④:仕入代金を支払
#仕入代金500のうち300について、外部業者に支払いました。
#(残りの200は翌月支払の契約と仮定します)
#仕訳は以下の通りです。
print(u"------------仕入代金を支払-----------")
df_siwake = siwake.entry(df_siwake, 20200420,[['買掛金', 300]],[['現金', 300]])
df_siwake[df_siwake['仕訳番号']==siwake.siwake_no]

#仕訳⑤:販売代金を回収
#販売代金200について、販売先から現金で回収しました。
#(残りの100は翌月回収の契約と仮定します)
#仕訳は以下の通りです。
print(u"------------販売代金を回収-----------")
df_siwake = siwake.entry(df_siwake, 20200430,[['現金', 200]],[['売掛金', 200]])
df_siwake[df_siwake['仕訳番号']==siwake.siwake_no]

参考URL

https://www.sejuku.net/blog/64370

UE4 きれいなグラデーションの虹色のレインボーのマテリアルが作りたい

正解はtexCoordの応用だった。

texCoordを縦のグラデーションと横グラデーションに分け

値をLerpのAlphaにつないでお好きな色をA,Bにつなぐ。

2つ作ってMultplyして縦横グラデーションになるようにMIXした。

さらに回転させたい

下の部分が見切れていたので追加しました。

参考

UE4]UMGで使えるでシンプルなグラデーションを作 …historia.co.jp

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

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

[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

[UE5] SubSystemの種類

https://docs.unrealengine.com/4.26/ja/ProgrammingAndScripting/Subsystems/

このページにもあるがUE5には多くのサブシステムがあるみたい。
もうちょっと前からあったみたいスクショは4.25.4。

全部BluePrintからアクセスできる。

・ただでさえ入り組んだクラスにさらに API を追加しなくてすむ。

とあるように、中にはすごいAPIがたくさん詰まってる。

できないと思ってたことができることもある。

ここにあるだけで

EngineSubsystem 

EditorSubsystem 

GameInstanceSubsystem 

LocalPlayerSubsystem 

AssetEditorSubsystem

で肝心のAPIが

BrushEditingSubsystem

EditorUtilitySubsystem

で肝心のAPIが

ImportSubsystem

LayersSubsystem

MoviepipelineQueueSubsystem

PanelExtentionSubsystem

AssetTagsSubsystem

AutoDestroySubsystem

LandscapeSubsystem

ObjectTraceWorldSubsystem

参考URL

https://www.docswell.com/s/EpicGamesJapan/KY18EZ-UE4_AllStudy04_Subsystem#p1

アンリアルクエスト5で勉強したProcedural Meshでオブジェクトを切るについて

プロジェクトのサンプルはアンリアルクエスト5のプロジェクトを使いました。

https://historia.co.jp/unrealquest05 のDiscordから #プロジェクトデータ配布のチャンネルからDLできます。Discordサーバーが消えた場合はあとで考えます。

使用バージョンは
UE5.2.0

切られるオブジェクトを用意する

ブループリントクラス>Actorで作成します。

名前はBP_ProceduralMesh_Actor としました。

作成したブループリントを開き

DefaultSceneRootの下に

ProceduralMeshとCubeまたはキューブを追加します。

Cubeコンポーネントの設定

M_Procedralというマテリアルを作って

/Game/UnrealQuest5/Props/LevelPrototyping/Meshes/SM_Cubeをコピーしてきて
CubeコンポーネントのスタティックメッシュをSM_Cubeに変更

コピーしてきたSM_Cubeの設定を行います。

AllowCPUAccess にチェックを入れてCPUからでもメッシュ情報にアクセスできるようにします。

Procedural Meshコンポーネントの設定
Procedural Meshコンポーネントの Use Complex as Simple Collisionのチェックを外します。

コンストラクタのノードを設定する
ProceduralMeshに対してCube情報をコピーしてCubeコンポーネントを削除します。

コピーしてきたレベルに作成したBPをおいてみました。

BP_UQ5_Playerを開いて

BladeMeshのOnConponentBeginOverlapをクリックしてノードを作ります。

これ動くのSet Simulate Physics だけだったので、結局

ファーストパーソン を追加

/Game/FirstPerson/Blueprints/BP_FirstPersonProjectile をコピーして

BP_ProceduralBulletとする

On Component Hit をこのように改造する

BP_UQ5_PlayerにBullet_Spawnのカスタムイベントを追加

通常攻撃をコンボにカスタムしてあるけど、こんな感じでSequenceでBullet_Spawnを呼ぶ

BP_ProceduralBulletの当たり判定がデカくなるようにスケールをデカくした

できたのがこちら

アンリアルクエスト5のDiscordでこのページを見た兎月さんがもっとすごい実装方法をしていたので許可を頂いたので、こちらに張らせていただきます
https://uq5.netlify.app/UE5-1-1_Cut_with_a_blade.png

兎月さんに感謝!できたのがこれ。

きもちいですねカットした法線どおりに切れると!

参考サイト

SkeltalMeshをカット?
https://www.unrealengine.com/marketplace/en-US/product/slice-skeletal-mesh-vr?sessionInvalidated=true

[UE4/UE5]MasterPoseComponentの説明

ぷちコンでも乱用した

MasterPoseComponentの説明です。

これがあればぶっちゃけリターゲットとか必要なくない?

みたいなお話です。

大きいEnableMasterPose図はこれです。

アップのEnableMasterPoseはこれです。

UE5.1ではこうしないと

ブループリントランタイム エラー:”プロパティ SkeletalMeshComponent の読み取りを試行するためのアクセスはありません”。 ノード: ブランチ グラフ: EnableMasterPose 関数: Enable Master Pose ブループリント: BP_ThirdMetaHuman

のエラー出た から 最初からSkeletel Mesh Component をIsVaildしたら治った。

添わせたいスケルタルメッシュを以下のように設定するだけで

あたまがこれです。

そうびがこれです。

グレイマンはトランスペアレントなマテリアルで見せてません。

グレイマンはVisibleはTrueにしておかないと壊れます。

こうしているせいで全モーションはグレイマンに追加するだけででOKです。
どんどんグレーマンが鬼カスタムモーション化していくだけなので他のプロジェクトを作る際も鬼グレイマンさえ移行すればいいから簡単です。

以上でした。

5.1のバージョンはこんな感じでした。

Meshの下に入れ子にするのがポイント

参考

https://forums.unrealengine.com/t/topic/402278