using GFramework.Core.architecture;
using GFramework.Core.events;
using GFramework.Core.extensions;
using GFramework.Core.system;
using GFramework.Game.assets;
using Godot;
namespace GFramework.Godot.system;
///
/// 资源工厂系统抽象基类,用于统一管理各类资源的创建与预加载逻辑。
/// 提供注册场景和资源的方法,并通过依赖的资源加载系统和资产目录系统完成实际资源的获取与构造。
///
public abstract class AbstractResourceFactorySystem : AbstractSystem, IResourceFactorySystem, IArchitectureLifecycle
{
private ResourceFactory.Registry? _registry;
private IResourceLoadSystem? _resourceLoadSystem;
private IAssetCatalogSystem? _assetCatalogSystem;
///
/// 系统初始化方法,在系统启动时执行一次。
/// 初始化资源注册表,并获取依赖的资源加载系统和资产目录系统。
/// 最后执行所有已注册资源的预加载操作。
///
protected override void OnInit()
{
_registry = new ResourceFactory.Registry();
_resourceLoadSystem = this.GetSystem();
_assetCatalogSystem = this.GetSystem();
}
///
/// 架构阶段回调,在架构就绪时注册和预加载资源
///
/// 当前架构阶段
/// 架构实例
public void OnPhase(ArchitecturePhase phase, IArchitecture arch)
{
if (phase == ArchitecturePhase.Ready)
{
// 注册资源
RegisterResources();
// 预加载所有资源
_registry!.PreloadAll();
}
}
///
/// 注册系统所需的各种资源类型。由子类实现具体注册逻辑。
///
protected abstract void RegisterResources();
///
/// 根据指定的键获取资源工厂函数。
///
/// 资源类型
/// 资源键
/// 返回创建指定类型资源的工厂函数
public Func GetFactory(string key) => _registry!.ResolveFactory(key);
///
/// 根据资产目录映射信息获取资源工厂函数。
///
/// 资源类型
/// 资产目录映射信息
/// 返回创建指定类型资源的工厂函数
public Func GetFactory(AssetCatalog.AssetCatalogMapping mapping) => _registry!.ResolveFactory(mapping.Key);
#region Register Helpers(声明式)
///
/// 注册场景单元到资源管理系统中
///
/// 场景单元类型,必须继承自Node
/// 场景单元键值,用于标识特定的场景单元资源
/// 是否预加载该资源,默认为false
public void RegisterSceneUnit(
string sceneUnitKey,
bool preload = false)
where T : Node
{
var id = _assetCatalogSystem!.GetSceneUnit(sceneUnitKey);
_registry!.Register(
sceneUnitKey,
_resourceLoadSystem!.GetOrRegisterGameUnitFactory(id),
preload
);
}
///
/// 注册场景页面到资源管理系统中
///
/// 场景页面类型,必须继承自Node
/// 场景页面键值,用于标识特定的场景页面资源
/// 是否预加载该资源,默认为false
public void RegisterScenePage(
string scenePageKey,
bool preload = false)
where T : Node
{
var id = _assetCatalogSystem!.GetScenePage(scenePageKey);
_registry!.Register(
scenePageKey,
_resourceLoadSystem!.GetOrRegisterTemplateFactory(id),
preload
);
}
///
/// 注册通用资产资源到资源管理系统中
///
/// 资产类型,必须继承自Resource
/// 资产键值,用于标识特定的资产资源
/// 是否预加载该资源,默认为false
public void RegisterAsset(
string assetKey,
bool preload = false)
where T : Resource
{
var id = _assetCatalogSystem!.GetAsset(assetKey);
_registry!.Register(
assetKey,
_resourceLoadSystem!.GetOrRegisterAssetFactory(id),
preload
);
}
#endregion
}