Files
UnrealLuaDemo/Source/UnrealLuaDemoEditor/LuaBundlePacker.cpp
T

301 lines
8.9 KiB
C++
Raw Normal View History

// Copyright Epic Games, Inc. All Rights Reserved.
#include "LuaBundlePacker.h"
#include "UnrealLuaDemoEditor.h"
#include "LuaBundle/LuaBundleAsset.h"
#include "LuaBundle/LuaScriptSettings.h"
#include "AssetRegistry/AssetRegistryModule.h"
#include "HAL/FileManager.h"
#include "Interfaces/IPluginManager.h"
#include "Misc/DateTime.h"
#include "Misc/FileHelper.h"
#include "Misc/PackageName.h"
#include "Misc/Paths.h"
#include "UObject/Package.h"
#include "UObject/SavePackage.h"
namespace
{
bool ShouldSkipRelativeLuaPath(const FString& RelativePath)
{
// Skip editor-only IntelliSense stubs and hidden directories (e.g. .git)
if (RelativePath.StartsWith(TEXT("IntelliSense/"), ESearchCase::IgnoreCase) ||
RelativePath.Contains(TEXT("/IntelliSense/"), ESearchCase::IgnoreCase))
{
return true;
}
TArray<FString> Segments;
RelativePath.ParseIntoArray(Segments, TEXT("/"), true);
for (const FString& Segment : Segments)
{
if (Segment.StartsWith(TEXT(".")))
{
return true;
}
}
return false;
}
}
void FLuaBundlePacker::CollectDirectoryLuaFiles(
const FString& RootDir,
TMap<FString, FLuaBundleSourceItem>& InOutItemsByLowerPath,
bool bAllowOverwrite)
{
if (!FPaths::DirectoryExists(RootDir))
{
return;
}
FString NormalizedRoot = FPaths::ConvertRelativePathToFull(RootDir);
FPaths::NormalizeDirectoryName(NormalizedRoot);
if (!NormalizedRoot.EndsWith(TEXT("/")))
{
NormalizedRoot += TEXT("/");
}
TArray<FString> FoundFiles;
IFileManager::Get().FindFilesRecursive(FoundFiles, *NormalizedRoot, TEXT("*.lua"), /*Files=*/true, /*Directories=*/false);
FoundFiles.Sort();
for (const FString& FilePath : FoundFiles)
{
FString NormalizedFile = FPaths::ConvertRelativePathToFull(FilePath);
FPaths::NormalizeFilename(NormalizedFile);
FString RelativePath = NormalizedFile;
if (!FPaths::MakePathRelativeTo(RelativePath, *NormalizedRoot))
{
continue;
}
RelativePath = FLuaBundleArchive::NormalizeRelativePath(RelativePath);
if (RelativePath.IsEmpty() || ShouldSkipRelativeLuaPath(RelativePath))
{
continue;
}
const FString LowerKey = RelativePath.ToLower();
if (!bAllowOverwrite && InOutItemsByLowerPath.Contains(LowerKey))
{
continue;
}
TArray<uint8> RawBytes;
if (!FFileHelper::LoadFileToArray(RawBytes, *NormalizedFile))
{
UE_LOG(LogUnrealLuaDemoEditor, Warning, TEXT("[LuaBundlePacker] Failed to read Lua file: %s"), *NormalizedFile);
continue;
}
// Strip UTF-8 BOM if present so runtime loading is consistent
if (RawBytes.Num() >= 3 && RawBytes[0] == 0xEF && RawBytes[1] == 0xBB && RawBytes[2] == 0xBF)
{
RawBytes.RemoveAt(0, 3);
}
FLuaBundleSourceItem Item;
Item.RelativePath = RelativePath;
Item.PlaintextBytes = MoveTemp(RawBytes);
InOutItemsByLowerPath.Add(LowerKey, MoveTemp(Item));
}
}
bool FLuaBundlePacker::CollectLuaSources(TArray<FLuaBundleSourceItem>& OutItems, FString& OutError)
{
OutItems.Reset();
const ULuaScriptSettings* Settings = GetDefault<ULuaScriptSettings>();
if (!Settings)
{
OutError = TEXT("ULuaScriptSettings CDO is unavailable.");
return false;
}
const FString ProjectLuaRoot = Settings->GetExternalScriptRootFullPath();
if (!FPaths::DirectoryExists(ProjectLuaRoot))
{
OutError = FString::Printf(TEXT("External Lua script root directory does not exist: %s"), *ProjectLuaRoot);
return false;
}
TMap<FString, FLuaBundleSourceItem> ItemsByLowerPath;
// 1. Collect project scripts from <ProjectDir>/Script/lua (highest priority)
CollectDirectoryLuaFiles(ProjectLuaRoot, ItemsByLowerPath, /*bAllowOverwrite=*/true);
// 2. Optionally include UnLua plugin runtime scripts (e.g. UnLua/HotReload.lua, UnLua/EnhancedInput.lua)
// without overwriting any project-provided script of the same path.
if (Settings->bIncludeUnLuaPluginScriptsInBundle)
{
if (TSharedPtr<IPlugin> UnLuaPlugin = IPluginManager::Get().FindPlugin(TEXT("UnLua")))
{
const FString PluginScriptRoot = FPaths::Combine(UnLuaPlugin->GetContentDir(), TEXT("Script"));
CollectDirectoryLuaFiles(PluginScriptRoot, ItemsByLowerPath, /*bAllowOverwrite=*/false);
}
}
if (ItemsByLowerPath.Num() == 0)
{
OutError = FString::Printf(TEXT("No .lua files found under: %s"), *ProjectLuaRoot);
return false;
}
OutItems.Reserve(ItemsByLowerPath.Num());
for (TPair<FString, FLuaBundleSourceItem>& Pair : ItemsByLowerPath)
{
OutItems.Add(MoveTemp(Pair.Value));
}
return true;
}
bool FLuaBundlePacker::PackToDefaultAsset(FLuaBundlePackResult& OutResult, TOptional<bool> bEncryptOverride)
{
const ULuaScriptSettings* Settings = GetDefault<ULuaScriptSettings>();
if (!Settings)
{
OutResult.bSuccess = false;
OutResult.ErrorMessage = TEXT("ULuaScriptSettings CDO is unavailable.");
return false;
}
return PackToAsset(Settings->LuaBundleAssetPath, OutResult, bEncryptOverride);
}
bool FLuaBundlePacker::PackToAsset(
const FSoftObjectPath& TargetAssetPath,
FLuaBundlePackResult& OutResult,
TOptional<bool> bEncryptOverride)
{
OutResult = FLuaBundlePackResult{};
const ULuaScriptSettings* Settings = GetDefault<ULuaScriptSettings>();
if (!Settings)
{
OutResult.ErrorMessage = TEXT("ULuaScriptSettings CDO is unavailable.");
return false;
}
const FString PackageName = TargetAssetPath.GetLongPackageName();
const FString AssetName = TargetAssetPath.GetAssetName();
if (PackageName.IsEmpty() || AssetName.IsEmpty())
{
OutResult.ErrorMessage = FString::Printf(TEXT("Invalid LuaBundleAssetPath: '%s'"), *TargetAssetPath.ToString());
return false;
}
TArray<FLuaBundleSourceItem> SourceItems;
if (!CollectLuaSources(SourceItems, OutResult.ErrorMessage))
{
return false;
}
const bool bEncrypt = bEncryptOverride.Get(Settings->bEncryptBundle);
TArray<uint8> ArchiveBytes;
if (!FLuaBundleArchive::Build(SourceItems, ArchiveBytes, bEncrypt, Settings->BundleEncryptionKey))
{
OutResult.ErrorMessage = TEXT("FLuaBundleArchive::Build failed.");
return false;
}
UPackage* Package = CreatePackage(*PackageName);
if (!Package)
{
OutResult.ErrorMessage = FString::Printf(TEXT("Failed to create package '%s'."), *PackageName);
return false;
}
Package->FullyLoad();
ULuaBundleAsset* BundleAsset = FindObject<ULuaBundleAsset>(Package, *AssetName);
const bool bNewlyCreated = (BundleAsset == nullptr);
if (!BundleAsset)
{
BundleAsset = NewObject<ULuaBundleAsset>(Package, *AssetName, RF_Public | RF_Standalone);
}
BundleAsset->FormatVersion = static_cast<int32>(FLuaBundleArchive::CurrentVersion);
BundleAsset->ScriptCount = SourceItems.Num();
BundleAsset->bEncrypted = bEncrypt;
BundleAsset->BuildTimestamp = FDateTime::UtcNow().ToIso8601();
BundleAsset->ArchiveBytes = MoveTemp(ArchiveBytes);
BundleAsset->InvalidateCache();
BundleAsset->MarkPackageDirty();
if (bNewlyCreated)
{
FAssetRegistryModule::AssetCreated(BundleAsset);
}
const FString PackageFilename = FPackageName::LongPackageNameToFilename(
PackageName, FPackageName::GetAssetPackageExtension());
const FString ParentDir = FPaths::GetPath(PackageFilename);
IFileManager::Get().MakeDirectory(*ParentDir, /*Tree=*/true);
FSavePackageArgs SaveArgs;
SaveArgs.TopLevelFlags = RF_Public | RF_Standalone;
SaveArgs.Error = GError;
SaveArgs.bWarnOfLongFilename = false;
const bool bSaved = UPackage::SavePackage(Package, BundleAsset, *PackageFilename, SaveArgs);
if (!bSaved)
{
OutResult.ErrorMessage = FString::Printf(TEXT("UPackage::SavePackage failed for '%s'."), *PackageFilename);
return false;
}
OutResult.bSuccess = true;
OutResult.ScriptCount = BundleAsset->ScriptCount;
OutResult.ArchiveByteSize = BundleAsset->ArchiveBytes.Num();
OutResult.bEncrypted = BundleAsset->bEncrypted;
OutResult.OutputPath = PackageFilename;
return true;
}
bool FLuaBundlePacker::PackToStandaloneFile(
const FString& OutputFilePath,
FLuaBundlePackResult& OutResult,
TOptional<bool> bEncryptOverride)
{
OutResult = FLuaBundlePackResult{};
const ULuaScriptSettings* Settings = GetDefault<ULuaScriptSettings>();
if (!Settings)
{
OutResult.ErrorMessage = TEXT("ULuaScriptSettings CDO is unavailable.");
return false;
}
TArray<FLuaBundleSourceItem> SourceItems;
if (!CollectLuaSources(SourceItems, OutResult.ErrorMessage))
{
return false;
}
const bool bEncrypt = bEncryptOverride.Get(Settings->bEncryptBundle);
TArray<uint8> ArchiveBytes;
if (!FLuaBundleArchive::Build(SourceItems, ArchiveBytes, bEncrypt, Settings->BundleEncryptionKey))
{
OutResult.ErrorMessage = TEXT("FLuaBundleArchive::Build failed.");
return false;
}
const FString FullOutputPath = FPaths::ConvertRelativePathToFull(OutputFilePath);
IFileManager::Get().MakeDirectory(*FPaths::GetPath(FullOutputPath), /*Tree=*/true);
if (!FFileHelper::SaveArrayToFile(ArchiveBytes, *FullOutputPath))
{
OutResult.ErrorMessage = FString::Printf(TEXT("Failed to save standalone Lua bundle to '%s'."), *FullOutputPath);
return false;
}
OutResult.bSuccess = true;
OutResult.ScriptCount = SourceItems.Num();
OutResult.ArchiveByteSize = ArchiveBytes.Num();
OutResult.bEncrypted = bEncrypt;
OutResult.OutputPath = FullOutputPath;
return true;
}