From 256a60ac80971d49e946616865ec2381d26bb771 Mon Sep 17 00:00:00 2001 From: szy73711 Date: Sat, 28 Nov 2026 15:48:35 +0800 Subject: [PATCH] feat: add L_LuaDemo scene and verify UnLua Tick, input, and hot-reload --- Config/DefaultEngine.ini | 4 +- Content/Maps/L_LuaDemo.umap | Bin 0 -> 21958 bytes Content/Script/Framework/HotReload.lua | 60 +++++++-- Content/Script/Game/LuaDemoActor.lua | 109 +++++++++++++++ Content/Script/Game/LuaGameMode.lua | 10 +- Content/Script/Game/LuaPlayerController.lua | 14 +- README.md | 19 ++- .../Core/LuaPlayerController.cpp | 126 ++++++++++++++++++ .../UnrealLuaDemo/Core/LuaPlayerController.h | 23 ++++ Source/UnrealLuaDemo/Demo/LuaDemoActor.cpp | 119 +++++++++++++++++ Source/UnrealLuaDemo/Demo/LuaDemoActor.h | 86 ++++++++++++ Tools/create_demo_map.py | 111 +++++++++++++++ UnrealLuaDemo.uproject | 7 + 13 files changed, 670 insertions(+), 18 deletions(-) create mode 100644 Content/Maps/L_LuaDemo.umap create mode 100644 Content/Script/Game/LuaDemoActor.lua create mode 100644 Source/UnrealLuaDemo/Demo/LuaDemoActor.cpp create mode 100644 Source/UnrealLuaDemo/Demo/LuaDemoActor.h create mode 100644 Tools/create_demo_map.py diff --git a/Config/DefaultEngine.ini b/Config/DefaultEngine.ini index d899be3..71ea000 100644 --- a/Config/DefaultEngine.ini +++ b/Config/DefaultEngine.ini @@ -1,6 +1,6 @@ [/Script/EngineSettings.GameMapsSettings] -GameDefaultMap=/Engine/Maps/Templates/Template_Default -EditorStartupMap=/Engine/Maps/Templates/Template_Default +GameDefaultMap=/Game/Maps/L_LuaDemo +EditorStartupMap=/Game/Maps/L_LuaDemo GlobalDefaultGameMode=/Script/UnrealLuaDemo.LuaGameModeBase GameInstanceClass=/Script/UnrealLuaDemo.LuaGameInstance diff --git a/Content/Maps/L_LuaDemo.umap b/Content/Maps/L_LuaDemo.umap new file mode 100644 index 0000000000000000000000000000000000000000..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#syR73)~a(*oBx)7BL)m0OyBB>Wl)8L78^B9Yu(|^C^Let;S3=Cy+u!*wDR*77@FO zv{8#z+%cj_8MDq6uN}Jfz<%SNP4@j)ox1C`E48AQ?gO!rLV^???W6`kf^$fN1P-<( zdXk{oG4MEe;xNFy&rk!8Gkb(KyscD9n1Dwq)`6oSc80ESn722fq z5&aYCxTY|I{e?^>m-msD0|bwQK|+6dn^HnVotMdVTvHgK{&M-y$3Tr4ex;VG?}hjU zKMu6VAzt%3F9|tu?i^?QLLUwW@U3=i2>s=4P?nN|mtq|_927>xzaz6L9*|4K-q7w{ z!n&D~aj{oTo5)8KBFhY^xf(mFwCNaPnL871^fIR7J73*+xaOgXAKlr0a{K5FEkD*u z$MnHK4v|i8jS~KUM2gYa`vJ0E53H-6S+kR%tzl zr8KSQ&~n(GoAdMM?tCO{UcL43RogCibl#}txrs!u`nU@>mHdBfB%4T|bAgkxqrzaq zux}`Ln5-4~aV? z&aalkGrxj07CTHWgNsFHVc!{pd{#?og)J)51|Ws_Cb6H3N#`s&AGissoXlt1S;8VZ zl*S6d!I`2%=|jl1%l_VBoM(OXxfxL@;{}KY1yMZ#2Q|~*)^<$oYe724u!2iFR`d69& literal 0 HcmV?d00001 diff --git a/Content/Script/Framework/HotReload.lua b/Content/Script/Framework/HotReload.lua index f5cc19b..8e0699f 100644 --- a/Content/Script/Framework/HotReload.lua +++ b/Content/Script/Framework/HotReload.lua @@ -8,8 +8,19 @@ local HotReload = {} HotReload.EVENT_BEFORE_RELOAD = "Framework.BeforeHotReload" HotReload.EVENT_AFTER_RELOAD = "Framework.AfterHotReload" ----Reloads a specific Lua module (clears package.loaded and re-requires it). ----@param moduleName string Dot-separated Lua module name, e.g. "Game.LuaGameMode" +local function CollectReloadableGameModules() + local modules = {} + for name, _ in pairs(package.loaded) do + if type(name) == "string" and name:match("^Game%.") then + modules[#modules + 1] = name + end + end + table.sort(modules) + return modules +end + +---Reloads a specific Lua module using UnLua's hot-reload sandbox (falls back to package.loaded reset). +---@param moduleName string Dot-separated Lua module name, e.g. "Game.LuaDemoActor" ---@return boolean ok ---@return any resultOrErr function HotReload.ReloadModule(moduleName) @@ -20,25 +31,50 @@ function HotReload.ReloadModule(moduleName) Log.Info("Hot-reloading Lua module: %s", moduleName) EventBus.Emit(HotReload.EVENT_BEFORE_RELOAD, moduleName) - package.loaded[moduleName] = nil - local ok, result = pcall(require, moduleName) - if not ok then - Log.Error("Failed to hot-reload module '%s': %s", moduleName, tostring(result)) - return false, result + local okHr, unluaHr = pcall(require, "UnLua.HotReload") + if okHr and unluaHr and type(unluaHr.reload) == "function" then + local ok, err = pcall(unluaHr.reload, { moduleName }) + if not ok then + Log.Error("UnLua.HotReload.reload('%s') failed: %s", moduleName, tostring(err)) + return false, err + end + else + package.loaded[moduleName] = nil + local ok, result = pcall(require, moduleName) + if not ok then + Log.Error("Failed to hot-reload module '%s': %s", moduleName, tostring(result)) + return false, result + end end - EventBus.Emit(HotReload.EVENT_AFTER_RELOAD, moduleName, result) + EventBus.Emit(HotReload.EVENT_AFTER_RELOAD, moduleName) Log.Info("Successfully hot-reloaded Lua module: %s", moduleName) - return true, result + return true end ----Triggers UnLua's built-in hot reload across all loaded modules. +---Triggers UnLua hot-reload across all loaded Game.* modules (supports Saved/HotUpdate/Script overrides). ---@return boolean ok function HotReload.ReloadAll() - Log.Info("Triggering full UnLua HotReload...") + local gameModules = CollectReloadableGameModules() + Log.Info("Triggering UnLua HotReload (modules=%d)...", #gameModules) EventBus.Emit(HotReload.EVENT_BEFORE_RELOAD, "*") - if UnLua and type(UnLua.HotReload) == "function" then + local okHr, unluaHr = pcall(require, "UnLua.HotReload") + if okHr and unluaHr and type(unluaHr.reload) == "function" then + if #gameModules > 0 then + local ok, err = pcall(unluaHr.reload, gameModules) + if not ok then + Log.Error("UnLua.HotReload.reload(gameModules) failed: %s", tostring(err)) + return false + end + end + -- Also run timestamp-based check for any other modified modules + local ok2, err2 = pcall(unluaHr.reload) + if not ok2 then + Log.Error("UnLua.HotReload.reload() failed: %s", tostring(err2)) + return false + end + elseif UnLua and type(UnLua.HotReload) == "function" then local ok, err = pcall(UnLua.HotReload) if not ok then Log.Error("UnLua.HotReload() failed: %s", tostring(err)) diff --git a/Content/Script/Game/LuaDemoActor.lua b/Content/Script/Game/LuaDemoActor.lua new file mode 100644 index 0000000..a66bde5 --- /dev/null +++ b/Content/Script/Game/LuaDemoActor.lua @@ -0,0 +1,109 @@ +---@type LuaDemoActor +local M = UnLua.Class() + +local Log = require("Framework.Log") +local EventBus = require("Framework.EventBus") +local HotReload = require("Framework.HotReload") + +local DEMO_COLORS = { + { Name = "Cyan", R = 0.08, G = 0.78, B = 0.95, A = 1.0 }, + { Name = "Gold", R = 0.98, G = 0.72, B = 0.12, A = 1.0 }, + { Name = "Magenta", R = 0.92, G = 0.22, B = 0.65, A = 1.0 }, + { Name = "Lime", R = 0.25, G = 0.90, B = 0.35, A = 1.0 }, + { Name = "Orange", R = 0.98, G = 0.42, B = 0.14, A = 1.0 }, +} + +local function MakeLinearColor(c) + return UE.FLinearColor(c.R, c.G, c.B, c.A) +end + +function M:ReceiveBeginPlay() + self.ElapsedTime = 0.0 + self.TextRefreshTimer = 0.0 + self.TickCount = 0 + self.PingCount = 0 + self.ReloadCount = 0 + self.ColorIndex = 1 + self.HasLoggedTick = false + + EventBus.On("Demo.Ping", self.OnDemoPing, self) + EventBus.On(HotReload.EVENT_AFTER_RELOAD, self.OnAfterHotReload, self) + + self:ApplyCurrentColor() + self:RefreshStatusText() + + Log.Info("LuaDemoActor:ReceiveBeginPlay() bound successfully! Lua=%s", _VERSION) + + local msg = string.format("[UnLua Demo] LuaDemoActor active (%s) - Press [Space] to Ping, [R] to HotReload", _VERSION) + UE.UKismetSystemLibrary.PrintString(self, msg, true, true, UE.FLinearColor(0.2, 1.0, 0.4, 1.0), 8.0) +end + +function M:ReceiveTick(DeltaSeconds) + self.ElapsedTime = (self.ElapsedTime or 0.0) + DeltaSeconds + self.TickCount = (self.TickCount or 0) + 1 + + if not self.HasLoggedTick then + self.HasLoggedTick = true + Log.Info("LuaDemoActor:ReceiveTick() first tick verified (dt=%.4f)", DeltaSeconds) + end + + -- Rotate cube mesh & apply vertical sine-wave bobbing entirely from Lua + local yawDelta = (self.SpinSpeed or 60.0) * DeltaSeconds + local pitchDelta = yawDelta * 0.35 + self:AddCubeLocalRotation(UE.FRotator(pitchDelta, yawDelta, 0.0)) + + local zOffset = math.sin(self.ElapsedTime * (self.BobFrequency or 2.0)) * (self.BobAmplitude or 25.0) + self:SetCubeVerticalOffset(zOffset) + + self.TextRefreshTimer = (self.TextRefreshTimer or 0.0) + DeltaSeconds + if self.TextRefreshTimer >= 0.2 then + self.TextRefreshTimer = 0.0 + self:RefreshStatusText() + end +end + +function M:OnDemoPing(sourceName) + self.PingCount = (self.PingCount or 0) + 1 + self.ColorIndex = (self.ColorIndex % #DEMO_COLORS) + 1 + local colorEntry = self:ApplyCurrentColor() + self:RefreshStatusText() + + local msg = string.format("[UnLua Demo] Ping #%d from %s -> Cube color: %s", self.PingCount, tostring(sourceName), colorEntry.Name) + Log.Info(msg) + UE.UKismetSystemLibrary.PrintString(self, msg, true, true, MakeLinearColor(colorEntry), 3.0) +end + +function M:OnAfterHotReload(moduleName) + self.ReloadCount = (self.ReloadCount or 0) + 1 + self:RefreshStatusText() + + local msg = string.format("[UnLua Demo] HotReload #%d completed (target=%s)", self.ReloadCount, tostring(moduleName)) + Log.Info(msg) + UE.UKismetSystemLibrary.PrintString(self, msg, true, true, UE.FLinearColor(1.0, 0.85, 0.2, 1.0), 4.0) +end + +function M:ApplyCurrentColor() + local colorEntry = DEMO_COLORS[self.ColorIndex or 1] or DEMO_COLORS[1] + self:SetCubeColor(MakeLinearColor(colorEntry)) + return colorEntry +end + +function M:RefreshStatusText() + local colorEntry = DEMO_COLORS[self.ColorIndex or 1] or DEMO_COLORS[1] + local text = string.format( + "UnLua Active (%s)\nTime: %.1fs | Pings: %d | Reloads: %d | Color: %s\n[Space] Ping Lua | [R] HotReload", + _VERSION, + self.ElapsedTime or 0.0, + self.PingCount or 0, + self.ReloadCount or 0, + colorEntry.Name + ) + self:SetStatusText(text) +end + +function M:ReceiveEndPlay(EndPlayReason) + EventBus.OffAllForOwner(self) + Log.Info("LuaDemoActor:ReceiveEndPlay(ticks=%d, pings=%d)", self.TickCount or 0, self.PingCount or 0) +end + +return M diff --git a/Content/Script/Game/LuaGameMode.lua b/Content/Script/Game/LuaGameMode.lua index 938870f..f4295d6 100644 --- a/Content/Script/Game/LuaGameMode.lua +++ b/Content/Script/Game/LuaGameMode.lua @@ -4,7 +4,15 @@ local M = UnLua.Class() local Log = require("Framework.Log") function M:ReceiveBeginPlay() - Log.Info("LuaGameMode:ReceiveBeginPlay()") + Log.Info("LuaGameMode:ReceiveBeginPlay() - Demo scene started") + UE.UKismetSystemLibrary.PrintString( + self, + "[UnLua Demo] LuaGameMode initialized!", + true, + true, + UE.FLinearColor(0.3, 0.85, 1.0, 1.0), + 5.0 + ) end function M:ReceiveEndPlay(EndPlayReason) diff --git a/Content/Script/Game/LuaPlayerController.lua b/Content/Script/Game/LuaPlayerController.lua index 6309922..cd75c5f 100644 --- a/Content/Script/Game/LuaPlayerController.lua +++ b/Content/Script/Game/LuaPlayerController.lua @@ -2,9 +2,21 @@ local M = UnLua.Class() local Log = require("Framework.Log") +local EventBus = require("Framework.EventBus") +local HotReload = require("Framework.HotReload") function M:ReceiveBeginPlay() - Log.Info("LuaPlayerController:ReceiveBeginPlay()") + Log.Info("LuaPlayerController:ReceiveBeginPlay() - Ready for [Space]=Ping, [R]=HotReload") +end + +function M:OnDemoPingPressed() + Log.Info("LuaPlayerController:OnDemoPingPressed() -> Emitting Demo.Ping") + EventBus.Emit("Demo.Ping", "LuaPlayerController") +end + +function M:OnDemoHotReloadPressed() + Log.Info("LuaPlayerController:OnDemoHotReloadPressed() -> Triggering HotReload.ReloadAll()") + HotReload.ReloadAll() end function M:ReceiveEndPlay(EndPlayReason) diff --git a/README.md b/README.md index eb72555..bbd280d 100644 --- a/README.md +++ b/README.md @@ -8,17 +8,20 @@ UnrealLuaDemo/ ├── Config/ # UE 项目配置(DefaultEngine / DefaultGame / DefaultInput 等) ├── Content/ +│ ├── Maps/ +│ │ └── L_LuaDemo.umap # Lua 执行与热更新验证 Demo 关卡(默认启动地图) │ └── Script/ # Lua 脚本根目录(打包时通过 DirectoriesToAlwaysStageAsNonUFS 输出) │ ├── Framework/ # Lua 基础框架层 │ │ ├── Bootstrap.lua # 框架启动入口(由 LuaGameInstance 初始化) │ │ ├── EventBus.lua # 轻量级事件总线 │ │ ├── HotReload.lua # Lua 模块热重载协调器 │ │ └── Log.lua # 统一日志封装 -│ └── Game/ # 游戏核心类对应的 Lua 绑定脚本 +│ └── Game/ # 游戏核心类与 Demo 对应的 Lua 绑定脚本 │ ├── LuaGameInstance.lua │ ├── LuaGameMode.lua │ ├── LuaPlayerController.lua -│ └── LuaCharacter.lua +│ ├── LuaCharacter.lua +│ └── LuaDemoActor.lua # Demo 场景中的旋转立方体与 3D 状态文本控制脚本 ├── Plugins/ │ └── UnLua/ # Tencent UnLua 插件(已适配 UE 5.8 编译) ├── Source/ @@ -31,13 +34,25 @@ UnrealLuaDemo/ │ │ ├── LuaPlayerController.* │ │ ├── LuaCharacter.* │ │ └── LuaBlueprintLibrary.* +│ ├── Demo/ # 验证场景 Actor +│ │ └── LuaDemoActor.* │ └── HotUpdate/ # Lua 热更新子系统 │ └── LuaHotUpdateSubsystem.* +├── Tools/ +│ └── create_demo_map.py # UE Python 关卡生成脚本(可重建 L_LuaDemo.umap) ├── .gitignore ├── .gitattributes └── UnrealLuaDemo.uproject ``` +## Demo 场景验证(`L_LuaDemo`) + +打开 `UnrealLuaDemo.uproject` 后会自动加载默认关卡 `Content/Maps/L_LuaDemo.umap`,点击 **Play (PIE)** 即可验证: + +- **自动执行验证**:场景中正前方的 `LuaDemoActor` 由 `Content/Script/Game/LuaDemoActor.lua` 驱动,会自动旋转、上下浮动,并在上方 3D 文本实时刷新 Lua 版本、运行时间、Ping 次数、热重载次数与当前颜色,同时屏幕左上角打印初始化信息。 +- **按 `Space`(空格)**:验证 `C++ 输入 -> LuaPlayerController -> EventBus -> LuaDemoActor -> C++ 材质颜色/3D 文本` 全链路,立方体切换颜色且计数 +1。 +- **按 `R`**:触发全量 Lua 热重载(`HotReload.ReloadAll()`),热重载计数 +1;可先将修改后的脚本放到 `Saved/HotUpdate/Script/Game/LuaDemoActor.lua` 再按 `R` 直接验证热更新覆盖生效。 + ## 核心设计 1. **C++ 骨架 + Lua 业务分离** diff --git a/Source/UnrealLuaDemo/Core/LuaPlayerController.cpp b/Source/UnrealLuaDemo/Core/LuaPlayerController.cpp index d04cdf4..d03f92b 100644 --- a/Source/UnrealLuaDemo/Core/LuaPlayerController.cpp +++ b/Source/UnrealLuaDemo/Core/LuaPlayerController.cpp @@ -1,8 +1,134 @@ // Copyright Epic Games, Inc. All Rights Reserved. #include "Core/LuaPlayerController.h" +#include "Demo/LuaDemoActor.h" +#include "UnrealLuaDemo.h" +#include "Components/InputComponent.h" +#include "Engine/World.h" +#include "EngineUtils.h" +#include "InputCoreTypes.h" +#include "InputKeyEventArgs.h" +#include "TimerManager.h" + +void ALuaPlayerController::BeginPlay() +{ + Super::BeginPlay(); + + bShowMouseCursor = false; + FInputModeGameOnly InputMode; + SetInputMode(InputMode); +} + +void ALuaPlayerController::SetupInputComponent() +{ + Super::SetupInputComponent(); + + if (InputComponent) + { + FInputKeyBinding& PingBinding = InputComponent->BindKey(EKeys::SpaceBar, IE_Pressed, this, &ALuaPlayerController::HandlePingKeyPressed); + PingBinding.bConsumeInput = false; + + FInputKeyBinding& ReloadBinding = InputComponent->BindKey(EKeys::R, IE_Pressed, this, &ALuaPlayerController::HandleHotReloadKeyPressed); + ReloadBinding.bConsumeInput = false; + } +} FString ALuaPlayerController::GetModuleName_Implementation() const { return LuaModuleName; } + +void ALuaPlayerController::HandlePingKeyPressed() +{ + UE_LOG(LogUnrealLuaDemo, Log, TEXT("ALuaPlayerController::HandlePingKeyPressed() -> dispatching OnDemoPingPressed to Lua")); + OnDemoPingPressed(); +} + +void ALuaPlayerController::HandleHotReloadKeyPressed() +{ + UE_LOG(LogUnrealLuaDemo, Log, TEXT("ALuaPlayerController::HandleHotReloadKeyPressed() -> dispatching OnDemoHotReloadPressed to Lua")); + OnDemoHotReloadPressed(); +} + +void ALuaPlayerController::DemoVerifyInteraction() +{ + UWorld* World = GetWorld(); + if (!World) + { + return; + } + + UE_LOG(LogUnrealLuaDemo, Log, TEXT("[DemoVerify] Scheduling simulated SpaceBar and R key presses after world ticks...")); + + FTimerHandle Step1Handle; + World->GetTimerManager().SetTimer(Step1Handle, [WeakSelf = TWeakObjectPtr(this)]() + { + ALuaPlayerController* PC = WeakSelf.Get(); + if (!PC) + { + return; + } + + UE_LOG(LogUnrealLuaDemo, Log, TEXT("[DemoVerify] Step 1: Simulating SpaceBar Pressed/Released")); + PC->InputKey(FInputKeyEventArgs::CreateSimulated(EKeys::SpaceBar, IE_Pressed, 1.0f)); + PC->InputKey(FInputKeyEventArgs::CreateSimulated(EKeys::SpaceBar, IE_Released, 0.0f)); + }, 0.35f, false); + + FTimerHandle Step2Handle; + World->GetTimerManager().SetTimer(Step2Handle, [WeakSelf = TWeakObjectPtr(this)]() + { + ALuaPlayerController* PC = WeakSelf.Get(); + if (!PC) + { + return; + } + + UE_LOG(LogUnrealLuaDemo, Log, TEXT("[DemoVerify] Step 2: Simulating R Pressed/Released")); + PC->InputKey(FInputKeyEventArgs::CreateSimulated(EKeys::R, IE_Pressed, 1.0f)); + PC->InputKey(FInputKeyEventArgs::CreateSimulated(EKeys::R, IE_Released, 0.0f)); + }, 0.70f, false); + + FTimerHandle Step3Handle; + World->GetTimerManager().SetTimer(Step3Handle, [WeakSelf = TWeakObjectPtr(this)]() + { + ALuaPlayerController* PC = WeakSelf.Get(); + if (!PC || !PC->GetWorld()) + { + return; + } + + ALuaDemoActor* DemoActor = nullptr; + if (TActorIterator It(PC->GetWorld()); It) + { + DemoActor = *It; + } + + if (!DemoActor) + { + UE_LOG(LogUnrealLuaDemo, Error, TEXT("[DemoVerify] FAILED: ALuaDemoActor not found in world.")); + FPlatformMisc::RequestExitWithStatus(false, 1); + return; + } + + const FString StatusStr = DemoActor->GetStatusTextString(); + const FRotator CubeRot = DemoActor->GetCubeLocalRotation(); + const bool bHasTickRotation = !CubeRot.IsNearlyZero(); + const bool bHasPing = StatusStr.Contains(TEXT("Pings: 1")); + const bool bHasReload = StatusStr.Contains(TEXT("Reloads: 1")); + + UE_LOG(LogUnrealLuaDemo, Log, TEXT("[DemoVerify] Step 3 Result -> CubeRot=%s | StatusText=\n%s"), + *CubeRot.ToString(), *StatusStr); + + if (bHasTickRotation && bHasPing && bHasReload) + { + UE_LOG(LogUnrealLuaDemo, Log, TEXT("[DemoVerify] PASSED: Tick rotation, SpaceBar Ping, and R HotReload all verified!")); + PC->ConsoleCommand(TEXT("Quit")); + } + else + { + UE_LOG(LogUnrealLuaDemo, Error, TEXT("[DemoVerify] FAILED: TickRot=%d Ping=%d Reload=%d"), + bHasTickRotation ? 1 : 0, bHasPing ? 1 : 0, bHasReload ? 1 : 0); + FPlatformMisc::RequestExitWithStatus(false, 1); + } + }, 1.15f, false); +} diff --git a/Source/UnrealLuaDemo/Core/LuaPlayerController.h b/Source/UnrealLuaDemo/Core/LuaPlayerController.h index 51b5534..c559f9d 100644 --- a/Source/UnrealLuaDemo/Core/LuaPlayerController.h +++ b/Source/UnrealLuaDemo/Core/LuaPlayerController.h @@ -9,6 +9,7 @@ /** * Base PlayerController bound to Lua (Content/Script/Game/LuaPlayerController.lua). + * Binds demo hotkeys ([Space] Ping Lua, [R] HotReload Lua) and forwards them to Lua via BlueprintImplementableEvent. */ UCLASS() class UNREALLUADEMO_API ALuaPlayerController : public APlayerController, public IUnLuaInterface @@ -16,9 +17,31 @@ class UNREALLUADEMO_API ALuaPlayerController : public APlayerController, public GENERATED_BODY() public: + virtual void BeginPlay() 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) + void DemoVerifyInteraction(); + protected: UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua") FString LuaModuleName = TEXT("Game.LuaPlayerController"); + +private: + void HandlePingKeyPressed(); + void HandleHotReloadKeyPressed(); }; diff --git a/Source/UnrealLuaDemo/Demo/LuaDemoActor.cpp b/Source/UnrealLuaDemo/Demo/LuaDemoActor.cpp new file mode 100644 index 0000000..627a8cb --- /dev/null +++ b/Source/UnrealLuaDemo/Demo/LuaDemoActor.cpp @@ -0,0 +1,119 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#include "Demo/LuaDemoActor.h" +#include "Components/StaticMeshComponent.h" +#include "Components/TextRenderComponent.h" +#include "Engine/StaticMesh.h" +#include "Materials/MaterialInterface.h" +#include "Materials/MaterialInstanceDynamic.h" +#include "UObject/ConstructorHelpers.h" + +ALuaDemoActor::ALuaDemoActor() +{ + PrimaryActorTick.bCanEverTick = true; + + SceneRoot = CreateDefaultSubobject(TEXT("SceneRoot")); + SetRootComponent(SceneRoot); + + CubeMesh = CreateDefaultSubobject(TEXT("CubeMesh")); + CubeMesh->SetupAttachment(SceneRoot); + + static ConstructorHelpers::FObjectFinder CubeMeshAsset(TEXT("/Engine/BasicShapes/Cube.Cube")); + if (CubeMeshAsset.Succeeded()) + { + CubeMesh->SetStaticMesh(CubeMeshAsset.Object); + } + + static ConstructorHelpers::FObjectFinder BasicMatAsset(TEXT("/Engine/BasicShapes/BasicShapeMaterial.BasicShapeMaterial")); + if (BasicMatAsset.Succeeded()) + { + CubeMesh->SetMaterial(0, BasicMatAsset.Object); + } + + StatusText = CreateDefaultSubobject(TEXT("StatusText")); + StatusText->SetupAttachment(SceneRoot); + StatusText->SetRelativeLocation(FVector(0.0f, 0.0f, 120.0f)); + // Face -X toward PlayerStart placed at (-450, 0, 100) + StatusText->SetRelativeRotation(FRotator(0.0f, 180.0f, 0.0f)); + StatusText->SetHorizontalAlignment(EHTA_Center); + StatusText->SetVerticalAlignment(EVRTA_TextCenter); + StatusText->SetWorldSize(26.0f); + StatusText->SetTextRenderColor(FColor(120, 245, 255)); + StatusText->SetText(FText::FromString(TEXT("Waiting for UnLua..."))); +} + +void ALuaDemoActor::BeginPlay() +{ + InitialLocation = GetActorLocation(); + + if (CubeMesh) + { + CubeDynamicMaterial = CubeMesh->CreateAndSetMaterialInstanceDynamic(0); + } + + Super::BeginPlay(); +} + +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); + } +} + +FString ALuaDemoActor::GetModuleName_Implementation() const +{ + return LuaModuleName; +} + +void ALuaDemoActor::SetStatusText(const FString& InText) +{ + if (StatusText) + { + StatusText->SetText(FText::FromString(InText)); + } +} + +FString ALuaDemoActor::GetStatusTextString() const +{ + return StatusText ? StatusText->Text.ToString() : FString(); +} + +void ALuaDemoActor::SetCubeColor(FLinearColor NewColor) +{ + if (!CubeDynamicMaterial && CubeMesh) + { + CubeDynamicMaterial = CubeMesh->CreateAndSetMaterialInstanceDynamic(0); + } + + if (CubeDynamicMaterial) + { + CubeDynamicMaterial->SetVectorParameterValue(TEXT("Color"), NewColor); + } +} + +void ALuaDemoActor::AddCubeLocalRotation(FRotator DeltaRotation) +{ + if (CubeMesh) + { + CubeMesh->AddLocalRotation(DeltaRotation); + } +} + +FRotator ALuaDemoActor::GetCubeLocalRotation() const +{ + return CubeMesh ? CubeMesh->GetRelativeRotation() : FRotator::ZeroRotator; +} + +void ALuaDemoActor::SetCubeVerticalOffset(float ZOffset) +{ + if (CubeMesh) + { + CubeMesh->SetRelativeLocation(FVector(0.0f, 0.0f, ZOffset)); + } +} diff --git a/Source/UnrealLuaDemo/Demo/LuaDemoActor.h b/Source/UnrealLuaDemo/Demo/LuaDemoActor.h new file mode 100644 index 0000000..792404b --- /dev/null +++ b/Source/UnrealLuaDemo/Demo/LuaDemoActor.h @@ -0,0 +1,86 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include "CoreMinimal.h" +#include "GameFramework/Actor.h" +#include "UnLuaInterface.h" +#include "LuaDemoActor.generated.h" + +class UStaticMeshComponent; +class UTextRenderComponent; +class UMaterialInstanceDynamic; + +/** + * Interactive demo actor driven by Lua (Content/Script/Game/LuaDemoActor.lua) + * to visually and programmatically verify UnLua binding, Tick, EventBus, and HotReload. + */ +UCLASS(Blueprintable) +class UNREALLUADEMO_API ALuaDemoActor : public AActor, public IUnLuaInterface +{ + GENERATED_BODY() + +public: + ALuaDemoActor(); + + virtual void BeginPlay() override; + virtual void Tick(float DeltaSeconds) override; + virtual FString GetModuleName_Implementation() const override; + + /** Updates the floating 3D status text rendered above the cube. */ + UFUNCTION(BlueprintCallable, Category = "LuaDemo") + void SetStatusText(const FString& InText); + + /** Returns the current floating 3D status text string. */ + UFUNCTION(BlueprintPure, Category = "LuaDemo") + FString GetStatusTextString() const; + + /** Updates the dynamic material color of the demo cube. */ + UFUNCTION(BlueprintCallable, Category = "LuaDemo") + void SetCubeColor(FLinearColor NewColor); + + /** Returns the world location captured at BeginPlay (used for smooth bobbing). */ + UFUNCTION(BlueprintPure, Category = "LuaDemo") + FVector GetInitialLocation() const { return InitialLocation; } + + /** Rotates only the cube mesh while keeping the floating 3D label readable. */ + UFUNCTION(BlueprintCallable, Category = "LuaDemo") + void AddCubeLocalRotation(FRotator DeltaRotation); + + /** Returns the current relative rotation of the cube mesh. */ + UFUNCTION(BlueprintPure, Category = "LuaDemo") + FRotator GetCubeLocalRotation() const; + + /** Sets the vertical bob offset of the cube mesh relative to the actor root. */ + UFUNCTION(BlueprintCallable, Category = "LuaDemo") + void SetCubeVerticalOffset(float ZOffset); + +public: + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "LuaDemo") + TObjectPtr SceneRoot; + + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "LuaDemo") + TObjectPtr CubeMesh; + + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "LuaDemo") + TObjectPtr StatusText; + + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "LuaDemo") + float SpinSpeed = 60.0f; + + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "LuaDemo") + float BobAmplitude = 25.0f; + + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "LuaDemo") + float BobFrequency = 2.0f; + +protected: + UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua") + FString LuaModuleName = TEXT("Game.LuaDemoActor"); + +private: + UPROPERTY(Transient) + TObjectPtr CubeDynamicMaterial; + + FVector InitialLocation = FVector::ZeroVector; +}; diff --git a/Tools/create_demo_map.py b/Tools/create_demo_map.py new file mode 100644 index 0000000..9d6bcd0 --- /dev/null +++ b/Tools/create_demo_map.py @@ -0,0 +1,111 @@ +import unreal + + +MAP_PATH = "/Game/Maps/L_LuaDemo" + + +def main(): + level_sub = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem) + actor_sub = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) + + unreal.log(f"[CreateDemoMap] Creating level: {MAP_PATH}") + ok = level_sub.new_level(MAP_PATH) + if not ok: + raise RuntimeError(f"Failed to create new level at {MAP_PATH}") + + # 1. Floor plane with grid material + floor = actor_sub.spawn_actor_from_class( + unreal.StaticMeshActor, + unreal.Vector(0.0, 0.0, 0.0), + unreal.Rotator(0.0, 0.0, 0.0), + ) + floor.set_actor_label("DemoFloor") + floor.set_actor_scale3d(unreal.Vector(25.0, 25.0, 1.0)) + plane_mesh = unreal.EditorAssetLibrary.load_asset("/Engine/BasicShapes/Plane") + if plane_mesh: + floor.static_mesh_component.set_static_mesh(plane_mesh) + grid_mat = unreal.EditorAssetLibrary.load_asset("/Engine/EngineMaterials/WorldGridMaterial") + if grid_mat: + floor.static_mesh_component.set_material(0, grid_mat) + + # 2. Directional sun light + sun = actor_sub.spawn_actor_from_class( + unreal.DirectionalLight, + unreal.Vector(0.0, 0.0, 500.0), + unreal.Rotator(-45.0, -35.0, 0.0), + ) + sun.set_actor_label("DemoSunLight") + sun_comp = sun.light_component + sun_comp.set_mobility(unreal.ComponentMobility.MOVABLE) + sun_comp.set_intensity(4.0) + try: + sun_comp.set_editor_property("atmosphere_sun_light", True) + except Exception: + pass + + # 3. SkyLight + sky_light = actor_sub.spawn_actor_from_class( + unreal.SkyLight, + unreal.Vector(0.0, 0.0, 600.0), + unreal.Rotator(0.0, 0.0, 0.0), + ) + sky_light.set_actor_label("DemoSkyLight") + sky_comp = sky_light.light_component + sky_comp.set_mobility(unreal.ComponentMobility.MOVABLE) + try: + sky_comp.set_editor_property("real_time_capture", True) + except Exception: + pass + + # 4. SkyAtmosphere & ExponentialHeightFog + sky_atmo = actor_sub.spawn_actor_from_class( + unreal.SkyAtmosphere, + unreal.Vector(0.0, 0.0, 0.0), + unreal.Rotator(0.0, 0.0, 0.0), + ) + sky_atmo.set_actor_label("DemoSkyAtmosphere") + + fog = actor_sub.spawn_actor_from_class( + unreal.ExponentialHeightFog, + unreal.Vector(0.0, 0.0, 0.0), + unreal.Rotator(0.0, 0.0, 0.0), + ) + fog.set_actor_label("DemoHeightFog") + + # 5. PlayerStart facing +X toward LuaDemoActor + player_start = actor_sub.spawn_actor_from_class( + unreal.PlayerStart, + unreal.Vector(-450.0, 0.0, 100.0), + unreal.Rotator(0.0, 0.0, 0.0), + ) + player_start.set_actor_label("DemoPlayerStart") + + # 6. LuaDemoActor driven by Content/Script/Game/LuaDemoActor.lua + demo_actor_class = unreal.load_class(None, "/Script/UnrealLuaDemo.LuaDemoActor") + if demo_actor_class is None: + raise RuntimeError("Could not load /Script/UnrealLuaDemo.LuaDemoActor") + + demo_actor = actor_sub.spawn_actor_from_class( + demo_actor_class, + unreal.Vector(0.0, 0.0, 140.0), + unreal.Rotator(0.0, 0.0, 0.0), + ) + demo_actor.set_actor_label("LuaDemoActor") + + # 7. Set level GameMode override to ALuaGameModeBase + world = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem).get_editor_world() + if world: + ws = world.get_world_settings() + gm_class = unreal.load_class(None, "/Script/UnrealLuaDemo.LuaGameModeBase") + if ws and gm_class: + ws.set_editor_property("default_game_mode", gm_class) + + saved = level_sub.save_current_level() + if not saved: + raise RuntimeError(f"Failed to save level {MAP_PATH}") + + unreal.log(f"[CreateDemoMap] Successfully created and saved {MAP_PATH}") + + +if __name__ == "__main__": + main() diff --git a/UnrealLuaDemo.uproject b/UnrealLuaDemo.uproject index 2e63e7c..2d6607d 100644 --- a/UnrealLuaDemo.uproject +++ b/UnrealLuaDemo.uproject @@ -21,6 +21,13 @@ "TargetAllowList": [ "Editor" ] + }, + { + "Name": "PythonScriptPlugin", + "Enabled": true, + "TargetAllowList": [ + "Editor" + ] } ] }