Files
Pal3.Unity/Assets/Scripts/Pal3.Game/Script/ScriptManager.cs
T
Jiaqi Liu d1b2c05eb4 Optimize resource loading and fix PAL3A script execution (#92)
* Optimize DDS texture creation and static POL meshes

Separate file decoding from Unity upload through format-neutral texture data
and explicit world, sprite and skybox policies. Validate DDS layouts, preserve
alpha coverage and use native BC uploads with software RGBA fallback.

Compact referenced POL vertices and batch nearby static opaque groups sharing
materials. Keep water and dynamic geometry separate, with source ranges retained
only in the Editor. Add DDS layout and POL index regression tests.

Validation: PAL3 and PAL3A each passed 24 Editor tests, eight combined Game and
ResourceViewer style regressions, 936 paired skybox comparisons, and both macOS
Player builds on Metal. Editor provenance and Core tests are excluded from Players.

* Add core protocol regression tests and copyright checks

Cover SCE command contracts, binary readers, resource layouts and full local CPK decompression for PAL3 and PAL3A. Fix CVD time rebasing, binary read bounds and short reads, and CPK/NAV validation.

Standardize first-party copyright headers, preserve correct creation years, and update console source generation. Validate both variants in Unity and verify all live CPK entries.

* Implement PAL3A command handlers and isolate script execution

Correct PAL3A parameter signatures and add handlers for fortune selection,
skybox sequences, actor facing and attacks, team and progression state,
camera constraints, and battle preparation flags.

Give script instances separate locals, advance grouped waits concurrently,
and pause PAL3A parents only for their directly decoded child calls. Cancel
stale interactions and save replay on reset, preserve finite action semantics,
and restore camera orientation after releasing horizontal constraints.

Persist supported state in v2 saves and add protocol, runtime, and progression
regressions. Full combat gameplay remains outside this change.

Validation: PAL3 274/274 and PAL3A 291/291 EditMode tests; 18 PAL3 and 22 PAL3A
runtime checks. All 77,889 PAL3A instruction boundaries match EXE signatures.

* Run CI only for pull requests and upgrade build actions
2026-11-13 09:28:31 +08:00

268 lines
10 KiB
C#

// ------------------------------------------------------------------------
// Copyright (c) 2021-2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Game.Script
{
using System;
using System.Collections.Generic;
using System.Linq;
using Command;
using Command.Extensions;
using Core.Command;
using Core.Command.SceCommands;
using Core.Contract.Constants;
using Core.DataReader.Sce;
using Core.Utilities;
using Data;
using Engine.Logging;
using Patcher;
public sealed class ScriptManager : IDisposable,
ICommandExecutor<ScriptExecuteCommand>,
ICommandExecutor<ResetGameStateCommand>
{
private readonly ISceCommandParser _sceCommandParser;
private readonly IPalScriptPatcher _scriptPatcher;
private readonly UserVariableManager _userVariableStore;
private readonly Action<ICommand> _executeCommand;
private readonly SceFile _systemSceFile;
private readonly SceFile _worldMapSceFile;
private SceFile _currentSceFile;
private readonly Queue<PalScriptRunner> _pendingScripts = new ();
private readonly List<PalScriptRunner> _runningScripts = new ();
private readonly List<PalScriptRunner> _finishedScripts = new ();
private bool _pendingSceneScriptExecution = false;
private PalScriptRunner _executingScript;
private ICommand _executingCommand;
private int _generation;
public ScriptManager(GameResourceProvider resourceProvider,
UserVariableManager userVariableStore,
ISceCommandParser sceCommandParser,
IPalScriptPatcher scriptPatcher)
: this(Requires.IsNotNull(resourceProvider, nameof(resourceProvider))
.GetGameResourceFile<SceFile>(FileConstants.SystemSceFileVirtualPath),
resourceProvider.GetGameResourceFile<SceFile>(FileConstants.WorldMapSceFileVirtualPath),
userVariableStore, sceCommandParser, scriptPatcher,
command => Pal3.Instance.Execute(command))
{
}
internal ScriptManager(SceFile systemSceFile,
SceFile worldMapSceFile,
UserVariableManager userVariableStore,
ISceCommandParser sceCommandParser,
IPalScriptPatcher scriptPatcher,
Action<ICommand> executeCommand)
{
_userVariableStore = Requires.IsNotNull(userVariableStore, nameof(userVariableStore));
_sceCommandParser = Requires.IsNotNull(sceCommandParser, nameof(sceCommandParser));
_scriptPatcher = Requires.IsNotNull(scriptPatcher, nameof(scriptPatcher));
_executeCommand = Requires.IsNotNull(executeCommand, nameof(executeCommand));
_systemSceFile = Requires.IsNotNull(systemSceFile, nameof(systemSceFile));
_worldMapSceFile = Requires.IsNotNull(worldMapSceFile, nameof(worldMapSceFile));
CommandExecutorRegistry<ICommand>.Instance.Register(this);
}
public void Dispose()
{
CommandExecutorRegistry<ICommand>.Instance.UnRegister(this);
ClearScripts();
}
public int GetNumberOfRunningScripts()
{
return _pendingScripts.Count + _runningScripts.Count;
}
public bool AddScript(uint scriptId, bool isWorldMapScript = false)
{
return TryAddScript(scriptId, isWorldMapScript, out _);
}
private bool TryAddScript(uint scriptId, bool isWorldMapScript, out PalScriptRunner scriptRunner)
{
scriptRunner = null;
if (scriptId == ScriptConstants.InvalidScriptId) return false;
if (_pendingScripts.Any(s => s.ScriptId == scriptId) ||
_runningScripts.Any(s => s.ScriptId == scriptId))
{
EngineLogger.LogError($"Script is already running: {scriptId}");
return false;
}
SceFile file;
PalScriptType type;
if (isWorldMapScript)
{
file = _worldMapSceFile;
type = PalScriptType.WorldMap;
}
else if (scriptId < ScriptConstants.SystemScriptIdMax)
{
file = _systemSceFile;
type = PalScriptType.System;
}
else
{
file = _currentSceFile;
type = PalScriptType.Scene;
}
if (file == null || !file.ScriptBlocks.ContainsKey(scriptId))
{
EngineLogger.LogError($"Script not found: {type} {scriptId}");
return false;
}
scriptRunner = PalScriptRunner.Create(file, type, scriptId,
_userVariableStore, _sceCommandParser, _scriptPatcher);
scriptRunner.OnCommandExecutionRequested += OnCommandExecutionRequested;
_pendingScripts.Enqueue(scriptRunner);
return true;
}
private void OnCommandExecutionRequested(object sender, ICommand command)
{
var script = (PalScriptRunner)sender;
var previous = _executingScript;
var previousCommand = _executingCommand;
_executingScript = script;
_executingCommand = command;
try { _userVariableStore.ExecuteInScope(script.Variables, command, _executeCommand); }
finally
{
_executingScript = previous;
_executingCommand = previousCommand;
}
}
public void Update(float deltaTime)
{
// A previous update may have been interrupted by a command/notification
// exception. Completed runners still in the running list are collected
// again below; never carry over a partially processed completion batch.
_finishedScripts.Clear();
while (_pendingScripts.Count > 0)
{
_runningScripts.Insert(0, _pendingScripts.Dequeue());
}
if (_runningScripts.Count == 0) return;
int generation = _generation;
for (int i = 0; i < _runningScripts.Count; i++)
{
PalScriptRunner script = _runningScripts[i];
bool running = script.Update(deltaTime);
// A command can reset the game during this update. All old script
// instances have been disposed; do not emit completion notifications.
if (generation != _generation) return;
if (!running)
{
_finishedScripts.Add(script);
}
}
for (int i = 0; i < _finishedScripts.Count; i++)
{
PalScriptRunner finishedScript = _finishedScripts[i];
_runningScripts.Remove(finishedScript);
finishedScript.OnCommandExecutionRequested -= OnCommandExecutionRequested;
finishedScript.Dispose();
EngineLogger.Log($"Script [{finishedScript.ScriptId} " +
$"{finishedScript.ScriptDescription}] finished running");
_executeCommand(new ScriptFinishedRunningNotification(
finishedScript.ScriptId,
finishedScript.ScriptType));
if (generation != _generation) return;
}
_finishedScripts.Clear();
// Scene script can be added during above script execution.
// Call update again to trigger the execution of the scene script.
if (_pendingSceneScriptExecution)
{
_pendingSceneScriptExecution = false;
Update(0f);
}
}
public bool TryAddSceneScript(SceFile sceFile, string sceneScriptDescription, out uint sceneScriptId)
{
sceneScriptId = ScriptConstants.InvalidScriptId;
_currentSceFile = sceFile;
foreach (KeyValuePair<uint, SceScriptBlock> scriptBlock in _currentSceFile.ScriptBlocks
.Where(scriptBlock =>
string.Equals(scriptBlock.Value.Description,
sceneScriptDescription,
StringComparison.OrdinalIgnoreCase)))
{
sceneScriptId = scriptBlock.Key;
if (!AddScript(sceneScriptId)) return false;
_pendingSceneScriptExecution = true;
// This is to break the current running script from executing and let scene script to execute first
_executeCommand(new ScriptRunnerWaitUntilTimeCommand(0f));
return true;
}
return false;
}
public void Execute(ScriptExecuteCommand command)
{
if (TryAddScript((uint)command.ScriptId, false, out PalScriptRunner child))
{
#if PAL3A
// Only the command decoded by this runner is a synchronous call.
// Object interactions may dispatch another 16 during command 124.
if (ReferenceEquals(command, _executingCommand))
_executingScript?.WaitForCalledScript(child);
#endif
}
else
{
_executeCommand(new ScriptFailedToRunNotification((uint) command.ScriptId));
}
}
public void Execute(ResetGameStateCommand command)
{
ClearScripts();
_currentSceFile = null;
}
private void ClearScripts()
{
_generation++;
_pendingSceneScriptExecution = false;
foreach (PalScriptRunner script in _pendingScripts)
{
script.OnCommandExecutionRequested -= OnCommandExecutionRequested;
script.Dispose();
}
foreach (PalScriptRunner script in _runningScripts)
{
script.OnCommandExecutionRequested -= OnCommandExecutionRequested;
script.Dispose();
}
_pendingScripts.Clear();
_runningScripts.Clear();
_finishedScripts.Clear();
}
}
}