feat: upgrade to ts2lua-unreal v0.3.0 and refactor Game classes to pure C++ callback + TS composition hot-reload
This commit is contained in:
1 parent
4ad4a8f36f
commit
783dccf53d
64 files changed
+2368
-714
No files matched your search
@@ -0,0 +1,186 @@
|
||||
// Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
#include "Core/LuaCallbackBridge.h"
|
||||
#include "UnrealLuaDemo.h"
|
||||
#include "Engine/World.h"
|
||||
#include "Modules/ModuleManager.h"
|
||||
#include "UnLua.h"
|
||||
#include "UnLuaModule.h"
|
||||
#include "LuaEnv.h"
|
||||
#include "lua.hpp"
|
||||
|
||||
namespace
|
||||
{
|
||||
UnLua::FLuaEnv* ResolveLuaEnv(UObject* Target)
|
||||
{
|
||||
if (!Target || Target->HasAnyFlags(RF_ClassDefaultObject | RF_ArchetypeObject))
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Actor 类仅在真实游戏/PIE 世界中分发回调,避免编辑器视口预览对象误触发
|
||||
if (const AActor* Actor = Cast<AActor>(Target))
|
||||
{
|
||||
const UWorld* World = Actor->GetWorld();
|
||||
if (!World || !World->IsGameWorld())
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
if (FModuleManager::Get().IsModuleLoaded(TEXT("UnLua")))
|
||||
{
|
||||
IUnLuaModule& UnLuaModule = IUnLuaModule::Get();
|
||||
if (UnLuaModule.IsActive())
|
||||
{
|
||||
if (UnLua::FLuaEnv* Env = UnLuaModule.GetEnv(Target))
|
||||
{
|
||||
return Env;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TMap<lua_State*, UnLua::FLuaEnv*>& AllEnvs = UnLua::FLuaEnv::GetAll();
|
||||
for (const TPair<lua_State*, UnLua::FLuaEnv*>& Pair : AllEnvs)
|
||||
{
|
||||
if (Pair.Value)
|
||||
{
|
||||
return Pair.Value;
|
||||
}
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool PushModuleFunction(lua_State* L, const FString& ModuleName, const char* FuncName, int32& OutErrHandlerIdx)
|
||||
{
|
||||
lua_pushcfunction(L, UnLua::ReportLuaCallError);
|
||||
OutErrHandlerIdx = lua_gettop(L);
|
||||
|
||||
lua_getglobal(L, "__MODULE__");
|
||||
if (!lua_istable(L, -1))
|
||||
{
|
||||
lua_pop(L, 2);
|
||||
return false;
|
||||
}
|
||||
|
||||
lua_getfield(L, -1, "Import");
|
||||
if (!lua_isfunction(L, -1))
|
||||
{
|
||||
lua_pop(L, 3);
|
||||
return false;
|
||||
}
|
||||
|
||||
const FTCHARToUTF8 ModNameUtf8(*ModuleName);
|
||||
lua_pushlstring(L, ModNameUtf8.Get(), ModNameUtf8.Length());
|
||||
if (lua_pcall(L, 1, 1, OutErrHandlerIdx) != LUA_OK)
|
||||
{
|
||||
lua_pop(L, 3); // error, __MODULE__, errHandler
|
||||
return false;
|
||||
}
|
||||
|
||||
// stack: errHandler, __MODULE__, M
|
||||
lua_remove(L, -2); // stack: errHandler, M
|
||||
if (!lua_istable(L, -1))
|
||||
{
|
||||
lua_pop(L, 2);
|
||||
return false;
|
||||
}
|
||||
|
||||
lua_getfield(L, -1, FuncName);
|
||||
lua_remove(L, -2); // stack: errHandler, fn
|
||||
if (!lua_isfunction(L, -1))
|
||||
{
|
||||
lua_pop(L, 2);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool FLuaCallbackBridge::Call(UObject* Target, const FString& ModuleName, const char* FuncName)
|
||||
{
|
||||
UnLua::FLuaEnv* Env = ResolveLuaEnv(Target);
|
||||
if (!Env)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
lua_State* L = Env->GetMainState();
|
||||
if (!L)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
const int32 Top = lua_gettop(L);
|
||||
int32 ErrHandlerIdx = 0;
|
||||
if (!PushModuleFunction(L, ModuleName, FuncName, ErrHandlerIdx))
|
||||
{
|
||||
lua_settop(L, Top);
|
||||
return false;
|
||||
}
|
||||
|
||||
UnLua::PushUObject(L, Target);
|
||||
const bool bOk = (lua_pcall(L, 1, 0, ErrHandlerIdx) == LUA_OK);
|
||||
lua_settop(L, Top);
|
||||
return bOk;
|
||||
}
|
||||
|
||||
bool FLuaCallbackBridge::CallFloat(UObject* Target, const FString& ModuleName, const char* FuncName, float Value)
|
||||
{
|
||||
UnLua::FLuaEnv* Env = ResolveLuaEnv(Target);
|
||||
if (!Env)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
lua_State* L = Env->GetMainState();
|
||||
if (!L)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
const int32 Top = lua_gettop(L);
|
||||
int32 ErrHandlerIdx = 0;
|
||||
if (!PushModuleFunction(L, ModuleName, FuncName, ErrHandlerIdx))
|
||||
{
|
||||
lua_settop(L, Top);
|
||||
return false;
|
||||
}
|
||||
|
||||
UnLua::PushUObject(L, Target);
|
||||
lua_pushnumber(L, static_cast<lua_Number>(Value));
|
||||
const bool bOk = (lua_pcall(L, 2, 0, ErrHandlerIdx) == LUA_OK);
|
||||
lua_settop(L, Top);
|
||||
return bOk;
|
||||
}
|
||||
|
||||
bool FLuaCallbackBridge::CallInt(UObject* Target, const FString& ModuleName, const char* FuncName, int32 Value)
|
||||
{
|
||||
UnLua::FLuaEnv* Env = ResolveLuaEnv(Target);
|
||||
if (!Env)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
lua_State* L = Env->GetMainState();
|
||||
if (!L)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
const int32 Top = lua_gettop(L);
|
||||
int32 ErrHandlerIdx = 0;
|
||||
if (!PushModuleFunction(L, ModuleName, FuncName, ErrHandlerIdx))
|
||||
{
|
||||
lua_settop(L, Top);
|
||||
return false;
|
||||
}
|
||||
|
||||
UnLua::PushUObject(L, Target);
|
||||
lua_pushinteger(L, static_cast<lua_Integer>(Value));
|
||||
const bool bOk = (lua_pcall(L, 2, 0, ErrHandlerIdx) == LUA_OK);
|
||||
lua_settop(L, Top);
|
||||
return bOk;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "CoreMinimal.h"
|
||||
|
||||
class UObject;
|
||||
|
||||
/**
|
||||
* 极薄 C++ -> Lua 回调分发器:
|
||||
* 通过 __MODULE__.Import(ModuleName)[FuncName](Target, ...) 直接调用纯 TS/Lua 模块,
|
||||
* 业务脚本无需在 Lua 中继承 UE 对象(不使用 IUnLuaInterface / UnLua.Class),
|
||||
* 100% 纳入 Lib/Module.lua 与 Lib/Class.lua 的单文件热更闭环。
|
||||
*/
|
||||
class UNREALLUADEMO_API FLuaCallbackBridge
|
||||
{
|
||||
public:
|
||||
static bool Call(UObject* Target, const FString& ModuleName, const char* FuncName);
|
||||
static bool CallFloat(UObject* Target, const FString& ModuleName, const char* FuncName, float Value);
|
||||
static bool CallInt(UObject* Target, const FString& ModuleName, const char* FuncName, int32 Value);
|
||||
};
|
||||
@@ -1,13 +1,21 @@
|
||||
// Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
#include "Core/LuaCharacter.h"
|
||||
#include "Core/LuaCallbackBridge.h"
|
||||
|
||||
ALuaCharacter::ALuaCharacter()
|
||||
{
|
||||
PrimaryActorTick.bCanEverTick = false;
|
||||
}
|
||||
|
||||
FString ALuaCharacter::GetModuleName_Implementation() const
|
||||
void ALuaCharacter::BeginPlay()
|
||||
{
|
||||
return LuaModuleName;
|
||||
Super::BeginPlay();
|
||||
FLuaCallbackBridge::Call(this, LuaModuleName, "OnBeginPlay");
|
||||
}
|
||||
|
||||
void ALuaCharacter::EndPlay(const EEndPlayReason::Type EndPlayReason)
|
||||
{
|
||||
FLuaCallbackBridge::CallInt(this, LuaModuleName, "OnEndPlay", static_cast<int32>(EndPlayReason));
|
||||
Super::EndPlay(EndPlayReason);
|
||||
}
|
||||
@@ -4,21 +4,21 @@
|
||||
|
||||
#include "CoreMinimal.h"
|
||||
#include "GameFramework/Character.h"
|
||||
#include "UnLuaInterface.h"
|
||||
#include "LuaCharacter.generated.h"
|
||||
|
||||
/**
|
||||
* Base Character bound to Lua (Script/lua/Game/LuaCharacter.lua).
|
||||
* C++ 薄桥接 Character:不实现 IUnLuaInterface,通过回调转发生命周期至纯 TS 模块 Game.LuaCharacter。
|
||||
*/
|
||||
UCLASS()
|
||||
class UNREALLUADEMO_API ALuaCharacter : public ACharacter, public IUnLuaInterface
|
||||
class UNREALLUADEMO_API ALuaCharacter : public ACharacter
|
||||
{
|
||||
GENERATED_BODY()
|
||||
|
||||
public:
|
||||
ALuaCharacter();
|
||||
|
||||
virtual FString GetModuleName_Implementation() const override;
|
||||
virtual void BeginPlay() override;
|
||||
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
|
||||
|
||||
protected:
|
||||
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua")
|
||||
|
||||
@@ -1,21 +1,19 @@
|
||||
// Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
#include "Core/LuaGameInstance.h"
|
||||
#include "Core/LuaCallbackBridge.h"
|
||||
#include "UnrealLuaDemo.h"
|
||||
|
||||
void ULuaGameInstance::Init()
|
||||
{
|
||||
Super::Init();
|
||||
UE_LOG(LogUnrealLuaDemo, Log, TEXT("ULuaGameInstance::Init() - LuaModule=%s"), *LuaModuleName);
|
||||
FLuaCallbackBridge::Call(this, LuaModuleName, "OnInit");
|
||||
}
|
||||
|
||||
void ULuaGameInstance::Shutdown()
|
||||
{
|
||||
UE_LOG(LogUnrealLuaDemo, Log, TEXT("ULuaGameInstance::Shutdown()"));
|
||||
FLuaCallbackBridge::Call(this, LuaModuleName, "OnShutdown");
|
||||
Super::Shutdown();
|
||||
}
|
||||
|
||||
FString ULuaGameInstance::GetModuleName_Implementation() const
|
||||
{
|
||||
return LuaModuleName;
|
||||
}
|
||||
@@ -4,14 +4,13 @@
|
||||
|
||||
#include "CoreMinimal.h"
|
||||
#include "Engine/GameInstance.h"
|
||||
#include "UnLuaInterface.h"
|
||||
#include "LuaGameInstance.generated.h"
|
||||
|
||||
/**
|
||||
* Base GameInstance bound to Lua (Script/lua/Game/LuaGameInstance.lua).
|
||||
* C++ 薄桥接 GameInstance:不实现 IUnLuaInterface,通过回调转发生命周期至纯 TS 模块 Game.LuaGameInstance。
|
||||
*/
|
||||
UCLASS()
|
||||
class UNREALLUADEMO_API ULuaGameInstance : public UGameInstance, public IUnLuaInterface
|
||||
class UNREALLUADEMO_API ULuaGameInstance : public UGameInstance
|
||||
{
|
||||
GENERATED_BODY()
|
||||
|
||||
@@ -19,10 +18,7 @@ public:
|
||||
virtual void Init() override;
|
||||
virtual void Shutdown() override;
|
||||
|
||||
virtual FString GetModuleName_Implementation() const override;
|
||||
|
||||
protected:
|
||||
/** Lua module name bound to this GameInstance (relative to Script/lua). */
|
||||
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua")
|
||||
FString LuaModuleName = TEXT("Game.LuaGameInstance");
|
||||
};
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "Core/LuaGameModeBase.h"
|
||||
#include "Core/LuaPlayerController.h"
|
||||
#include "Core/LuaCharacter.h"
|
||||
#include "Core/LuaCallbackBridge.h"
|
||||
|
||||
ALuaGameModeBase::ALuaGameModeBase()
|
||||
{
|
||||
@@ -10,7 +11,14 @@ ALuaGameModeBase::ALuaGameModeBase()
|
||||
DefaultPawnClass = ALuaCharacter::StaticClass();
|
||||
}
|
||||
|
||||
FString ALuaGameModeBase::GetModuleName_Implementation() const
|
||||
void ALuaGameModeBase::BeginPlay()
|
||||
{
|
||||
return LuaModuleName;
|
||||
Super::BeginPlay();
|
||||
FLuaCallbackBridge::Call(this, LuaModuleName, "OnBeginPlay");
|
||||
}
|
||||
|
||||
void ALuaGameModeBase::EndPlay(const EEndPlayReason::Type EndPlayReason)
|
||||
{
|
||||
FLuaCallbackBridge::CallInt(this, LuaModuleName, "OnEndPlay", static_cast<int32>(EndPlayReason));
|
||||
Super::EndPlay(EndPlayReason);
|
||||
}
|
||||
@@ -4,21 +4,21 @@
|
||||
|
||||
#include "CoreMinimal.h"
|
||||
#include "GameFramework/GameModeBase.h"
|
||||
#include "UnLuaInterface.h"
|
||||
#include "LuaGameModeBase.generated.h"
|
||||
|
||||
/**
|
||||
* Base GameMode bound to Lua (Script/lua/Game/LuaGameMode.lua).
|
||||
* C++ 薄桥接 GameMode:不实现 IUnLuaInterface,通过回调转发生命周期至纯 TS 模块 Game.LuaGameMode。
|
||||
*/
|
||||
UCLASS()
|
||||
class UNREALLUADEMO_API ALuaGameModeBase : public AGameModeBase, public IUnLuaInterface
|
||||
class UNREALLUADEMO_API ALuaGameModeBase : public AGameModeBase
|
||||
{
|
||||
GENERATED_BODY()
|
||||
|
||||
public:
|
||||
ALuaGameModeBase();
|
||||
|
||||
virtual FString GetModuleName_Implementation() const override;
|
||||
virtual void BeginPlay() override;
|
||||
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
|
||||
|
||||
protected:
|
||||
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua")
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
#include "Core/LuaPlayerController.h"
|
||||
#include "Core/LuaCallbackBridge.h"
|
||||
#include "Demo/LuaDemoActor.h"
|
||||
#include "UnrealLuaDemo.h"
|
||||
#include "Components/InputComponent.h"
|
||||
@@ -17,6 +18,14 @@ void ALuaPlayerController::BeginPlay()
|
||||
bShowMouseCursor = false;
|
||||
FInputModeGameOnly InputMode;
|
||||
SetInputMode(InputMode);
|
||||
|
||||
FLuaCallbackBridge::Call(this, LuaModuleName, "OnBeginPlay");
|
||||
}
|
||||
|
||||
void ALuaPlayerController::EndPlay(const EEndPlayReason::Type EndPlayReason)
|
||||
{
|
||||
FLuaCallbackBridge::CallInt(this, LuaModuleName, "OnEndPlay", static_cast<int32>(EndPlayReason));
|
||||
Super::EndPlay(EndPlayReason);
|
||||
}
|
||||
|
||||
void ALuaPlayerController::SetupInputComponent()
|
||||
@@ -33,21 +42,16 @@ void ALuaPlayerController::SetupInputComponent()
|
||||
}
|
||||
}
|
||||
|
||||
FString ALuaPlayerController::GetModuleName_Implementation() const
|
||||
{
|
||||
return LuaModuleName;
|
||||
}
|
||||
|
||||
void ALuaPlayerController::HandlePingKeyPressed()
|
||||
{
|
||||
UE_LOG(LogUnrealLuaDemo, Log, TEXT("ALuaPlayerController::HandlePingKeyPressed() -> dispatching OnDemoPingPressed to Lua"));
|
||||
OnDemoPingPressed();
|
||||
FLuaCallbackBridge::Call(this, LuaModuleName, "OnDemoPingPressed");
|
||||
}
|
||||
|
||||
void ALuaPlayerController::HandleHotReloadKeyPressed()
|
||||
{
|
||||
UE_LOG(LogUnrealLuaDemo, Log, TEXT("ALuaPlayerController::HandleHotReloadKeyPressed() -> dispatching OnDemoHotReloadPressed to Lua"));
|
||||
OnDemoHotReloadPressed();
|
||||
FLuaCallbackBridge::Call(this, LuaModuleName, "OnDemoHotReloadPressed");
|
||||
}
|
||||
|
||||
void ALuaPlayerController::DemoVerifyInteraction()
|
||||
|
||||
@@ -4,34 +4,21 @@
|
||||
|
||||
#include "CoreMinimal.h"
|
||||
#include "GameFramework/PlayerController.h"
|
||||
#include "UnLuaInterface.h"
|
||||
#include "LuaPlayerController.generated.h"
|
||||
|
||||
/**
|
||||
* Base PlayerController bound to Lua (Script/lua/Game/LuaPlayerController.lua).
|
||||
* Binds demo hotkeys ([Space] Ping Lua, [R] HotReload Lua) and forwards them to Lua via BlueprintImplementableEvent.
|
||||
* C++ 薄桥接 PlayerController:不实现 IUnLuaInterface,通过 FLuaCallbackBridge
|
||||
* 将生命周期与按键事件([Space] Ping, [R] HotReload)分发至纯 TS 模块 Game.LuaPlayerController。
|
||||
*/
|
||||
UCLASS()
|
||||
class UNREALLUADEMO_API ALuaPlayerController : public APlayerController, public IUnLuaInterface
|
||||
class UNREALLUADEMO_API ALuaPlayerController : public APlayerController
|
||||
{
|
||||
GENERATED_BODY()
|
||||
|
||||
public:
|
||||
virtual void BeginPlay() override;
|
||||
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
|
||||
virtual void SetupInputComponent() override;
|
||||
virtual FString GetModuleName_Implementation() const override;
|
||||
|
||||
/**
|
||||
* Implemented in LuaPlayerController.lua to test C++ -> Lua -> EventBus flow.
|
||||
* Note: BlueprintImplementableEvent ensures UE always dispatches through ProcessEvent into UnLua
|
||||
* (unlike BlueprintNativeEvent on native C++ classes which UHT optimizes to bypass ProcessEvent).
|
||||
*/
|
||||
UFUNCTION(BlueprintImplementableEvent, Category = "LuaDemo")
|
||||
void OnDemoPingPressed();
|
||||
|
||||
/** Implemented in LuaPlayerController.lua to trigger live Lua hot-reload. */
|
||||
UFUNCTION(BlueprintImplementableEvent, Category = "LuaDemo")
|
||||
void OnDemoHotReloadPressed();
|
||||
|
||||
/** Automated self-test command (console: Demo.VerifyInteraction) that simulates Space & R and verifies Tick + Lua state. */
|
||||
UFUNCTION(Exec)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
#include "Demo/LuaDemoActor.h"
|
||||
#include "Core/LuaCallbackBridge.h"
|
||||
#include "Components/StaticMeshComponent.h"
|
||||
#include "Components/TextRenderComponent.h"
|
||||
#include "Engine/StaticMesh.h"
|
||||
@@ -39,7 +40,7 @@ ALuaDemoActor::ALuaDemoActor()
|
||||
StatusText->SetVerticalAlignment(EVRTA_TextCenter);
|
||||
StatusText->SetWorldSize(26.0f);
|
||||
StatusText->SetTextRenderColor(FColor(120, 245, 255));
|
||||
StatusText->SetText(FText::FromString(TEXT("Waiting for UnLua...")));
|
||||
StatusText->SetText(FText::FromString(TEXT("Waiting for Lua...")));
|
||||
}
|
||||
|
||||
void ALuaDemoActor::BeginPlay()
|
||||
@@ -52,23 +53,22 @@ void ALuaDemoActor::BeginPlay()
|
||||
}
|
||||
|
||||
Super::BeginPlay();
|
||||
|
||||
FLuaCallbackBridge::Call(this, LuaModuleName, "OnBeginPlay");
|
||||
}
|
||||
|
||||
void ALuaDemoActor::Tick(float DeltaSeconds)
|
||||
{
|
||||
Super::Tick(DeltaSeconds);
|
||||
|
||||
// AActor::Tick skips ReceiveTick for pure native C++ classes (CLASS_Native without CLASS_CompiledFromBlueprint).
|
||||
// Explicitly call ReceiveTick so UnLua's Lua ReceiveTick override executes every frame.
|
||||
if (!GetClass()->HasAnyClassFlags(CLASS_CompiledFromBlueprint))
|
||||
{
|
||||
ReceiveTick(DeltaSeconds);
|
||||
}
|
||||
FLuaCallbackBridge::CallFloat(this, LuaModuleName, "OnTick", DeltaSeconds);
|
||||
}
|
||||
|
||||
FString ALuaDemoActor::GetModuleName_Implementation() const
|
||||
void ALuaDemoActor::EndPlay(const EEndPlayReason::Type EndPlayReason)
|
||||
{
|
||||
return LuaModuleName;
|
||||
FLuaCallbackBridge::CallInt(this, LuaModuleName, "OnEndPlay", static_cast<int32>(EndPlayReason));
|
||||
|
||||
Super::EndPlay(EndPlayReason);
|
||||
}
|
||||
|
||||
void ALuaDemoActor::SetStatusText(const FString& InText)
|
||||
@@ -86,6 +86,8 @@ FString ALuaDemoActor::GetStatusTextString() const
|
||||
|
||||
void ALuaDemoActor::SetCubeColor(FLinearColor NewColor)
|
||||
{
|
||||
CurrentCubeColor = NewColor;
|
||||
|
||||
if (!CubeDynamicMaterial && CubeMesh)
|
||||
{
|
||||
CubeDynamicMaterial = CubeMesh->CreateAndSetMaterialInstanceDynamic(0);
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
|
||||
#include "CoreMinimal.h"
|
||||
#include "GameFramework/Actor.h"
|
||||
#include "UnLuaInterface.h"
|
||||
#include "LuaDemoActor.generated.h"
|
||||
|
||||
class UStaticMeshComponent;
|
||||
@@ -12,11 +11,12 @@ class UTextRenderComponent;
|
||||
class UMaterialInstanceDynamic;
|
||||
|
||||
/**
|
||||
* Interactive demo actor driven by Lua (Script/lua/Game/LuaDemoActor.lua)
|
||||
* to visually and programmatically verify UnLua binding, Tick, EventBus, and HotReload.
|
||||
* C++ 薄桥接 Demo Actor:不实现 IUnLuaInterface(不在 Lua 侧继承 UE 对象),
|
||||
* 通过 FLuaCallbackBridge 将 BeginPlay / Tick / EndPlay 回调分发给纯 TS 模块 Game.LuaDemoActor,
|
||||
* 以便运行时 100% 通过 __MODULE__.ReimportSafely("Game.LuaDemoActor") 单文件热更旋转速度、颜色与逻辑。
|
||||
*/
|
||||
UCLASS(Blueprintable)
|
||||
class UNREALLUADEMO_API ALuaDemoActor : public AActor, public IUnLuaInterface
|
||||
class UNREALLUADEMO_API ALuaDemoActor : public AActor
|
||||
{
|
||||
GENERATED_BODY()
|
||||
|
||||
@@ -25,7 +25,7 @@ public:
|
||||
|
||||
virtual void BeginPlay() override;
|
||||
virtual void Tick(float DeltaSeconds) override;
|
||||
virtual FString GetModuleName_Implementation() const override;
|
||||
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
|
||||
|
||||
/** Updates the floating 3D status text rendered above the cube. */
|
||||
UFUNCTION(BlueprintCallable, Category = "LuaDemo")
|
||||
@@ -39,6 +39,10 @@ public:
|
||||
UFUNCTION(BlueprintCallable, Category = "LuaDemo")
|
||||
void SetCubeColor(FLinearColor NewColor);
|
||||
|
||||
/** Returns the last applied dynamic material color of the demo cube. */
|
||||
UFUNCTION(BlueprintPure, Category = "LuaDemo")
|
||||
FLinearColor GetCubeColor() const { return CurrentCubeColor; }
|
||||
|
||||
/** Returns the world location captured at BeginPlay (used for smooth bobbing). */
|
||||
UFUNCTION(BlueprintPure, Category = "LuaDemo")
|
||||
FVector GetInitialLocation() const { return InitialLocation; }
|
||||
@@ -82,5 +86,6 @@ private:
|
||||
UPROPERTY(Transient)
|
||||
TObjectPtr<UMaterialInstanceDynamic> CubeDynamicMaterial;
|
||||
|
||||
FLinearColor CurrentCubeColor = FLinearColor::White;
|
||||
FVector InitialLocation = FVector::ZeroVector;
|
||||
};
|
||||
@@ -1,12 +1,17 @@
|
||||
// Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
#include "HotUpdate/LuaHotUpdateSubsystem.h"
|
||||
#include "Demo/LuaDemoActor.h"
|
||||
#include "LuaBundle/LuaBundleAsset.h"
|
||||
#include "LuaBundle/LuaScriptSettings.h"
|
||||
#include "UnrealLuaDemo.h"
|
||||
#include "UnLuaDelegates.h"
|
||||
#include "Engine/GameInstance.h"
|
||||
#include "Engine/World.h"
|
||||
#include "EngineUtils.h"
|
||||
#include "HAL/FileManager.h"
|
||||
#include "Misc/CommandLine.h"
|
||||
#include "Misc/DateTime.h"
|
||||
#include "Misc/FileHelper.h"
|
||||
#include "Misc/Parse.h"
|
||||
#include "Misc/Paths.h"
|
||||
@@ -17,6 +22,7 @@ namespace
|
||||
FCriticalSection GLuaBundleAccessMutex;
|
||||
TStrongObjectPtr<ULuaBundleAsset> GCachedLuaBundleAsset;
|
||||
bool GBundleLoadAttempted = false;
|
||||
FDelegateHandle GLuaStateCreatedHandle;
|
||||
}
|
||||
|
||||
void ULuaHotUpdateSubsystem::Initialize(FSubsystemCollectionBase& Collection)
|
||||
@@ -46,21 +52,115 @@ void ULuaHotUpdateSubsystem::Initialize(FSubsystemCollectionBase& Collection)
|
||||
TEXT("LuaHotUpdateSubsystem initialized [ExternalSourceMode]. OverrideDir=%s ExternalDir=%s"),
|
||||
*HotUpdateDir, *GetDefaultScriptDir());
|
||||
}
|
||||
|
||||
#if WITH_EDITOR
|
||||
// PIE / Editor 模式下轮询 Saved/HotUpdate/reload.trigger,支持外部工具编译 TS 后一键触发单文件热更
|
||||
TriggerPollHandle = FTSTicker::GetCoreTicker().AddTicker(
|
||||
FTickerDelegate::CreateUObject(this, &ULuaHotUpdateSubsystem::PollHotReloadTriggerFile),
|
||||
0.2f);
|
||||
#endif
|
||||
}
|
||||
|
||||
void ULuaHotUpdateSubsystem::Deinitialize()
|
||||
{
|
||||
#if WITH_EDITOR
|
||||
if (TriggerPollHandle.IsValid())
|
||||
{
|
||||
FTSTicker::GetCoreTicker().RemoveTicker(TriggerPollHandle);
|
||||
TriggerPollHandle.Reset();
|
||||
}
|
||||
#endif
|
||||
|
||||
UE_LOG(LogUnrealLuaDemo, Log, TEXT("LuaHotUpdateSubsystem deinitialized."));
|
||||
Super::Deinitialize();
|
||||
}
|
||||
|
||||
#if WITH_EDITOR
|
||||
bool ULuaHotUpdateSubsystem::PollHotReloadTriggerFile(float DeltaTime)
|
||||
{
|
||||
const FString TriggerPath = FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("HotUpdate/reload.trigger"));
|
||||
if (!FPaths::FileExists(TriggerPath))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
FString Content;
|
||||
if (!FFileHelper::LoadFileToString(Content, *TriggerPath))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
IFileManager::Get().Delete(*TriggerPath, false, true, true);
|
||||
|
||||
TArray<FString> Lines;
|
||||
Content.ParseIntoArrayLines(Lines, true);
|
||||
|
||||
FString ResultLog;
|
||||
for (FString Line : Lines)
|
||||
{
|
||||
Line.TrimStartAndEndInline();
|
||||
if (Line.IsEmpty() || Line.StartsWith(TEXT("#")))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
bool bOk = true;
|
||||
if (Line == TEXT("*"))
|
||||
{
|
||||
ReloadAllLuaModules();
|
||||
}
|
||||
else
|
||||
{
|
||||
bOk = ReloadLuaModule(Line);
|
||||
}
|
||||
|
||||
ResultLog += FString::Printf(TEXT("[%s] target=%s ok=%s\n"),
|
||||
*FDateTime::Now().ToString(), *Line, bOk ? TEXT("true") : TEXT("false"));
|
||||
}
|
||||
|
||||
if (UGameInstance* GI = GetGameInstance())
|
||||
{
|
||||
if (UWorld* World = GI->GetWorld())
|
||||
{
|
||||
for (TActorIterator<ALuaDemoActor> It(World); It; ++It)
|
||||
{
|
||||
const FLinearColor C = It->GetCubeColor();
|
||||
ResultLog += FString::Printf(TEXT("Actor=%s Color=(%.2f,%.2f,%.2f) Status=%s\n"),
|
||||
*It->GetName(), C.R, C.G, C.B, *It->GetStatusTextString().Replace(TEXT("\n"), TEXT(" | ")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const FString ResultPath = FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("HotUpdate/reload.result"));
|
||||
FFileHelper::SaveStringToFile(ResultLog, *ResultPath, FFileHelper::EEncodingOptions::ForceUTF8WithoutBOM);
|
||||
UE_LOG(LogUnrealLuaDemo, Log, TEXT("[HotReloadTrigger] Processed trigger:\n%s"), *ResultLog);
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
void ULuaHotUpdateSubsystem::RegisterHotUpdateLoader()
|
||||
{
|
||||
FUnLuaDelegates::CustomLoadLuaFile.BindStatic(&ULuaHotUpdateSubsystem::HandleCustomLoadLuaFile);
|
||||
if (!GLuaStateCreatedHandle.IsValid())
|
||||
{
|
||||
GLuaStateCreatedHandle = FUnLuaDelegates::OnLuaStateCreated.AddStatic(&ULuaHotUpdateSubsystem::HandleLuaStateCreated);
|
||||
}
|
||||
|
||||
// 若 UnLua 插件先于游戏模块启动并已创建了 FLuaEnv(如 -game / Standalone 模式),立即补初始化运行时
|
||||
for (const TPair<lua_State*, UnLua::FLuaEnv*>& Pair : UnLua::FLuaEnv::GetAll())
|
||||
{
|
||||
HandleLuaStateCreated(Pair.Key);
|
||||
}
|
||||
}
|
||||
|
||||
void ULuaHotUpdateSubsystem::UnregisterHotUpdateLoader()
|
||||
{
|
||||
if (GLuaStateCreatedHandle.IsValid())
|
||||
{
|
||||
FUnLuaDelegates::OnLuaStateCreated.Remove(GLuaStateCreatedHandle);
|
||||
GLuaStateCreatedHandle.Reset();
|
||||
}
|
||||
|
||||
FUnLuaDelegates::CustomLoadLuaFile.Unbind();
|
||||
|
||||
FScopeLock Lock(&GLuaBundleAccessMutex);
|
||||
@@ -71,6 +171,29 @@ void ULuaHotUpdateSubsystem::UnregisterHotUpdateLoader()
|
||||
GBundleLoadAttempted = false;
|
||||
}
|
||||
|
||||
void ULuaHotUpdateSubsystem::HandleLuaStateCreated(lua_State* L)
|
||||
{
|
||||
if (!L)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (UnLua::FLuaEnv* Env = UnLua::FLuaEnv::FindEnv(L))
|
||||
{
|
||||
const bool bOk = Env->DoString(
|
||||
TEXT("if not _G.__MODULE__ then require('Lib.Module') end\nif not _G.__TS__DefineClass then require('Lib.Class') end"),
|
||||
TEXT("InitTs2LuaModuleRuntime"));
|
||||
if (!bOk)
|
||||
{
|
||||
UE_LOG(LogUnrealLuaDemo, Error, TEXT("[ts2lua] Failed to initialize Lib.Module / Lib.Class runtime."));
|
||||
}
|
||||
else
|
||||
{
|
||||
UE_LOG(LogUnrealLuaDemo, Log, TEXT("[ts2lua] Initialized Lib.Module & Lib.Class runtime."));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool ULuaHotUpdateSubsystem::ShouldUseLuaBundle()
|
||||
{
|
||||
#if WITH_EDITOR
|
||||
@@ -157,7 +280,7 @@ void ULuaHotUpdateSubsystem::ReloadAllLuaModules()
|
||||
{
|
||||
if (UnLua::FLuaEnv* Env = Pair.Value)
|
||||
{
|
||||
Env->DoString(TEXT("require('Framework.HotReload').ReloadAll()"), TEXT("HotReloadAll"));
|
||||
Env->DoString(TEXT("__MODULE__.Import('Framework.HotReload').ReloadAll()"), TEXT("HotReloadAll"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -181,7 +304,7 @@ bool ULuaHotUpdateSubsystem::ReloadLuaModule(const FString& ModuleName)
|
||||
EscapedName.ReplaceInline(TEXT("\\"), TEXT("\\\\"));
|
||||
EscapedName.ReplaceInline(TEXT("'"), TEXT("\\'"));
|
||||
|
||||
const FString Chunk = FString::Printf(TEXT("require('Framework.HotReload').ReloadModule('%s')"), *EscapedName);
|
||||
const FString Chunk = FString::Printf(TEXT("__MODULE__.Import('Framework.HotReload').ReloadModule('%s')"), *EscapedName);
|
||||
bool bAnySucceeded = false;
|
||||
|
||||
for (const TPair<lua_State*, UnLua::FLuaEnv*>& Pair : AllEnvs)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "CoreMinimal.h"
|
||||
#include "Containers/Ticker.h"
|
||||
#include "Subsystems/GameInstanceSubsystem.h"
|
||||
#include "LuaEnv.h"
|
||||
#include "LuaHotUpdateSubsystem.generated.h"
|
||||
@@ -64,6 +65,12 @@ public:
|
||||
|
||||
private:
|
||||
static ULuaBundleAsset* GetOrLoadLuaBundleAsset();
|
||||
static void HandleLuaStateCreated(lua_State* L);
|
||||
static bool HandleCustomLoadLuaFile(UnLua::FLuaEnv& Env, const FString& RelativeFilePath, TArray<uint8>& Data, FString& FullFilePath);
|
||||
static bool TryLoadLuaFromRoot(const FString& RootDir, const FString& NormalizedModulePath, TArray<uint8>& OutData, FString& OutFullPath);
|
||||
|
||||
#if WITH_EDITOR
|
||||
bool PollHotReloadTriggerFile(float DeltaTime);
|
||||
FTSTicker::FDelegateHandle TriggerPollHandle;
|
||||
#endif
|
||||
};
|
||||
@@ -60,7 +60,7 @@ void FUnrealLuaDemoModule::StartupModule()
|
||||
UnLua::PushUObject(L, World);
|
||||
lua_setglobal(L, "__UE_TEST_WORLD");
|
||||
}
|
||||
Env->DoString(TEXT("require('Tests.UE.UERuntimeSuite').RunAllInUE(_G.__UE_TEST_WORLD)"), TEXT("Lua.RunTests"));
|
||||
Env->DoString(TEXT("__MODULE__.Import('Tests.UE.UERuntimeSuite').RunAllInUE(_G.__UE_TEST_WORLD)"), TEXT("Lua.RunTests"));
|
||||
if (L)
|
||||
{
|
||||
lua_pushnil(L);
|
||||
|
||||
@@ -89,8 +89,8 @@ int32 URunLuaTestsCommandlet::Main(const FString& Params)
|
||||
lua_setglobal(L, "__UE_TEST_TICK");
|
||||
|
||||
const FString RunChunk = TEXT(
|
||||
"local suite = require('Tests.UE.UERuntimeSuite')\n"
|
||||
"local runner = require('Tests.Harness.TestRunner')\n"
|
||||
"local suite = __MODULE__.Import('Tests.UE.UERuntimeSuite')\n"
|
||||
"local runner = __MODULE__.Import('Tests.Harness.TestRunner')\n"
|
||||
"local summary = suite.RunAllInUE(_G.__UE_TEST_WORLD)\n"
|
||||
"_G.__UE_TEST_TOTAL = summary.total or 0\n"
|
||||
"_G.__UE_TEST_PASSED = summary.passed or 0\n"
|
||||
|
||||
Reference in new issue
Block a user