Implement original PAL3 effects and editor with formatting checks

This commit is contained in:
Jiaqi (0x7c13) Liu committed 2026-11-14 03:46:07 +08:00
1 parent d1b2c05eb4
commit 09ef830a62
58 files changed
+5174 -124

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
root = true
[*.cs]
indent_style = space
indent_size = 4
# Match the existing Unity C# sources; keep each file's existing BOM.
end_of_line = crlf
insert_final_newline = true
trim_trailing_whitespace = true
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_members_in_anonymous_types = true
csharp_new_line_between_query_expression_clauses = true
csharp_indent_block_contents = true
csharp_indent_braces = false
csharp_indent_case_contents = true
csharp_indent_case_contents_when_block = false
csharp_indent_switch_labels = true
csharp_indent_labels = one_less_than_current
csharp_space_after_cast = false
csharp_space_after_keywords_in_control_flow_statements = true
csharp_space_between_method_declaration_parameter_list_parentheses = false
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
csharp_space_between_method_call_parameter_list_parentheses = false
csharp_space_between_method_call_empty_parameter_list_parentheses = false
csharp_space_between_parentheses = none
csharp_space_before_colon_in_inheritance_clause = true
csharp_space_after_colon_in_inheritance_clause = true
csharp_space_around_binary_operators = before_and_after
csharp_space_before_comma = false
csharp_space_after_comma = true
csharp_space_before_dot = false
csharp_space_after_dot = false
csharp_space_before_semicolon_in_for_statement = false
csharp_space_after_semicolon_in_for_statement = true
csharp_space_before_open_square_brackets = false
csharp_space_between_square_brackets = false
csharp_space_between_empty_square_brackets = false
csharp_preserve_single_line_statements = false
csharp_preserve_single_line_blocks = false
# SDK whitespace formatting does not enforce spacing between members.
# These targeted StyleCop rules also run through tools/format-csharp.py.
dotnet_diagnostic.SA1107.severity = warning
dotnet_diagnostic.SA1502.severity = warning
dotnet_diagnostic.SA1507.severity = warning
dotnet_diagnostic.SA1516.severity = warning
+11
View File
@@ -6,6 +6,17 @@ macOS, Linux, and 32-bit/64-bit Windows. The workflows run only on pull requests
New commits cancel superseded runs for the same pull request and workflow.
Successful desktop/Android builds upload artifacts.
The separate `Code style` workflow verifies changed owned C# files with the SDK's
`dotnet format`, using `.editorconfig` and the SDK pinned in `global.json`.
It combines whitespace formatting with pinned StyleCop layout rules SA1107, SA1502,
SA1507 and SA1516 to enforce separate statements, multiline blocks and blank lines
between members. StyleCop is restored only into the temporary formatting project.
It parses both PAL3 and PAL3A conditional branches without Unity, game data or private
assets. Run `python3 tools/format-csharp.py` locally to format current changes, then
`python3 tools/format-csharp.py --check` to verify them. CI selects PR changes with
`--check --base <base-sha>`; `--all` is an explicit full-source audit, not the default.
This checks whitespace and layout, not semantic correctness or Unity behavior.
Codacy is not part of this repository's CI. Its repository webhook is disabled;
there is no Codacy workflow or Codacy-required branch protection check. Re-enabling
that external integration would resume its checks independently of these workflows.
+29
View File
@@ -0,0 +1,29 @@
name: Code style
on:
pull_request:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
csharp-format:
name: C# formatting (PAL3 and PAL3A)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7.0.1
with:
fetch-depth: 0
- uses: actions/setup-dotnet@v5.3.0
with:
global-json-file: global.json
- name: Test formatter enforcement
run: python3 tools/tests/test-format-csharp.py
- name: Verify changed C# formatting
env:
BASE_REF: ${{ github.event.pull_request.base.sha }}
run: python3 tools/format-csharp.py --check --base "$BASE_REF"
@@ -0,0 +1,77 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
Shader "Pal3/OriginalEffect"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
[Enum(UnityEngine.Rendering.BlendMode)] _SrcBlend ("Source blend", Float) = 1
[Enum(UnityEngine.Rendering.BlendMode)] _DstBlend ("Destination blend", Float) = 1
[Enum(UnityEngine.Rendering.CompareFunction)] _ZTest ("Depth test", Float) = 4
_AlphaMode ("Original alpha operation", Float) = 0
}
SubShader
{
Tags
{
"RenderPipeline" = "UniversalPipeline"
"Queue" = "Transparent"
"RenderType" = "Transparent"
}
Pass
{
Tags { "LightMode" = "SRPDefaultUnlit" }
Blend [_SrcBlend] [_DstBlend]
ZTest [_ZTest]
ZWrite Off
Cull Off
HLSLPROGRAM
#pragma vertex Vert
#pragma fragment Frag
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
struct Attributes
{
float3 positionOS : POSITION;
float2 uv : TEXCOORD0;
half4 color : COLOR;
};
struct Varyings
{
float4 positionCS : SV_POSITION;
float2 uv : TEXCOORD0;
half4 color : COLOR;
};
TEXTURE2D(_MainTex);
SAMPLER(sampler_MainTex);
CBUFFER_START(UnityPerMaterial)
float _AlphaMode;
CBUFFER_END
Varyings Vert(Attributes i)
{
Varyings o;
o.positionCS = TransformObjectToHClip(i.positionOS);
o.uv = i.uv;
o.color = i.color;
return o;
}
half4 Frag(Varyings i) : SV_Target
{
half4 tex = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.uv);
half4 col = tex * i.color;
if (_AlphaMode > 1.5)
{
col.a = tex.a;
}
else if (_AlphaMode > 0.5)
{
col.a = saturate(tex.a + i.color.a);
}
return col;
}
ENDHLSL
}
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: dd7af60dc97334317a8bf7d560ba0f71
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,680 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Editor
{
using System;
using System.IO;
using System.Linq;
using Pal3.Core.DataReader.Cpk;
using Pal3.Core.DataReader.Data;
using Pal3.Core.DataReader.Par;
using Pal3.Core.FileSystem;
using Pal3.Game.Effect.Original;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
using UnityEngine.SceneManagement;
using UnityEngine.UIElements;
public sealed class OriginalEffectEditor : EditorWindow
{
private OriginalEffectResources _resources;
private OriginalEffectPlayer _player;
private OriginalPortalEffect _portal;
[SerializeField] private OriginalEffectOverrides _edits;
[SerializeField] private string _assetPath = "", _savedJson;
private GameObject _root, _private;
private Scene _scene;
private Camera _camera;
private RenderTexture _target, _privateTarget;
private string _dataPath, _search = "", _error;
private int _codepage = 936;
[SerializeField] private int _id = 98, _objectIndex;
private Vector2 _listScroll, _inspectorScroll, _orbit = new(135, 15);
private float _distance = 14, _speed = 1, _duration = 15;
[SerializeField] private float _time;
private bool _playing, _compare, _loop;
private uint _seed = 1;
private bool _emitterCurve;
private int _particleIndex, _curveIndex;
private double _lastUpdate;
private string _previewJson;
private float? _pendingSeek;
private double _seekAfter;
[MenuItem("PAL3/Original Effect Editor")]
public static void Open() => GetWindow<OriginalEffectEditor>("PAL3 Effects");
public void CreateGUI() => rootVisualElement.Add(new IMGUIContainer(DrawWindow) { style = { flexGrow = 1 } });
private void OnEnable()
{
minSize = new Vector2(1050, 640);
_dataPath = EditorPrefs.GetString("PAL3.OriginalEffect.DataPath", Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data/PAL3")));
_codepage = EditorPrefs.GetInt("PAL3.OriginalEffect.Codepage", 936) == 950 ? 950 : 936;
if (_edits == null)
LoadOverrides(Resources.Load<OriginalEffectOverrides>("Effects/PAL3Overrides"));
_edits.hideFlags = HideFlags.HideInHierarchy | HideFlags.DontSave;
saveChangesMessage = "Save the original effect overrides before closing?";
_scene = EditorSceneManager.NewPreviewScene();
var cameraObject = new GameObject("Effect preview camera") { hideFlags = HideFlags.HideAndDontSave };
SceneManager.MoveGameObjectToScene(cameraObject, _scene);
_camera = cameraObject.AddComponent<Camera>();
_camera.enabled = false;
_camera.clearFlags = CameraClearFlags.SolidColor;
_camera.backgroundColor = new Color(0.07f, 0.08f, 0.1f);
_camera.fieldOfView = 40;
_camera.nearClipPlane = 0.01f;
_camera.farClipPlane = 500;
_camera.scene = _scene;
_lastUpdate = EditorApplication.timeSinceStartup;
EditorApplication.update += Tick;
Undo.undoRedoPerformed += RefreshAfterUndo;
if (Directory.Exists(_dataPath))
LoadData();
}
private void OnDisable()
{
EditorApplication.update -= Tick;
Undo.undoRedoPerformed -= RefreshAfterUndo;
ClearPreview();
_resources?.Dispose();
_resources = null;
if (_target != null)
{
_target.Release();
DestroyImmediate(_target);
}
if (_privateTarget != null)
{
_privateTarget.Release();
DestroyImmediate(_privateTarget);
}
if (_scene.IsValid())
EditorSceneManager.ClosePreviewScene(_scene);
}
private void OnDestroy()
{
if (_edits != null)
{
Undo.ClearUndo(_edits);
DestroyImmediate(_edits);
}
}
private void LoadOverrides(OriginalEffectOverrides asset)
{
if (_edits != null)
{
Undo.ClearUndo(_edits);
DestroyImmediate(_edits);
}
_edits = asset != null ? Instantiate(asset) : CreateInstance<OriginalEffectOverrides>();
_edits.hideFlags = HideFlags.HideInHierarchy | HideFlags.DontSave;
_assetPath = asset != null ? AssetDatabase.GetAssetPath(asset) : "";
_savedJson = JsonUtility.ToJson(_edits);
hasUnsavedChanges = false;
}
private void MarkChanged() => hasUnsavedChanges = JsonUtility.ToJson(_edits) != _savedJson;
public override void SaveChanges()
{
if (SaveOverrides())
base.SaveChanges();
}
public override void DiscardChanges()
{
LoadOverrides(_assetPath.Length > 0 ? AssetDatabase.LoadAssetAtPath<OriginalEffectOverrides>(_assetPath) : null);
base.DiscardChanges();
RefreshAfterUndo();
}
private bool CanReplaceEdits()
{
if (!hasUnsavedChanges)
return true;
int choice = EditorUtility.DisplayDialogComplex("Original effect overrides", "Save your current edits before loading another asset?", "Save", "Cancel", "Discard");
return choice == 2 || choice == 0 && SaveOverrides();
}
private bool SaveOverrides()
{
string path = EditorUtility.SaveFilePanelInProject("Save PAL3 effect overrides",
_assetPath.Length > 0 ? Path.GetFileNameWithoutExtension(_assetPath) : "PAL3Overrides", "asset",
"Use Assets/Resources/Effects/PAL3Overrides.asset for runtime loading.");
if (path.Length == 0)
return false;
var existing = AssetDatabase.LoadMainAssetAtPath(path);
if (existing != null && existing is not OriginalEffectOverrides)
{
_error = "Choose an OriginalEffectOverrides asset or a new path.";
return false;
}
var saved = existing as OriginalEffectOverrides;
if (saved != null)
{
Undo.RecordObject(saved, "Save PAL3 effect overrides");
EditorUtility.CopySerialized(_edits, saved);
saved.hideFlags = HideFlags.None;
EditorUtility.SetDirty(saved);
}
else
{
saved = Instantiate(_edits);
saved.hideFlags = HideFlags.None;
AssetDatabase.CreateAsset(saved, path);
}
saved.name = Path.GetFileNameWithoutExtension(path);
EditorUtility.SetDirty(saved);
AssetDatabase.SaveAssets();
_assetPath = path;
_savedJson = JsonUtility.ToJson(_edits);
hasUnsavedChanges = false;
return true;
}
private void LoadData()
{
float time = _time;
ClearPreview();
_resources?.Dispose();
_resources = null;
_error = null;
try
{
var hash = new Crc32Hash();
hash.Init();
var fs = new CpkFileSystem(_dataPath, hash, _codepage);
fs.Mount("basedata/basedata.cpk", _codepage);
_resources = new OriginalEffectResources(fs, _codepage);
_ = _resources.Definitions;
EditorPrefs.SetString("PAL3.OriginalEffect.DataPath", _dataPath);
Restart();
Seek(time);
}
catch (Exception ex)
{
_resources?.Dispose();
_resources = null;
_error = ex.ToString();
}
}
private void ClearPreview()
{
if (_root != null)
DestroyImmediate(_root);
if (_private != null)
DestroyImmediate(_private);
_player = null;
_portal = null;
}
private void Restart()
{
ClearPreview();
_time = 0;
_pendingSeek = null;
_error = null;
_previewJson = JsonUtility.ToJson(_edits);
if (_resources == null)
return;
try
{
_root = new GameObject("Original effect preview") { hideFlags = HideFlags.HideAndDontSave };
SceneManager.MoveGameObjectToScene(_root, _scene);
if (_id < 0)
{
_portal = _root.AddComponent<OriginalPortalEffect>();
_portal.AutoAdvance = false;
_portal.Initialize(_resources);
}
else
{
string[] issues = _resources.Diagnose(_id, _edits);
if (issues.Length > 0)
_error = string.Join("\n", issues);
else
{
_player = _root.AddComponent<OriginalEffectPlayer>();
_player.AutoAdvance = false;
_player.Initialize(_resources, _id, _seed, _edits);
_player.Loop = false;
if (_player.Error != null)
_error = _player.Error;
}
}
if (_compare)
{
GameObject prefab = Resources.Load<GameObject>($"Prefabs/VFX/PAL3/{(_id < 0 ? 0 : _id)}");
if (prefab != null)
{
_private = Instantiate(prefab);
SceneManager.MoveGameObjectToScene(_private, _scene);
foreach (Transform child in _private.GetComponentsInChildren<Transform>(true))
child.gameObject.hideFlags = HideFlags.HideAndDontSave;
foreach (ParticleSystem system in _private.GetComponentsInChildren<ParticleSystem>(true))
{
system.useAutoRandomSeed = false;
system.randomSeed = _seed;
system.Simulate(0, false, true, true);
}
}
}
}
catch (Exception ex)
{
ClearPreview();
_error = ex.ToString();
}
}
private void Tick()
{
double now = EditorApplication.timeSinceStartup;
float dt = Mathf.Min(0.1f, (float)(now - _lastUpdate));
_lastUpdate = now;
if (_pendingSeek.HasValue && now >= _seekAfter)
{
Seek(_pendingSeek.Value);
Repaint();
}
if (_playing)
{
Advance(dt * _speed);
if (_time >= _duration)
{
if (_loop)
Restart();
else
_playing = false;
}
Repaint();
}
}
private void Advance(float delta)
{
_time += delta;
_player?.Advance(delta);
_portal?.Sample(_time);
if (_private != null)
foreach (ParticleSystem ps in _private.GetComponentsInChildren<ParticleSystem>(true))
ps.Simulate(delta, false, false, true);
}
private void Seek(float time)
{
_pendingSeek = null;
_time = time;
_player?.Seek(time);
_portal?.Sample(time);
if (_private != null)
foreach (ParticleSystem ps in _private.GetComponentsInChildren<ParticleSystem>(true))
ps.Simulate(time, false, true, true);
}
private void QueueSeek(float time)
{
_playing = false;
_pendingSeek = time;
_seekAfter = EditorApplication.timeSinceStartup + 0.05;
Repaint();
}
private void RefreshAfterUndo()
{
MarkChanged();
if (_previewJson == JsonUtility.ToJson(_edits))
return;
float time = _time;
Restart();
Seek(time);
Repaint();
}
private void DrawWindow()
{
using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar))
{
EditorGUILayout.LabelField("PAL3 data", GUILayout.Width(65));
_dataPath = EditorGUILayout.TextField(_dataPath);
int codepage = EditorGUILayout.Popup(_codepage == 950 ? 1 : 0, new[] { "GBK (936)", "Big5 (950)" }, GUILayout.Width(105)) == 0 ? 936 : 950;
if (codepage != _codepage)
{
_codepage = codepage;
EditorPrefs.SetInt("PAL3.OriginalEffect.Codepage", _codepage);
LoadData();
}
if (GUILayout.Button("Browse", EditorStyles.toolbarButton, GUILayout.Width(60)))
{
string path = EditorUtility.OpenFolderPanel("PAL3 data (contains basedata)", _dataPath, "");
if (path.Length > 0)
{
_dataPath = path;
LoadData();
}
}
if (GUILayout.Button("Reload", EditorStyles.toolbarButton, GUILayout.Width(55)))
LoadData();
}
var asset = _assetPath.Length > 0 ? AssetDatabase.LoadAssetAtPath<OriginalEffectOverrides>(_assetPath) : null;
var selected = (OriginalEffectOverrides)EditorGUILayout.ObjectField("Overrides", asset, typeof(OriginalEffectOverrides), false);
if (selected != asset && CanReplaceEdits())
{
LoadOverrides(selected);
Restart();
}
if (_resources == null)
{
EditorGUILayout.HelpBox(_error ?? "Choose the PAL3 game data directory.", MessageType.Info);
return;
}
using (new EditorGUILayout.HorizontalScope())
{
using (new EditorGUILayout.VerticalScope(GUILayout.Width(185)))
{
_search = EditorGUILayout.TextField(_search, EditorStyles.toolbarSearchField);
_listScroll = EditorGUILayout.BeginScrollView(_listScroll);
if (GUILayout.Button("Scene: Transport point"))
Select(-1);
for (int id = 0; id < _resources.Definitions.Groups.Length; id++)
{
EffectGroup g = _resources.Definitions.Groups[id];
if (g.Objects.Length == 0)
continue;
string label = $"{id} ({g.Objects.Length})";
if (_search.Length > 0 && !label.Contains(_search) && !g.Objects.Any(o => _resources.Definitions.TryGetType(o.TypeCrc, out var d) && d.TypeName.Contains(_search)))
continue;
if (GUILayout.Toggle(_id == id, label, "Button") && _id != id)
Select(id);
}
EditorGUILayout.EndScrollView();
}
using (new EditorGUILayout.VerticalScope())
{
using (new EditorGUILayout.HorizontalScope())
{
if (GUILayout.Button(_playing ? "Pause" : "Play", GUILayout.Width(60)))
_playing = !_playing;
if (GUILayout.Button("Reset", GUILayout.Width(55)))
Restart();
if (GUILayout.Button("Step", GUILayout.Width(50)))
{
_playing = false;
Advance(OriginalEffectPlayer.FixedStep);
Repaint();
}
GUILayout.Label("Speed", GUILayout.Width(40));
_speed = EditorGUILayout.FloatField(_speed, GUILayout.Width(45));
_speed = float.IsFinite(_speed) ? Mathf.Clamp(_speed, 0, 16) : 1;
_loop = GUILayout.Toggle(_loop, "Loop");
bool compare = GUILayout.Toggle(_compare, "Private comparison");
if (compare != _compare)
{
_compare = compare;
Restart();
}
}
Rect preview = GUILayoutUtility.GetRect(200, 200, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
DrawPreview(preview);
float displayedTime = _pendingSeek ?? _time;
float time = EditorGUILayout.Slider("Time", displayedTime, 0, _duration);
if (Mathf.Abs(time - displayedTime) > 0.00001f)
QueueSeek(time);
using (new EditorGUILayout.HorizontalScope())
{
_duration = EditorGUILayout.FloatField("Preview duration", _duration);
_duration = float.IsFinite(_duration) ? Mathf.Clamp(_duration, 0.1f, 600) : 15;
uint seed = (uint)Mathf.Max(1, EditorGUILayout.IntField("Seed", (int)_seed));
if (seed != _seed)
{
_seed = seed;
Restart();
}
}
EditorGUILayout.LabelField($"Original nodes: {_player?.NodeCount ?? 0} Quads/particles: {_player?.QuadCount ?? 0} {_player?.Error}");
EditorGUILayout.LabelField("Drag to orbit · Scroll to zoom", EditorStyles.miniLabel);
if (_error != null)
EditorGUILayout.HelpBox(_error, MessageType.Warning);
}
using (new EditorGUILayout.VerticalScope(GUILayout.Width(310)))
DrawInspector();
}
}
private void Select(int id)
{
_id = id;
_objectIndex = 0;
Restart();
}
private void DrawPreview(Rect rect)
{
Event e = Event.current;
if (rect.Contains(e.mousePosition))
{
if (e.type == EventType.MouseDrag && e.button == 0)
{
_orbit += e.delta * new Vector2(0.5f, -0.5f);
e.Use();
Repaint();
}
if (e.type == EventType.ScrollWheel)
{
_distance = Mathf.Clamp(_distance * Mathf.Exp(e.delta.y * 0.08f), 0.3f, 200);
e.Use();
Repaint();
}
}
if (e.type != EventType.Repaint || rect.width < 1 || rect.height < 1)
return;
int w = Mathf.Max(1, (int)(rect.width / (_compare ? 2 : 1))), h = Mathf.Max(1, (int)rect.height);
if (_target == null || _target.width != w || _target.height != h)
{
if (_target != null)
{
_target.Release();
DestroyImmediate(_target);
}
if (_privateTarget != null)
{
_privateTarget.Release();
DestroyImmediate(_privateTarget);
}
_target = new RenderTexture(w, h, 24) { hideFlags = HideFlags.HideAndDontSave };
_target.Create();
_privateTarget = new RenderTexture(w, h, 24) { hideFlags = HideFlags.HideAndDontSave };
_privateTarget.Create();
}
_camera.transform.position = Quaternion.Euler(_orbit.y, _orbit.x, 0) * new Vector3(0, 0, -_distance) + Vector3.up * 1.5f;
_camera.transform.LookAt(Vector3.up * 1.5f);
_camera.aspect = (float)w / h;
_player?.Render(_camera);
void Draw(RenderTexture destination, GameObject hidden, Rect area, string label)
{
Renderer[] rs = hidden == null ? Array.Empty<Renderer>() : hidden.GetComponentsInChildren<Renderer>();
bool[] state = rs.Select(r => r.enabled).ToArray();
for (int i = 0; i < rs.Length; i++)
rs[i].enabled = false;
try
{
RenderPipeline.SubmitRenderRequest(_camera, new UniversalRenderPipeline.SingleCameraRequest { destination = destination });
GUI.DrawTexture(area, destination, ScaleMode.StretchToFill, false);
GUI.Label(new Rect(area.x + 8, area.y + 8, area.width - 16, 25), label, EditorStyles.whiteBoldLabel);
}
finally
{
for (int i = 0; i < rs.Length; i++)
if (rs[i] != null)
rs[i].enabled = state[i];
}
}
Draw(_target, _private, new Rect(rect.x, rect.y, w, h), "Original PAL3 data");
if (_compare)
Draw(_privateTarget, _root, new Rect(rect.x + w, rect.y, w, h), _private != null ? "Private prefab (comparison only)" : "No private prefab");
}
private void DrawInspector()
{
EditorGUILayout.LabelField("Original object / task parameters", EditorStyles.boldLabel);
if (_id < 0)
{
EditorGUILayout.HelpBox("MXTransport: original two cones and rotating plane. This is separate from flexeff group 0.", MessageType.Info);
return;
}
EffectGroup group = _resources.Definitions.Groups[_id];
if (group.Objects.Length == 0)
return;
_objectIndex = EditorGUILayout.IntSlider("Object", _objectIndex, 0, group.Objects.Length - 1);
EffectGroupObject source = group.Objects[_objectIndex];
_resources.Definitions.TryGetType(source.TypeCrc, out EffectDefinition d);
EditorGUILayout.LabelField($"{d.TypeName} / {EffectClass.Name(d.ClassNameCrc)}");
EditorGUILayout.SelectableLabel(d.TextureName ?? "", GUILayout.Height(35));
OriginalEffectObjectOverride edit = _edits.Find(_id, _objectIndex);
if (edit == null && GUILayout.Button("Edit this object"))
{
Undo.RecordObject(_edits, "Edit original effect");
edit = new OriginalEffectObjectOverride
{
GroupId = _id,
ObjectIndex = _objectIndex,
Definition = JsonUtility.FromJson<EffectDefinition>(JsonUtility.ToJson(d)),
Tasks = source.Tasks.Select(t => JsonUtility.FromJson<EffectTask>(JsonUtility.ToJson(t))).ToArray()
};
_edits.Objects.Add(edit);
MarkChanged();
}
_inspectorScroll = EditorGUILayout.BeginScrollView(_inspectorScroll);
if (edit != null)
{
var so = new SerializedObject(_edits);
so.Update();
SerializedProperty entry = so.FindProperty("Objects").GetArrayElementAtIndex(_edits.Objects.IndexOf(edit));
EditorGUILayout.PropertyField(entry.FindPropertyRelative("Hidden"));
EditorGUILayout.PropertyField(entry.FindPropertyRelative("Definition"), true);
EditorGUILayout.PropertyField(entry.FindPropertyRelative("Tasks"), true);
if (so.ApplyModifiedProperties())
{
MarkChanged();
float time = _time;
Restart();
Seek(time);
}
}
else
foreach (EffectTask t in source.Tasks)
EditorGUILayout.LabelField($"{t.StartTime:0.###}s + {t.Duration:0.###}s loops={t.RequireLoops}");
EffectDefinition effective = edit?.Definition ?? d;
if (EffectClass.Name(effective.ClassNameCrc) == "particle")
DrawParticleCurves(effective.ParticleFileName);
EditorGUILayout.EndScrollView();
if (GUILayout.Button("Save overrides for game…"))
SaveOverrides();
if (GUILayout.Button("Discard edits for this object") && edit != null)
{
Undo.RecordObject(_edits, "Discard original effect override");
_edits.Objects.Remove(edit);
MarkChanged();
Restart();
}
}
private void DrawParticleCurves(string path)
{
EditorGUILayout.Space();
EditorGUILayout.LabelField("Particle resource curves", EditorStyles.boldLabel);
ParticleFile file;
try
{
file = _resources.Particle(path);
}
catch (Exception ex)
{
EditorGUILayout.HelpBox(ex.Message, MessageType.Warning);
return;
}
_emitterCurve = EditorGUILayout.Toggle("Emitter curves", _emitterCurve);
int count = _emitterCurve ? file.Emitters.Length : file.Particles.Length;
if (count == 0)
return;
_particleIndex = EditorGUILayout.IntSlider("Resource index", _particleIndex, 0, count - 1);
string[] names = _emitterCurve ? new[] { "Direction", "RandomVelocity", "Emission", "Life" } : new[] { "Size", "Rotation", "Alpha", "Color" };
_curveIndex = EditorGUILayout.Popup("Curve", Mathf.Clamp(_curveIndex, 0, names.Length - 1), names);
string name = names[_curveIndex];
ParticleCurve source = OriginalEffectOverrides.FindCurve(file, _emitterCurve, _particleIndex, name);
var entry = _edits.ParticleCurves.Find(c => string.Equals(c.File, path, StringComparison.OrdinalIgnoreCase)
&& c.Emitter == _emitterCurve && c.Index == _particleIndex && c.Parameter == name);
bool validEntry = entry == null || entry.Channels != null && entry.Channels.Length == source.Channels && entry.Channels.All(c => c != null);
if (!validEntry)
EditorGUILayout.HelpBox("This curve override has invalid channels. Restore the original curve to repair it.", MessageType.Warning);
for (int channel = 0; channel < source.Channels; channel++)
{
if (!validEntry)
break;
AnimationCurve curve = entry != null ? CopyCurve(entry.Channels[channel]) : SampleCurve(source, channel);
EditorGUI.BeginChangeCheck();
AnimationCurve changed = EditorGUILayout.CurveField($"Channel {channel}", curve);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(_edits, "Edit particle curve");
if (entry == null)
{
entry = new OriginalParticleCurveOverride
{
File = path,
Parameter = name,
Index = _particleIndex,
Emitter = _emitterCurve,
Channels = Enumerable.Range(0, source.Channels).Select(c => SampleCurve(source, c)).ToArray()
};
_edits.ParticleCurves.Add(entry);
}
entry.Channels[channel] = CopyCurve(changed);
MarkChanged();
float time = _time;
Restart();
Seek(time);
}
}
EditorGUILayout.LabelField(entry == null ? "Original sampled curve (unchanged)" : "Unity curve override for this particle resource", EditorStyles.wordWrappedMiniLabel);
if (entry != null && GUILayout.Button("Restore original particle curve"))
{
Undo.RecordObject(_edits, "Restore particle curve");
_edits.ParticleCurves.Remove(entry);
MarkChanged();
float time = _time;
Restart();
Seek(time);
}
}
private static AnimationCurve CopyCurve(AnimationCurve curve) =>
new(curve.keys)
{
preWrapMode = curve.preWrapMode,
postWrapMode = curve.postWrapMode
};
private static AnimationCurve SampleCurve(ParticleCurve source, int channel)
{
var curve = new AnimationCurve(Enumerable.Range(0, 101).Select(i => new Keyframe(i / 100f, source.Evaluate(i / 100f, channel))).ToArray());
for (int i = 0; i < curve.length; i++)
{
AnimationUtility.SetKeyLeftTangentMode(curve, i, AnimationUtility.TangentMode.Linear);
AnimationUtility.SetKeyRightTangentMode(curve, i, AnimationUtility.TangentMode.Linear);
}
return curve;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 28e20becd27fe4cc3b3151897935cd30
@@ -11,8 +11,16 @@ namespace Engine.Extensions
{
if (obj != null)
{
#if UNITY_EDITOR
// Model renderers are also used in isolated editor preview scenes.
if (!UnityEngine.Application.isPlaying)
{
UnityEngine.Object.DestroyImmediate(obj);
return;
}
#endif
UnityEngine.Object.Destroy(obj);
}
}
}
}
}
@@ -7,7 +7,6 @@
* @note Uses unsafe/fixed pointer contexts internally
* @liscence Bound by same liscence as minilzo as below, see file COPYING
*/
/* Based on minilzo.c -- mini subset of the LZO real-time data compression library
This file is part of the LZO real-time data compression library.
@@ -58,9 +57,16 @@ namespace Pal3.Core.DataReader.Cpk.Lzo
{
private const uint M2_MAX_OFFSET = 0x0800;
public static unsafe void Decompress(Span<byte> src, byte[] dst)
public static void Decompress(Span<byte> src, byte[] dst) => DecompressInternal(src, dst, false);
// Some PAL3 flexeff files retain a complete LZO stream followed by unused
// bytes in a fixed-size file. Keep ordinary CPK decompression strict.
public static int DecompressPrefix(Span<byte> src, byte[] dst) => DecompressInternal(src, dst, true);
private static unsafe int DecompressInternal(Span<byte> src, byte[] dst, bool allowTrailingBytes)
{
if (src.Length < 3) throw new OverflowException("Input Overrun");
if (src.Length < 3)
throw new OverflowException("Input Overrun");
uint t = 0;
fixed (byte* input = src, output = dst)
{
@@ -276,7 +282,7 @@ namespace Pal3.Core.DataReader.Cpk.Lzo
} while (--t > 0);
}
}
else if(!eof_found && !match_done)
else if (!eof_found && !match_done)
{
copy_match = false;
@@ -320,13 +326,15 @@ namespace Pal3.Core.DataReader.Cpk.Lzo
throw new OverflowException("EOF Marker Not Found");
else
{
if (op != op_end) throw new OverflowException("Output Length Mismatch");
if (op != op_end)
throw new OverflowException("Output Length Mismatch");
//Debug.Assert(t == 1);
if (ip > ip_end)
throw new OverflowException("Input Overrun");
else if (ip < ip_end)
else if (ip < ip_end && !allowTrailingBytes)
throw new OverflowException("Input Not Consumed");
}
return checked((int)(ip - input));
}
}
}
@@ -8,6 +8,7 @@ namespace Pal3.Core.DataReader.Data
//using System.Runtime.InteropServices;
//[StructLayout(LayoutKind.Explicit)]
[System.Serializable]
public struct EffectDefinition
{
//[FieldOffset(0)]
@@ -55,7 +56,7 @@ namespace Pal3.Core.DataReader.Data
public float InitAngle;
//[FieldOffset(200)]
public int InitSize;
public float InitSize;
//[FieldOffset(204)]
public uint InitColor;
@@ -124,11 +125,27 @@ namespace Pal3.Core.DataReader.Data
public sealed class EffectDefinitionFile
{
public EffectDefinitionFile(EffectDefinition[] effectDefinitions)
private readonly System.Collections.Generic.Dictionary<uint, EffectDefinition> _types = new();
public EffectDefinitionFile(EffectDefinition[] effectDefinitions, EffectGroup[] groups = null)
{
EffectDefinitions = effectDefinitions;
Groups = groups ?? System.Array.Empty<EffectGroup>();
foreach (EffectDefinition definition in effectDefinitions)
if (definition.IsValid && !_types.ContainsKey(definition.TypeNameCrc))
_types.Add(definition.TypeNameCrc, definition);
}
public EffectDefinition[] EffectDefinitions { get; }
public EffectDefinition[] EffectDefinitions
{
get;
}
public EffectGroup[] Groups
{
get;
}
public bool TryGetType(uint crc, out EffectDefinition definition) => _types.TryGetValue(crc, out definition);
}
}
}
@@ -5,22 +5,142 @@
namespace Pal3.Core.DataReader.Data
{
using System;
public sealed class EffectDefinitionFileReader : IFileReader<EffectDefinitionFile>
{
private const int NUM_OF_EFFECTS = 1324;
public const int Pal3Size = 1324 * 280 + 560 * 15940;
public const int Pal3ASize = 2048 * 280 + 1024 * 15940;
public EffectDefinitionFile Read(IBinaryReader reader, int codepage)
{
EffectDefinition[] effectDefinitions = new EffectDefinition[NUM_OF_EFFECTS];
for (int i = 0; i < NUM_OF_EFFECTS; i++)
byte[] bytes = reader.ReadExactly(checked((int)(reader.Length - reader.Position)));
// Validate the layout before accepting an unwrapped file. The shipped
// PAL3 sample is a padded LZO stream with the same length as the table.
if (bytes.Length == Pal3Size || bytes.Length == Pal3ASize)
{
effectDefinitions[i] = ReadEffectDefinition(reader, codepage);
}
try
{
return ReadPayload(bytes, codepage);
}
catch (System.IO.InvalidDataException)
{
return new EffectDefinitionFile(effectDefinitions);
}
var decoded = new byte[bytes.Length];
Cpk.Lzo.MiniLzo.DecompressPrefix(bytes, decoded);
return ReadPayload(decoded, codepage);
}
if (bytes.Length >= 7)
{
int size = bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24;
if (size == Pal3Size || size == Pal3ASize)
{
var decoded = new byte[size];
Cpk.Lzo.MiniLzo.Decompress(bytes.AsSpan(4), decoded);
return ReadPayload(decoded, codepage);
}
}
throw new System.IO.InvalidDataException("Unrecognized flexeff table layout or compression wrapper");
}
private EffectDefinitionFile ReadPayload(byte[] bytes, int codepage)
{
int typeCount = bytes.Length == Pal3Size ? 1324 : 2048;
int groupCount = bytes.Length == Pal3Size ? 560 : 1024;
using IBinaryReader reader = new SafeBinaryReader(bytes);
var definitions = new EffectDefinition[typeCount];
for (int i = 0; i < typeCount; i++)
{
// Invalid slots may contain uninitialized native bytes.
long offset = reader.Position;
reader.Seek(offset + 212, System.IO.SeekOrigin.Begin);
byte valid = reader.ReadByte();
if (valid > 1)
throw new System.IO.InvalidDataException($"Invalid effect type flag at {i}");
reader.Seek(offset, System.IO.SeekOrigin.Begin);
definitions[i] = ReadEffectDefinition(reader, codepage);
if (valid == 1 && (float.IsNaN(definitions[i].InitSize) || float.IsInfinity(definitions[i].InitSize)))
throw new System.IO.InvalidDataException($"Invalid effect size at {i}");
}
var groups = new EffectGroup[groupCount];
for (int g = 0; g < groupCount; g++)
{
int count = reader.ReadInt32();
if (count < 0 || count > 16)
throw new System.IO.InvalidDataException($"Invalid effect group size at {g}");
uint[] crcs = reader.ReadUInt32s(16);
var objects = new EffectGroupObject[count];
for (int o = 0; o < 16; o++)
{
var tasks = new System.Collections.Generic.List<EffectTask>();
for (int t = 0; t < 8; t++)
{
if (o >= count)
{
reader.Seek(124, System.IO.SeekOrigin.Current);
continue;
}
EffectTask task = ReadTask(reader);
if (task.IsValid)
tasks.Add(task);
}
if (o < count)
objects[o] = new EffectGroupObject { TypeCrc = crcs[o], Tasks = tasks.ToArray() };
}
groups[g] = new EffectGroup { Objects = objects };
}
var file = new EffectDefinitionFile(definitions, groups);
for (int g = 0; g < groups.Length; g++)
foreach (EffectGroupObject obj in groups[g].Objects)
if (!file.TryGetType(obj.TypeCrc, out _))
throw new System.IO.InvalidDataException($"Group {g} references missing effect type {obj.TypeCrc:X8}");
return file;
}
private static EffectTask ReadTask(IBinaryReader reader)
{
var task = new EffectTask
{
XStretchSpeed = reader.ReadSingle(),
SpeedX = reader.ReadSingle(),
SpeedY = reader.ReadSingle(),
SpeedZ = reader.ReadSingle(),
SpeedRot = reader.ReadSingle(),
CircleAxisX = reader.ReadSingle(),
CircleAxisY = reader.ReadSingle(),
CircleAxisZ = reader.ReadSingle(),
CircleRadius = reader.ReadSingle(),
CircleSpeed = reader.ReadSingle(),
RotAxisX = reader.ReadSingle(),
RotAxisY = reader.ReadSingle(),
RotAxisZ = reader.ReadSingle(),
RotSpeed = reader.ReadSingle(),
SpeedAlpha = reader.ReadSingle(),
SpeedRed = reader.ReadSingle(),
SpeedGreen = reader.ReadSingle(),
SpeedBlue = reader.ReadSingle(),
StartTime = reader.ReadSingle(),
Duration = reader.ReadSingle(),
RequireLoops = reader.ReadInt32(),
CreateTimeSlot = reader.ReadSingle(),
};
byte valid = reader.ReadByte();
if (valid > 1)
throw new System.IO.InvalidDataException("Invalid task validity flag");
task.IsValid = valid == 1;
task.CreateNew = reader.ReadBoolean();
task.ModifyLast = reader.ReadBoolean();
reader.ReadByte(); // native 4-byte alignment
task.YStretchSpeed = reader.ReadSingle();
reader.Seek(28, System.IO.SeekOrigin.Current); // reserved, not active parameters
if (task.IsValid && (!Finite(task.StartTime) || !Finite(task.Duration) || task.Duration < 0))
throw new System.IO.InvalidDataException("Invalid effect task timing");
return task;
}
private static bool Finite(float value) => !float.IsNaN(value) && !float.IsInfinity(value);
private EffectDefinition ReadEffectDefinition(IBinaryReader reader, int codepage)
{
EffectDefinition effectDefinition = new()
@@ -55,7 +175,7 @@ namespace Pal3.Core.DataReader.Data
effectDefinition.InitAngle = unionFloat;
}
effectDefinition.InitSize = reader.ReadInt32();
effectDefinition.InitSize = reader.ReadSingle();
effectDefinition.InitColor = reader.ReadUInt32();
effectDefinition.MaxQuadCount = reader.ReadInt32();
@@ -90,4 +210,4 @@ namespace Pal3.Core.DataReader.Data
return effectDefinition;
}
}
}
}
@@ -0,0 +1,85 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Core.DataReader.Data
{
using System;
using System.Collections.Generic;
using Cpk;
using Primitives;
// The names describe the quad interpretation of the original unions.
// Callback/audio/model adapters interpret these same fields by class.
[Serializable]
public sealed class EffectTask
{
public float XStretchSpeed, SpeedX, SpeedY, SpeedZ, SpeedRot;
public float CircleAxisX, CircleAxisY, CircleAxisZ, CircleRadius, CircleSpeed;
public float RotAxisX, RotAxisY, RotAxisZ, RotSpeed;
public float SpeedAlpha, SpeedRed, SpeedGreen, SpeedBlue, StartTime, Duration;
public int RequireLoops;
public float CreateTimeSlot;
public bool IsValid, CreateNew, ModifyLast;
public float YStretchSpeed;
public GameBoxVector3 Speed => new(SpeedX, SpeedY, SpeedZ);
public GameBoxVector3 CircleAxis => new(CircleAxisX, CircleAxisY, CircleAxisZ);
public IEnumerable<(int groupId, GameBoxVector3 position)> Callbacks()
{
if (XStretchSpeed != 0)
yield return ((int)MathF.Round(XStretchSpeed), new(SpeedX, SpeedY, SpeedZ));
if (CircleRadius != 0)
yield return ((int)MathF.Round(CircleRadius), new(RotAxisX, RotAxisY, RotAxisZ));
if (CircleAxisX != 0)
yield return ((int)MathF.Round(CircleAxisX), new(CircleAxisY, CircleAxisZ, CircleSpeed));
if (SpeedAlpha != 0)
yield return ((int)MathF.Round(SpeedAlpha), new(SpeedRed, SpeedGreen, SpeedBlue));
}
public IEnumerable<(int index, float delay)> Sounds()
{
if (XStretchSpeed != 0)
yield return ((int)MathF.Round(XStretchSpeed), SpeedX);
if (SpeedY != 0)
yield return ((int)MathF.Round(SpeedY), SpeedZ);
if (CircleRadius != 0)
yield return ((int)MathF.Round(CircleRadius), RotAxisX);
if (RotAxisY != 0)
yield return ((int)MathF.Round(RotAxisY), RotAxisZ);
}
}
[Serializable]
public sealed class EffectGroupObject
{
public uint TypeCrc;
public EffectTask[] Tasks = Array.Empty<EffectTask>();
}
[Serializable]
public sealed class EffectGroup
{
public EffectGroupObject[] Objects = Array.Empty<EffectGroupObject>();
}
public static class EffectClass
{
private static readonly Dictionary<uint, string> Names = CreateNames();
private static Dictionary<uint, string> CreateNames()
{
var hash = new Crc32Hash();
hash.Init();
var result = new Dictionary<uint, string>();
foreach (string name in new[] { "quad", "particle", "cylinder", "model", "callback", "audio",
"meteor", "shock", "grid", "explosive", "action", "camera", "time", "bink", "quake" })
result.Add(hash.Compute(name, 936), name);
return result;
}
public static string Name(uint crc) => Names.TryGetValue(crc, out string name) ? name : $"unknown:{crc:X8}";
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9fd0064acbd0242f981e846ddb645825
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c2f352a62352f4c2b8747dd5dd7168ae
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,88 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Core.DataReader.Par
{
using System;
using Primitives;
public sealed class ParticleCurve
{
public int Channels;
public string Name;
public GameBoxVector3[][] Samples;
public Func<float, int, float> OverrideEvaluation
{
get; set;
}
public float Evaluate(float time, int channel = 0)
{
if (OverrideEvaluation != null)
return OverrideEvaluation(time, channel);
if (channel < 0 || channel >= Channels)
return 0;
int lo = 0, hi = 100;
for (int i = 0; i < 5; i++)
{
int mid = (hi + lo) / 2;
if (Samples[0][mid].X <= time)
lo = mid;
else
hi = mid;
}
for (int i = lo; i < hi; i++)
{
if (Samples[0][i].X > time || Samples[0][i + 1].X < time)
continue;
GameBoxVector3 a = Samples[channel][i], b = Samples[channel][i + 1];
return b.X == a.X ? a.Y : a.Y + (b.Y - a.Y) * ((time - a.X) / (b.X - a.X));
}
return 0;
}
}
public sealed class ParticleDescription
{
public string Name, Texture;
public float Gravity, NoResistanceSpeed, Resistance;
public int VelocityResistancePower, SizeResistancePower, TextureSize, AnimationType, Fps;
public bool RandomFirstFrame, RandomRotationDirection, MirrorX, MirrorY;
public int RotationStart, RotationEnd, Rows, Columns, BlendMode;
public ParticleCurve Size, Rotation, Alpha, Color;
}
public sealed class ParticleEmitter
{
public string Name, ShapePath;
public GameBoxVector3 Position, Scope, BoxMin, BoxMax;
public int Shape;
public float SpeedMultiplier, CycleMin, CycleMax, Hotspot, Falloff;
public bool Loop;
public ParticleCurve Direction, RandomVelocity, Emission, Life, Size, Rotation;
}
public sealed class ParticleController
{
public string Name;
public int ParticleIndex, EmitterIndex, Capacity;
}
public sealed class ParticleFile
{
public uint Version;
public int Capacity, Space, Overflow;
public float Scale;
public ParticleDescription[] Particles;
public ParticleEmitter[] Emitters;
public ParticleController[] Controllers;
}
public sealed class ParticleShapeFile
{
public GameBoxVector3[] Points;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 30b0fbf09f821494eb895c502aa5cdcb
@@ -0,0 +1,160 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Core.DataReader.Par
{
using System;
using System.IO;
public sealed class ParticleFileReader : IFileReader<ParticleFile>
{
public ParticleFile Read(IBinaryReader r, int codepage)
{
if (r.ReadString(6) != "sgpar\0")
throw new InvalidDataException("Not an sgpar particle file (SPar is not supported)");
uint version = r.ReadUInt32();
if (version != 0x10000 && version != 0x10001)
throw new InvalidDataException($"Unsupported sgpar version {version:X}");
var file = new ParticleFile
{
Version = version,
Capacity = Count(r, 65536),
Space = r.ReadInt32(),
Overflow = r.ReadInt32(),
Scale = version > 0x10000 ? r.ReadSingle() : 1f
};
if (file.Space < 0 || file.Space > 1 || file.Overflow < 0 || file.Overflow > 2 || !Finite(file.Scale) || file.Scale <= 0)
throw new InvalidDataException("Invalid sgpar scene parameters");
int np = Count(r, 64), ne = Count(r, 64), nc = Count(r, 64);
file.Particles = new ParticleDescription[np];
file.Emitters = new ParticleEmitter[ne];
file.Controllers = new ParticleController[nc];
for (int i = 0; i < np; i++)
file.Particles[i] = ReadParticle(r, codepage);
for (int i = 0; i < ne; i++)
file.Emitters[i] = ReadEmitter(r, codepage, version);
for (int i = 0; i < nc; i++)
{
var c = new ParticleController
{
Name = r.ReadString(64, codepage),
ParticleIndex = r.ReadInt32(),
EmitterIndex = r.ReadInt32(),
Capacity = Count(r, 65536)
};
if (c.ParticleIndex < 0 || c.ParticleIndex >= np || c.EmitterIndex < 0 || c.EmitterIndex >= ne)
throw new InvalidDataException("Invalid sgpar controller reference");
file.Controllers[i] = c;
}
if (r.Position != r.Length)
throw new InvalidDataException("Unexpected sgpar trailing data");
return file;
}
private static ParticleDescription ReadParticle(IBinaryReader r, int cp)
{
var p = new ParticleDescription { Name = r.ReadString(32, cp) };
r.ReadInt32(); // native BOOL lighting (unused by original renderer)
p.Gravity = r.ReadSingle();
p.NoResistanceSpeed = r.ReadSingle();
p.VelocityResistancePower = r.ReadInt32();
p.SizeResistancePower = r.ReadInt32();
p.Resistance = r.ReadSingle();
p.Texture = r.ReadString(256, cp);
p.TextureSize = r.ReadInt32();
p.AnimationType = r.ReadInt32();
p.Fps = r.ReadInt32();
p.RandomFirstFrame = r.ReadInt32() != 0;
p.RotationStart = r.ReadInt32();
p.RotationEnd = r.ReadInt32();
p.RandomRotationDirection = r.ReadInt32() != 0;
p.MirrorX = r.ReadInt32() != 0;
p.MirrorY = r.ReadInt32() != 0;
p.Rows = r.ReadInt32();
p.Columns = r.ReadInt32();
p.BlendMode = r.ReadInt32();
if (p.Rows < 1 || p.Columns < 1 || p.Rows > 256 || p.Columns > 256)
throw new InvalidDataException("Invalid particle atlas");
p.Size = ReadCurve(r, cp);
p.Rotation = ReadCurve(r, cp);
p.Alpha = ReadCurve(r, cp);
p.Color = ReadCurve(r, cp);
return p;
}
private static ParticleEmitter ReadEmitter(IBinaryReader r, int cp, uint version)
{
var e = new ParticleEmitter { Name = r.ReadString(64, cp), Position = r.ReadGameBoxVector3(), Scope = r.ReadGameBoxVector3(), Shape = r.ReadInt32() };
e.ShapePath = version > 0x10000 ? r.ReadString(64, cp) : "";
e.SpeedMultiplier = version > 0x10000 ? r.ReadSingle() : 1f;
e.CycleMin = r.ReadSingle();
e.CycleMax = r.ReadSingle();
e.Loop = r.ReadInt32() != 0;
r.ReadInt32(); // lighton
e.Hotspot = r.ReadSingle();
e.Falloff = r.ReadSingle();
e.BoxMin = r.ReadGameBoxVector3();
e.BoxMax = r.ReadGameBoxVector3();
if (e.Shape < 0 || e.Shape > 2)
throw new InvalidDataException("Invalid sgpar emitter shape");
e.Direction = ReadCurve(r, cp);
e.RandomVelocity = ReadCurve(r, cp);
e.Emission = ReadCurve(r, cp);
e.Life = ReadCurve(r, cp);
e.Size = ReadCurve(r, cp);
e.Rotation = ReadCurve(r, cp);
return e;
}
private static ParticleCurve ReadCurve(IBinaryReader r, int cp)
{
int channels = Count(r, 3), points = Count(r, 20);
var curve = new ParticleCurve { Channels = channels, Name = r.ReadString(64, cp), Samples = new Primitives.GameBoxVector3[3][] };
r.ReadString(128, cp);
r.ReadGameBoxVector3();
r.ReadGameBoxVector3();
r.Seek(2 * 3 * 20 * 12, SeekOrigin.Current); // editor and real control points; runtime uses stored samples
for (int c = 0; c < 3; c++)
curve.Samples[c] = r.ReadGameBoxVector3s(101);
for (int c = 0; c < channels; c++)
for (int i = 0; i < 101; i++)
{
var p = curve.Samples[c][i];
// Shipped curves can double back in x. Preserve their original
// sample order and lookup semantics instead of sorting them.
if (!Finite(p.X) || !Finite(p.Y))
throw new InvalidDataException($"Invalid particle curve {curve.Name} channel={c} sample={i} x={p.X} y={p.Y} previous={(i > 0 ? curve.Samples[c][i - 1].X : 0)}");
}
return curve;
}
private static int Count(IBinaryReader r, int max)
{
int value = r.ReadInt32();
if (value < 0 || value > max)
throw new InvalidDataException("Invalid sgpar count");
return value;
}
private static bool Finite(float v) => !float.IsNaN(v) && !float.IsInfinity(v);
}
public sealed class ParticleShapeFileReader : IFileReader<ParticleShapeFile>
{
public ParticleShapeFile Read(IBinaryReader r, int codepage)
{
if (r.ReadString(4) != "csf\0")
throw new InvalidDataException("Invalid CSF header");
r.ReadUInt32();
int count = r.ReadInt32();
if (count < 2 || count > 1000000 || count > (r.Length - r.Position) / 12)
throw new InvalidDataException("Invalid CSF point count");
var result = new ParticleShapeFile { Points = r.ReadGameBoxVector3s(count) };
if (r.Position != r.Length)
throw new InvalidDataException("Unexpected CSF trailing data");
return result;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0c0f89a3d0f3c4df9864b29cbc004105
@@ -60,14 +60,17 @@ namespace Pal3.Game.Data
private ITextureCache _textureCache;
private readonly Dictionary<string, ISprite> _spriteCache = new ();
private readonly Dictionary<string, AudioClip> _audioClipCache = new ();
private readonly Dictionary<string, ISprite> _spriteCache = new();
private readonly Dictionary<string, AudioClip> _audioClipCache = new();
private readonly Dictionary<Type, Dictionary<string, object>> _gameResourceFileCache = new ();
private readonly Dictionary<Type, Dictionary<string, object>> _gameResourceFileCache = new();
private readonly int _codepage;
internal OptionalVfxPlayer OptionalVfx { get; }
internal OptionalVfxPlayer OptionalVfx
{
get;
}
public GameResourceProvider(ICpkFileSystem fileSystem,
ITextureLoaderFactory textureLoaderFactory,
@@ -83,7 +86,7 @@ namespace Pal3.Game.Data
_codepage = _gameSettings.Language == Language.SimplifiedChinese ? 936 : 950;
_gameDatabase = GetGameDatabaseFile(); // Initialize game database file
OptionalVfx = new OptionalVfxPlayer(_gameSettings);
OptionalVfx = new OptionalVfxPlayer(_gameSettings, _fileSystem, _codepage);
CommandExecutorRegistry<ICommand>.Instance.Register(this);
}
@@ -131,9 +134,11 @@ namespace Pal3.Game.Data
// No need to deallocate the shadow texture/sprite since it is been used almost every where.
private static ISprite _shadowSprite;
public ISprite GetShadowSprite()
{
if (_shadowSprite != null) return _shadowSprite;
if (_shadowSprite != null)
return _shadowSprite;
ITexture2D shadowTexture = new UnityTexture2D(Resources.Load<Texture2D>("Textures/shadow"));
_shadowSprite = shadowTexture.CreateSprite(0, 0,
@@ -143,6 +148,8 @@ namespace Pal3.Game.Data
return _shadowSprite;
}
public Effect.Original.OriginalEffectResources OriginalEffects => OptionalVfx.Original;
public IMaterialManager GetMaterialManager() => _materialManager;
public ITextureResourceProvider CreateTextureResourceProvider(string relativeDirectoryPath, bool useCache = true, TextureUsage usage = TextureUsage.World)
@@ -224,7 +231,8 @@ namespace Pal3.Game.Data
/// <param name="musicFileCachePath">music file path in cache folder</param>
public IEnumerator ExtractAndMoveMp3FileToCacheFolderAsync(string musicFileVirtualPath, string musicFileCachePath)
{
if (File.Exists(musicFileCachePath)) yield break;
if (File.Exists(musicFileCachePath))
yield break;
EngineLogger.Log($"Writing MP3 file to App's persistent folder: {musicFileVirtualPath}");
Thread dataMovementThread = new(() =>
@@ -253,11 +261,11 @@ namespace Pal3.Game.Data
public string GetSfxFilePath(string sfxName)
{
#if PAL3
#if PAL3
string sfxFileName = (sfxName + ".wav").ToLower();
#elif PAL3A
#elif PAL3A
string sfxFileName = (sfxName + ".wav").ToUpper();
#endif
#endif
string sfxFileRelativePath = $"{FileConstants.SfxFolderName}{Path.DirectorySeparatorChar}" + sfxFileName;
@@ -293,13 +301,13 @@ namespace Pal3.Game.Data
public ISprite GetLogoSprite()
{
#if PAL3
#if PAL3
const string mainLogoTextureFileName = "11.tga";
Rect mainLogoSpriteRect = new Rect(0, 600, 375, 145);
#elif PAL3A
#elif PAL3A
const string mainLogoTextureFileName = "12.tga";
Rect mainLogoSpriteRect = new Rect(0, 770, 500, 253);
#endif
#endif
ITextureResourceProvider uiLibTextureProvider = CreateTextureResourceProvider(FileConstants.UILibFolderVirtualPath, usage: TextureUsage.Sprite);
ITexture2D logoTexture = uiLibTextureProvider.GetTexture(mainLogoTextureFileName);
@@ -321,13 +329,15 @@ namespace Pal3.Game.Data
if (_spriteCache.TryGetValue(cacheKey, out ISprite sprite))
{
if (sprite is { Texture: { IsNativeObjectDisposed: false } }) return sprite;
if (sprite is { Texture: { IsNativeObjectDisposed: false } })
return sprite;
}
ITexture2D texture = GetActorAvatarTexture(
actorName, avatarName);
if (texture == null) return null;
if (texture == null)
return null;
ISprite avatarSprite = texture.CreateSprite(
// Cut 2f to hide artifacts near edges for some of the avatar textures
@@ -527,6 +537,7 @@ namespace Pal3.Game.Data
}
private string _currentCityName;
public void Execute(ScenePreLoadingNotification notification)
{
string newCityName = notification.NewSceneInfo.CityName.ToLower();
@@ -594,4 +605,4 @@ namespace Pal3.Game.Data
}
}
}
}
+13 -15
View File
@@ -14,19 +14,19 @@ namespace Pal3.Game.Effect
public sealed class CombatEffect : GameEntityScript, IEffect
{
#if PAL3
#if PAL3
private const string SHUSHAN_BRIDGE_TEXTURE_NAME = "q08qiao.dds";
#elif PAL3A
#elif PAL3A
private const string SHUSHAN_BRIDGE_TEXTURE_NAME = "q08qiao.tga";
#endif
#endif
private const float SHUSHAN_BRIDGE_DEFAULT_SIZE = 3.5f;
private const float SHUSHAN_BRIDGE_ANIMATION_ROTATION_SPEED = 15f;
#if PAL3
#if PAL3
private const string SHUSHAN_BRIDGE_EFFECT_TEXTURE_NAME = "q08qiao2.dds";
#elif PAL3A
#elif PAL3A
private const string SHUSHAN_BRIDGE_EFFECT_TEXTURE_NAME = "q08qiao2.tga";
#endif
#endif
private const float SHUSHAN_BRIDGE_EFFECT_DEFAULT_SIZE = 3.5f;
private const float SHUSHAN_BRIDGE_EFFECT_ANIMATION_ROTATION_SPEED = 40f;
@@ -41,11 +41,12 @@ namespace Pal3.Game.Effect
public void Init(GameResourceProvider resourceProvider, uint effectParameter)
{
#if PAL3
if (effectParameter == 465) // 蜀山太极桥特效
#elif PAL3A
#if PAL3
// MXCEft restarts the original group when it finishes. Group 275
// is additionally emitted every 9.5 seconds by the original scene object.
_effect = resourceProvider.OptionalVfx.Attach((int)effectParameter, GameEntity);
#elif PAL3A
if (effectParameter == 160) // 蜀山太极桥特效
#endif
{
_bridgeBaseEffect = GameEntity.AddComponent<RotatingSpriteEffect>();
_bridgeBaseEffect.Init(resourceProvider,
@@ -64,14 +65,11 @@ namespace Pal3.Game.Effect
SHUSHAN_BRIDGE_EFFECT_ANIMATION_ROTATION_SPEED);
}
#if PAL3
if (effectParameter == 275) // 重楼创建的用来禁锢雪见/龙葵的法阵特效
#elif PAL3A
if (effectParameter == 344) // 重盘古元灵特效
#endif
{
_effect = resourceProvider.OptionalVfx.Attach((int)effectParameter, GameEntity);
}
#endif
}
private void OnDestroy() => Dispose();
@@ -96,4 +94,4 @@ namespace Pal3.Game.Effect
_effect = null;
}
}
}
}
@@ -33,6 +33,7 @@ namespace Pal3.Game.Effect
private readonly OptionalVfxPlayer _optionalVfx;
private readonly SceneManager _sceneManager;
private ICommand _effectPositionCommand;
private Vector3 _originalPosition;
private const string EFFECT_LINKER_FILE_NAME = "efflinker.dat";
private EffectLinkerFile _effectLinkerFile;
@@ -61,22 +62,31 @@ namespace Pal3.Game.Effect
// So it is pointless to pre-load the effect here for PAL3A.
// Even with a waiter, we need to make sure waiter's current execution mode is set
// to synchronous otherwise the effect will be played before the pre-load is finished.
#if PAL3
#if PAL3
Pal3.Instance.StartCoroutine(_optionalVfx.PreloadAsync(command.EffectGroupId));
#endif
#endif
}
public void Execute(EffectPlayCommand command)
{
if (_effectPositionCommand == null ||
_sceneManager.GetCurrentScene() is not {} currentScene) return;
if (_sceneManager.GetCurrentScene() is not { } currentScene)
return;
bool playedOriginal = false;
#if PAL3
playedOriginal = _optionalVfx.Play(command.EffectGroupId,
_sceneManager.GetSceneRootGameEntity(), _originalPosition,
privateFallback: _effectPositionCommand is EffectAttachToActorCommand role
? (currentScene.GetActorGameEntity(role.ActorId), Vector3.zero) : null);
#else
if (_effectPositionCommand == null)
return;
#if PAL3A
#if PAL3A
if (_effectPositionCommand is EffectAttachToActorCommand effectAttachToActorCommand)
{
HandleNanGongHuangTransformEffect(effectAttachToActorCommand, command, currentScene);
}
#endif
#endif
if (_effectPositionCommand is EffectSetPositionCommand positionCommand)
{
@@ -94,15 +104,17 @@ namespace Pal3.Game.Effect
currentScene.GetActorGameEntity(actorCommand.ActorId), Vector3.zero);
}
// Play SFX if any
if (EffectConstants.EffectSfxInfo.TryGetValue(command.EffectGroupId, out var sfxName))
#endif
// Private fallback retains its old audio mapping; native groups own their audio tracks.
if (!playedOriginal && EffectConstants.EffectSfxInfo.TryGetValue(command.EffectGroupId, out var sfxName))
{
Pal3.Instance.Execute(
new PlaySfxCommand(sfxName, 1));
}
}
#if PAL3A
#if PAL3A
private void HandleNanGongHuangTransformEffect(EffectAttachToActorCommand effectAttachToActorCommand,
EffectPlayCommand effectPlayCommand,
GameScene currentScene)
@@ -138,11 +150,30 @@ namespace Pal3.Game.Effect
}
}
}
#endif
#endif
public void Execute(EffectSetPositionCommand command) => _effectPositionCommand = command;
public void Execute(EffectSetPositionCommand command)
{
_effectPositionCommand = command;
_originalPosition = new GameBoxVector3(command.GameBoxXPosition, command.GameBoxYPosition, command.GameBoxZPosition).ToUnityPosition();
}
public void Execute(EffectAttachToActorCommand command) => _effectPositionCommand = command;
public void Execute(EffectAttachToActorCommand command)
{
_effectPositionCommand = command;
#if PAL3
var scene = _sceneManager.GetCurrentScene();
var actor = scene?.GetActorGameEntity(command.ActorId);
if (!actor.IsNullOrDisposed())
{
var root = (UnityEngine.Transform)_sceneManager.GetSceneRootGameEntity().Transform.NativeObject;
var transform = (UnityEngine.Transform)actor.Transform.NativeObject;
// cmd_CEft_Role captures the position immediately and adds two
// GameBox units. It does not attach the effect to a moving actor.
_originalPosition = root.InverseTransformPoint(transform.position) + Vector3.up * 0.1f;
}
#endif
}
public void Execute(SceneLeavingCurrentSceneNotification command) => ClearSceneEffects();
@@ -151,7 +182,8 @@ namespace Pal3.Game.Effect
private void ClearSceneEffects()
{
_effectPositionCommand = null;
_originalPosition = Vector3.zero;
_optionalVfx.ClearPlayedEffects();
}
}
}
}
@@ -9,6 +9,9 @@ namespace Pal3.Game.Effect
using System.Collections;
using System.Collections.Generic;
using Constants;
using Original;
using Core.FileSystem;
using Core.Command.SceCommands;
using Engine.Core.Abstraction;
using Engine.Core.Implementation;
using Engine.Extensions;
@@ -19,27 +22,71 @@ namespace Pal3.Game.Effect
internal sealed class OptionalVfxPlayer : IDisposable
{
private readonly GameSettings _settings;
private readonly OriginalEffectResources _original;
private readonly HashSet<int> _originalFailures = new();
internal OriginalEffectResources Original => _original;
private readonly Dictionary<int, GameObject> _prefabs = new();
private readonly List<IGameEntity> _playedEffects = new();
private readonly List<PersistentEffect> _persistentEffects = new();
private int _prefabCacheGeneration;
private bool _disposed;
private bool IsEnabled => !_disposed && _settings.OptionalVfxEnabled;
internal OptionalVfxPlayer(GameSettings settings)
private bool IsEnabled => !_disposed && (_original != null || _settings.OptionalVfxEnabled);
internal OptionalVfxPlayer(GameSettings settings, ICpkFileSystem fileSystem, int codepage)
{
_settings = settings;
#if PAL3
_original = new OriginalEffectResources(fileSystem, codepage);
#endif
_settings.OnGameSettingsChanged += OnGameSettingsChanged;
}
private static string GetPrefabPath(int effectGroupId) => $"Prefabs/VFX/{GameConstants.AppName}/{effectGroupId}";
private static string GetPrefabPath(int effectGroupId) => $"Prefabs/VFX/{GameConstants.AppName}/{(effectGroupId == -1 ? 0 : effectGroupId)}";
internal IEnumerator PreloadAsync(int effectGroupId)
{
if (!IsEnabled || _prefabs.ContainsKey(effectGroupId)) yield break;
if (!IsEnabled || _prefabs.ContainsKey(effectGroupId))
yield break;
int generation = _prefabCacheGeneration;
bool useOriginal = false;
var edits = Resources.Load<OriginalEffectOverrides>("Effects/PAL3Overrides");
try
{
useOriginal = _original != null && effectGroupId >= 0 && _original.Diagnose(effectGroupId, edits).Length == 0;
}
catch (Exception ex)
{
if (_originalFailures.Add(effectGroupId))
EngineLogger.LogWarning(ex.Message);
}
if (useOriginal)
{
using var preload = _original.Preload(effectGroupId, edits).GetEnumerator();
while (IsEnabled && generation == _prefabCacheGeneration)
{
bool next;
try
{
next = preload.MoveNext();
}
catch (Exception ex)
{
EngineLogger.LogWarning($"Original effect preload {effectGroupId}: {ex.Message}");
break;
}
if (!next)
break;
yield return null;
}
yield break;
}
if (!_settings.OptionalVfxEnabled)
yield break;
ResourceRequest request = Resources.LoadAsync<GameObject>(GetPrefabPath(effectGroupId));
yield return request;
@@ -58,32 +105,88 @@ namespace Pal3.Game.Effect
}
}
private IGameEntity Create(int effectGroupId, IGameEntity parent)
private IGameEntity Create(int effectGroupId, IGameEntity parent, (IGameEntity parent, Vector3 position)? privateFallback = null)
{
if (!IsEnabled || parent.IsNullOrDisposed()) return null;
if (!IsEnabled || parent.IsNullOrDisposed())
return null;
if (_original != null)
{
GameObject native = null;
try
{
var edits = Resources.Load<OriginalEffectOverrides>("Effects/PAL3Overrides");
string[] issues = effectGroupId == -1 ? Array.Empty<string>() : _original.Diagnose(effectGroupId, edits);
if (issues.Length == 0)
{
native = new GameObject(effectGroupId == -1 ? "Original transport" : $"Original effect {effectGroupId}");
native.transform.SetParent((Transform)parent.Transform.NativeObject, false);
if (effectGroupId == -1)
native.AddComponent<OriginalPortalEffect>().Initialize(_original);
else
{
var player = native.AddComponent<OriginalEffectPlayer>();
player.Initialize(_original, effectGroupId, (uint)UnityEngine.Random.Range(1, int.MaxValue), overrides: edits,
sound: name => Pal3.Instance.Execute(new PlaySfxCommand(name, 1)));
player.DestroyOnComplete = true;
if (player.Error != null)
throw new InvalidOperationException(player.Error);
}
return new GameEntity(native);
}
if (_originalFailures.Add(effectGroupId))
EngineLogger.LogWarning(string.Join("\n", issues));
}
catch (Exception ex)
{
if (native != null)
{
native.SetActive(false);
OriginalEffectResources.Destroy(native);
}
if (_originalFailures.Add(effectGroupId))
EngineLogger.LogWarning($"Original effect {effectGroupId}: {ex.Message}");
}
}
if (!_settings.OptionalVfxEnabled)
return null;
if (!_prefabs.TryGetValue(effectGroupId, out GameObject prefab))
{
prefab = Resources.Load<GameObject>(GetPrefabPath(effectGroupId));
CachePrefab(effectGroupId, prefab);
}
return prefab == null ? null :
GameEntityFactory.Create($"VFX_{effectGroupId}", prefab, parent, worldPositionStays: false);
IGameEntity prefabParent = privateFallback.HasValue ? privateFallback.Value.parent : parent;
return prefab == null || prefabParent.IsNullOrDisposed() ? null :
GameEntityFactory.Create($"VFX_{effectGroupId}", prefab, prefabParent, worldPositionStays: false);
}
internal void Play(int effectGroupId, IGameEntity parent, Vector3 localPosition)
internal bool Play(int effectGroupId, IGameEntity parent, Vector3 localPosition,
(IGameEntity parent, Vector3 position)? privateFallback = null)
{
if (Create(effectGroupId, parent) is not {} instance) return;
if (Create(effectGroupId, parent, privateFallback) is not { } instance)
return false;
instance.Transform.LocalPosition += localPosition;
instance.Transform.LocalPosition += IsOriginal(instance) ? localPosition : privateFallback?.position ?? localPosition;
_playedEffects.RemoveAll(effect => effect.IsNativeObjectDisposed);
_playedEffects.Add(instance);
return IsOriginal(instance);
}
internal IDisposable AttachPortal(IGameEntity parent) => Attach(-1, parent);
private static bool IsOriginal(IGameEntity instance)
{
if (instance.IsNullOrDisposed())
return false;
var go = (GameObject)instance.NativeObject;
return go.GetComponent<OriginalEffectPlayer>() != null || go.GetComponent<OriginalPortalEffect>() != null;
}
internal IDisposable Attach(int effectGroupId, IGameEntity parent)
{
if (_disposed || parent.IsNullOrDisposed()) return null;
if (_disposed || parent.IsNullOrDisposed())
return null;
PruneDeadAttachments();
var effect = new PersistentEffect(this, effectGroupId, parent);
_persistentEffects.Add(effect);
@@ -93,13 +196,20 @@ namespace Pal3.Game.Effect
private void OnGameSettingsChanged(string propertyName)
{
if (propertyName != nameof(GameSettings.OptionalVfxEnabled)) return;
if (propertyName != nameof(GameSettings.OptionalVfxEnabled))
return;
if (!IsEnabled) ClearPlayedEffects();
if (!_settings.OptionalVfxEnabled)
for (int i = _playedEffects.Count - 1; i >= 0; i--)
if (!IsOriginal(_playedEffects[i]))
{
Stop(_playedEffects[i]);
_playedEffects.RemoveAt(i);
}
foreach (PersistentEffect effect in _persistentEffects.ToArray())
{
effect.Refresh();
effect.Refresh(reconsiderPrivate: true);
}
}
@@ -110,11 +220,42 @@ namespace Pal3.Game.Effect
Stop(effect);
}
_playedEffects.Clear();
if (_disposed || _original == null)
return;
ClearPrefabCache();
_originalFailures.Clear();
if (Application.isPlaying && Pal3.Instance != null)
Pal3.Instance.StartCoroutine(TrimSceneRenderAssetsAfterFrame());
else
_original.TrimUnusedRenderAssets(LiveOriginalRoots());
}
private IEnumerator TrimSceneRenderAssetsAfterFrame()
{
// Scene objects are destroyed at the end of the leaving frame. Keep
// any effects already created for the next scene while evicting old
// render assets; parsed tables/particle data remain reusable.
yield return null;
if (_disposed)
yield break;
PruneDeadAttachments();
_original.TrimUnusedRenderAssets(LiveOriginalRoots());
}
private IEnumerable<GameObject> LiveOriginalRoots()
{
foreach (IGameEntity effect in _playedEffects)
if (IsOriginal(effect))
yield return (GameObject)effect.NativeObject;
foreach (PersistentEffect effect in _persistentEffects)
if (effect.OriginalRoot != null)
yield return effect.OriginalRoot;
}
private static void Stop(IGameEntity effect)
{
if (effect.IsNullOrDisposed()) return;
if (effect.IsNullOrDisposed())
return;
// Destroy is deferred to the end of the frame.
((GameObject)effect.NativeObject).SetActive(false);
@@ -125,7 +266,8 @@ namespace Pal3.Game.Effect
{
for (int i = _persistentEffects.Count - 1; i >= 0; i--)
{
if (_persistentEffects[i].ParentIsDisposed) _persistentEffects[i].Dispose();
if (_persistentEffects[i].ParentIsDisposed)
_persistentEffects[i].Dispose();
}
}
@@ -147,6 +289,7 @@ namespace Pal3.Game.Effect
effect.Dispose();
}
ClearPrefabCache();
_original?.Dispose();
}
private sealed class PersistentEffect : IDisposable
@@ -165,19 +308,35 @@ namespace Pal3.Game.Effect
}
internal bool ParentIsDisposed => _parent.IsNullOrDisposed();
internal GameObject OriginalRoot => IsOriginal(_instance) ? (GameObject)_instance.NativeObject : null;
internal void Refresh()
internal void Refresh(bool reconsiderPrivate = false)
{
if (_disposed) return;
if (_disposed)
return;
if (ParentIsDisposed)
{
Dispose();
return;
}
if (reconsiderPrivate && !IsOriginal(_instance))
{
Stop(_instance);
_instance = null;
}
if (_player.IsEnabled)
{
if (_instance.IsNullOrDisposed()) _instance = _player.Create(_effectGroupId, _parent);
if (_instance.IsNullOrDisposed())
{
_instance = _player.Create(_effectGroupId, _parent);
if (!_instance.IsNullOrDisposed() && ((GameObject)_instance.NativeObject).GetComponent<OriginalEffectPlayer>() is { } native)
{
native.DestroyOnComplete = false;
native.Loop = true;
native.RepeatInterval = _effectGroupId == 275 ? 9.5f : 0;
}
}
}
else
{
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ce61acd16e807473ea038ae337099077
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,84 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Game.Effect.Original
{
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
internal sealed class EffectMeshBuffer : IDisposable
{
private readonly Mesh _mesh;
private readonly MeshRenderer _renderer;
private readonly List<Vector3> _vertices = new();
private readonly List<Vector2> _uv = new();
private readonly List<Color32> _colors = new();
private readonly List<int> _indices = new();
public int QuadCount => _vertices.Count / 4;
public EffectMeshBuffer(GameObject root, Material material)
{
_mesh = new Mesh { name = "Original effect mesh", indexFormat = IndexFormat.UInt32, hideFlags = HideFlags.DontSave };
_mesh.MarkDynamic();
root.AddComponent<MeshFilter>().sharedMesh = _mesh;
_renderer = root.AddComponent<MeshRenderer>();
_renderer.sharedMaterial = material;
_renderer.shadowCastingMode = ShadowCastingMode.Off;
_renderer.receiveShadows = false;
_renderer.lightProbeUsage = LightProbeUsage.Off;
_renderer.reflectionProbeUsage = ReflectionProbeUsage.Off;
}
public void Clear()
{
_vertices.Clear();
_uv.Clear();
_colors.Clear();
_indices.Clear();
}
public void Quad(Vector3 a, Vector3 b, Vector3 c, Vector3 d, Vector2 uv0, Vector2 uv1, Color32 color)
=> Quad(a, b, c, d, uv0, uv1, color, color, color, color);
public void Quad(Vector3 a, Vector3 b, Vector3 c, Vector3 d, Vector2 uv0, Vector2 uv1,
Color32 colorA, Color32 colorB, Color32 colorC, Color32 colorD)
{
int n = _vertices.Count;
_vertices.Add(a);
_vertices.Add(b);
_vertices.Add(c);
_vertices.Add(d);
_uv.Add(uv0);
_uv.Add(new Vector2(uv1.x, uv0.y));
_uv.Add(uv1);
_uv.Add(new Vector2(uv0.x, uv1.y));
_colors.Add(colorA);
_colors.Add(colorB);
_colors.Add(colorC);
_colors.Add(colorD);
_indices.Add(n);
_indices.Add(n + 1);
_indices.Add(n + 2);
_indices.Add(n);
_indices.Add(n + 2);
_indices.Add(n + 3);
}
public void Upload()
{
_renderer.enabled = _vertices.Count > 0;
_mesh.Clear(false);
_mesh.SetVertices(_vertices);
_mesh.SetUVs(0, _uv);
_mesh.SetColors(_colors);
_mesh.SetTriangles(_indices, 0, true);
}
public void Dispose() => OriginalEffectResources.Destroy(_mesh);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4daa7814a3fa8493293fc2ad9eb6fecc
@@ -0,0 +1,193 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Game.Effect.Original
{
using System;
using Core.DataReader.Data;
using UnityEngine;
using Color = UnityEngine.Color;
internal sealed class OriginalTaskClock
{
private bool _initialized, _finished;
private float _initAt;
public float StartedAt { get; private set; } = -1;
public bool StartedNow
{
get; private set;
}
public bool Finished => _finished;
public bool Tick(float time, float dt, EffectTask task, out float elapsed)
{
StartedNow = false;
elapsed = 0;
if (_finished)
return false;
if (!_initialized)
{
_initialized = true;
_initAt = time;
// A negative wait means "after the previous init subtask",
// which has already finished in this update in CTaskTpl.
if (task.StartTime >= 0)
return false;
StartedAt = time;
StartedNow = true;
}
if (StartedAt < 0)
{
if (time - _initAt <= Mathf.Max(0, task.StartTime))
return false;
StartedAt = time;
StartedNow = true;
}
elapsed = dt - Mathf.Max(0, time - StartedAt - task.Duration);
_finished = time - StartedAt + 0.000001f >= task.Duration;
return true;
}
}
internal abstract class OriginalEffectNode : IDisposable
{
protected readonly GameObject Root;
protected readonly EffectDefinition Definition;
protected readonly EffectTask[] Tasks;
protected readonly OriginalTaskClock[] Clocks;
protected readonly float Birth;
protected Vector3 Position, Rotation, Orbit, Scale;
protected Color Tint;
protected float TextureOffset, LocalTime;
protected bool Visible;
public virtual bool Alive { get; protected set; } = true;
public virtual int QuadCount => 0;
protected OriginalEffectNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth)
{
Root = root;
Definition = d;
Tasks = tasks ?? Array.Empty<EffectTask>();
Birth = birth;
Position = origin + new Vector3(d.InitXPosition, d.InitYPosition, d.InitZPosition);
Rotation = new Vector3(d.InitXRotation, d.InitYRotation, d.InitZRotation);
Scale = Vector3.one * d.InitSize;
Tint = PackedColor(d.InitColor);
Clocks = new OriginalTaskClock[Tasks.Length];
for (int i = 0; i < Clocks.Length; i++)
Clocks[i] = new OriginalTaskClock();
}
public virtual void Step(float time, float dt)
{
LocalTime = time - Birth;
bool alive = false;
for (int i = 0; i < Tasks.Length; i++)
{
if (Clocks[i].Tick(LocalTime, dt, Tasks[i], out float activeDt))
{
Visible = true;
Apply(Tasks[i], Clocks[i], Mathf.Max(0, activeDt));
}
alive |= !Clocks[i].Finished;
}
Alive = alive;
}
protected virtual void Apply(EffectTask t, OriginalTaskClock clock, float dt)
{
Position += new Vector3(t.SpeedX, t.SpeedY, t.SpeedZ) * dt;
ApplyRotationAndStretch(t, dt);
Tint = ChangedColor(Tint, t, dt);
Vector3 axis = new(t.CircleAxisX, t.CircleAxisY, t.CircleAxisZ);
Orbit = OrbitPosition(axis, (LocalTime - clock.StartedAt) * t.CircleSpeed, t.CircleRadius);
TextureOffset += t.CreateTimeSlot * dt;
}
protected virtual void ApplyRotationAndStretch(EffectTask t, float dt)
{
Rotation += new Vector3(t.RotAxisX, t.RotAxisY, t.RotAxisZ) * dt;
Scale += new Vector3(t.XStretchSpeed, t.YStretchSpeed, t.CreateTimeSlot) * dt;
}
public abstract void Render(Camera camera);
public virtual void Dispose()
{
if (Root != null)
Root.SetActive(false);
OriginalEffectResources.Destroy(Root);
}
internal static Vector3 UnityPosition(Vector3 v) => new(-v.x / 20, v.y / 20, v.z / 20);
// A zero axis produces an identity matrix in GameBox, preserving the
// input radius vector rather than discarding the offset.
internal static Vector3 OrbitPosition(Vector3 axis, float angle, float radius) =>
(axis.sqrMagnitude > 0 ? Quaternion.AngleAxis(angle, axis.normalized) : Quaternion.identity) * new Vector3(0, 0, radius);
internal static Quaternion UnityRotation(Vector3 r) => Quaternion.AngleAxis(r.x, Vector3.right) * Quaternion.AngleAxis(-r.y, Vector3.up) * Quaternion.AngleAxis(-r.z, Vector3.forward);
internal static Quaternion RawRotation(Vector3 r) => Quaternion.AngleAxis(r.x, Vector3.right) * Quaternion.AngleAxis(r.y, Vector3.up) * Quaternion.AngleAxis(r.z, Vector3.forward);
internal static Color PackedColor(uint c) => new((c >> 16 & 255) / 255f, (c >> 8 & 255) / 255f, (c & 255) / 255f, (c >> 24) / 255f);
internal static Color ChangedColor(Color c, EffectTask t, float dt) => new(Mathf.Clamp01(c.r + t.SpeedRed * dt / 255),
Mathf.Clamp01(c.g + t.SpeedGreen * dt / 255), Mathf.Clamp01(c.b + t.SpeedBlue * dt / 255), Mathf.Clamp01(c.a + t.SpeedAlpha * dt / 255));
protected (Vector2 min, Vector2 max) Atlas(float age)
{
int columns = Mathf.Max(1, Definition.FramesPerRow), rows = Mathf.Max(1, Definition.FramesPerColumn);
int frame = Mathf.Abs(Mathf.RoundToInt(age * Definition.FramePerSecond)) % Mathf.Max(1, Definition.FrameCount);
var uv = new Vector2((float)(frame % columns) / columns, 1f - (float)(frame / columns + 1) / rows);
return (uv, uv + new Vector2(1f / columns, 1f / rows));
}
}
internal sealed class OriginalControlNode : OriginalEffectNode
{
private readonly OriginalEffectPlayer _player;
private readonly string _kind;
private readonly byte[] _played;
public OriginalControlNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, OriginalEffectPlayer player, string kind)
: base(root, d, tasks, origin, birth)
{
_player = player;
_kind = kind;
_played = new byte[Tasks.Length];
}
protected override void Apply(EffectTask t, OriginalTaskClock clock, float dt)
{
if (_kind == "callback")
{
if (clock.StartedNow)
foreach (var child in t.Callbacks())
_player.AddGroup(child.groupId, Position + new Vector3(child.position.X, child.position.Y, child.position.Z));
}
else
{
int index = Array.IndexOf(Tasks, t), bit = 0;
foreach (var sound in t.Sounds())
{
int mask = 1 << bit++;
if ((_played[index] & mask) != 0 || LocalTime - clock.StartedAt < sound.delay)
continue;
_player.Sound($"{Definition.SfxFileNamePrefix}{sound.index:000}");
_played[index] |= (byte)mask;
}
}
}
public override void Render(Camera camera)
{
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 03437bbaa78854faca572e1b314a630a
@@ -0,0 +1,133 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Game.Effect.Original
{
using System;
using System.Collections.Generic;
using System.Linq;
using Core.DataReader.Data;
using Core.DataReader.Par;
using UnityEngine;
[Serializable]
public sealed class OriginalEffectObjectOverride
{
public int GroupId, ObjectIndex;
public EffectDefinition Definition;
public EffectTask[] Tasks;
public bool Hidden;
}
[Serializable]
public sealed class OriginalParticleCurveOverride
{
public string File, Parameter;
public bool Emitter;
public int Index;
public AnimationCurve[] Channels;
}
[CreateAssetMenu(menuName = "PAL3/Original effect overrides")]
public sealed class OriginalEffectOverrides : ScriptableObject
{
public int Version = 1;
public List<OriginalEffectObjectOverride> Objects = new();
public List<OriginalParticleCurveOverride> ParticleCurves = new();
public OriginalEffectObjectOverride Find(int group, int index) =>
Objects.Find(o => o.GroupId == group && o.ObjectIndex == index);
internal static bool Resolve(OriginalEffectOverrides edits, int group, int index,
ref EffectDefinition definition, ref EffectTask[] tasks)
{
if (edits != null && edits.Version != 1)
throw new NotSupportedException($"Unknown original effect override version {edits.Version}");
OriginalEffectObjectOverride edit = edits?.Find(group, index);
if (edit?.Hidden == true)
return false;
if (edit != null)
{
definition = edit.Definition;
tasks = edit.Tasks ?? throw new InvalidOperationException("Missing effect override tasks");
ValidateNumbers(new[] { definition.InitXPosition, definition.InitYPosition, definition.InitZPosition,
definition.InitXRotation, definition.InitYRotation, definition.InitZRotation, definition.InitSize,
definition.FramePerSecond, definition.RotationAngle, definition.Width, definition.DivisionCount,
definition.TopShrink, definition.BottomShrink, definition.TopRadius, definition.BottomRadius,
definition.TopRadiusIncreaseSpeed, definition.BottomRadiusIncreaseSpeed, definition.TopRiseSpeed,
definition.BottomRiseSpeed, definition.TextureRepeat });
if (tasks.Length > 8)
throw new InvalidOperationException("An original effect object supports at most eight tasks");
foreach (EffectTask t in tasks.Where(t => t != null && t.IsValid))
{
ValidateNumbers(new[] { t.XStretchSpeed, t.SpeedX, t.SpeedY, t.SpeedZ, t.SpeedRot,
t.CircleAxisX, t.CircleAxisY, t.CircleAxisZ, t.CircleRadius, t.CircleSpeed,
t.RotAxisX, t.RotAxisY, t.RotAxisZ, t.RotSpeed, t.SpeedAlpha, t.SpeedRed,
t.SpeedGreen, t.SpeedBlue, t.StartTime, t.Duration, t.CreateTimeSlot, t.YStretchSpeed });
if (t.Duration < 0)
throw new InvalidOperationException("An effect task duration cannot be negative");
}
}
tasks = tasks.Where(t => t != null && t.IsValid).ToArray();
return true;
}
private static void ValidateNumbers(IEnumerable<float> values)
{
if (values.Any(v => !float.IsFinite(v)))
throw new InvalidOperationException("Effect overrides require finite numeric parameters");
}
public bool HasParticleEdits(string file) => ParticleCurves.Exists(c =>
string.Equals(OriginalEffectResources.Normalize(c.File), OriginalEffectResources.Normalize(file), StringComparison.OrdinalIgnoreCase));
public void ApplyParticle(string path, ParticleFile file)
{
foreach (OriginalParticleCurveOverride edit in ParticleCurves)
{
if (!string.Equals(OriginalEffectResources.Normalize(edit.File), OriginalEffectResources.Normalize(path), StringComparison.OrdinalIgnoreCase))
continue;
ParticleCurve curve = FindCurve(file, edit.Emitter, edit.Index, edit.Parameter);
if (edit.Channels == null || edit.Channels.Length != curve.Channels || edit.Channels.Any(c => c == null))
throw new InvalidOperationException("Particle curve channel count does not match original data");
foreach (AnimationCurve channel in edit.Channels)
{
ValidateNumbers(channel.keys.SelectMany(k => new[] { k.time, k.value }));
// Infinite tangents are valid stepped keys. Evaluate the
// normalized interval to reject curves that produce NaN/Inf.
ValidateNumbers(Enumerable.Range(0, 101).Select(i => channel.Evaluate(i / 100f)));
}
curve.OverrideEvaluation = (time, channel) => channel >= 0 && channel < edit.Channels.Length ? edit.Channels[channel].Evaluate(time) : 0;
}
}
public static ParticleCurve FindCurve(ParticleFile file, bool emitter, int index, string name)
{
if (emitter)
{
ParticleEmitter e = file.Emitters[index];
return name switch
{
"Direction" => e.Direction,
"RandomVelocity" => e.RandomVelocity,
"Emission" => e.Emission,
"Life" => e.Life,
"Size" => e.Size,
"Rotation" => e.Rotation,
_ => throw new ArgumentException(name)
};
}
ParticleDescription p = file.Particles[index];
return name switch
{
"Size" => p.Size,
"Rotation" => p.Rotation,
"Alpha" => p.Alpha,
"Color" => p.Color,
_ => throw new ArgumentException(name)
};
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 3a0f5edeb37f04ad28e5e2ed9000e2c5
@@ -0,0 +1,294 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Game.Effect.Original
{
using System;
using System.Collections.Generic;
using Core.DataReader.Data;
using UnityEngine;
// One simulation serves both clocks: real frame time in game, and fixed
// steps for editor playback/seeking. Rendering never advances the clock.
public sealed class OriginalEffectPlayer : MonoBehaviour
{
public const float FixedStep = 0.02f;
private readonly List<OriginalEffectNode> _nodes = new();
private OriginalEffectResources _resources;
private OriginalEffectOverrides _overrides;
private int _groupId;
private double _time;
private uint _seed;
private uint _spawnSequence;
private float _accumulator;
private Action<string> _sound;
private bool _disposed, _suppressEvents;
private float _lastRepeat;
public float Time => (float)_time;
public bool AutoAdvance { get; set; } = true;
public bool Paused
{
get; set;
}
public float Speed { get; set; } = 1;
public bool Loop
{
get; set;
}
public bool DestroyOnComplete
{
get; set;
}
public float RepeatInterval
{
get; set;
}
public int NodeCount => _nodes.Count;
public int QuadCount
{
get; private set;
}
public bool IsAlive
{
get; private set;
}
public string Error
{
get; private set;
}
public void Initialize(OriginalEffectResources resources, int groupId, uint seed = 1,
OriginalEffectOverrides overrides = null, Action<string> sound = null)
{
if (overrides != null && overrides.Version != 1)
throw new NotSupportedException($"Unknown original effect override version {overrides.Version}");
_resources = resources;
_groupId = groupId;
_seed = seed == 0 ? 1 : seed;
_overrides = overrides;
_sound = sound;
ResetSimulation();
}
private void ResetSimulation(bool resetRandom = true)
{
ClearNodes();
_time = 0;
_accumulator = 0;
_lastRepeat = 0;
Error = null;
if (resetRandom)
_spawnSequence = 0;
try
{
AddGroup(_groupId, Vector3.zero);
IsAlive = _nodes.Count > 0;
}
catch (Exception ex)
{
Error = ex.Message;
ClearNodes();
IsAlive = false;
}
}
internal void AddGroup(int groupId, Vector3 position)
{
if (groupId < 0 || groupId >= _resources.Definitions.Groups.Length)
throw new ArgumentOutOfRangeException(nameof(groupId));
EffectGroup group = _resources.Definitions.Groups[groupId];
for (int i = 0; i < group.Objects.Length; i++)
{
EffectGroupObject obj = group.Objects[i];
_resources.Definitions.TryGetType(obj.TypeCrc, out EffectDefinition d);
EffectTask[] tasks = obj.Tasks;
if (!OriginalEffectOverrides.Resolve(_overrides, groupId, i, ref d, ref tasks))
continue;
if (_nodes.Count >= 2048)
throw new InvalidOperationException("Original effect object limit (2048) reached");
obj = new EffectGroupObject { TypeCrc = obj.TypeCrc, Tasks = tasks };
var root = new GameObject($"{groupId}:{i} {d.TypeName}") { hideFlags = HideFlags.DontSave, layer = gameObject.layer };
root.transform.SetParent(transform, false);
OriginalEffectNode node = null;
try
{
string kind = EffectClass.Name(d.ClassNameCrc);
uint seed = _seed + _spawnSequence++ * 7919 + (uint)(groupId * 104729 + i);
node = kind switch
{
"callback" or "audio" => new OriginalControlNode(root, d, obj.Tasks, position, Time, this, kind),
"quad" => new OriginalQuadNode(root, d, obj.Tasks, position, Time, _resources),
"particle" => new OriginalParticleNode(root, d, obj.Tasks, position, Time, _resources, seed, _overrides),
"cylinder" or "grid" => new OriginalGeometryNode(root, d, obj.Tasks, position, Time, _resources, kind),
"meteor" or "shock" => new OriginalTrailNode(root, d, obj.Tasks, position, Time, _resources, kind, seed),
"model" => new OriginalModelNode(root, d, obj.Tasks, position, Time, _resources),
_ => throw new NotSupportedException($"Original effect class {kind}: {d.TypeName}"),
};
_nodes.Add(node);
}
catch
{
node?.Dispose();
OriginalEffectResources.Destroy(root);
throw;
}
}
}
internal void Sound(string name)
{
if (!_suppressEvents)
_sound?.Invoke(name);
}
public void Advance(float delta)
{
float elapsed = ScaledDelta(delta);
if (elapsed <= 0)
return;
_accumulator += elapsed;
while (_accumulator + 0.000001f >= FixedStep)
{
_accumulator -= FixedStep;
if (!SimulateStep(FixedStep))
break;
}
}
public void AdvanceFrame(float delta)
{
float elapsed = ScaledDelta(delta);
if (elapsed <= 0)
return;
elapsed += _accumulator;
_accumulator = 0;
SimulateStep(elapsed);
}
private float ScaledDelta(float delta)
{
if (_disposed || Paused || Error != null || delta <= 0 || !float.IsFinite(delta))
return 0;
float elapsed = delta * (float.IsFinite(Speed) ? Mathf.Clamp(Speed, 0, 16) : 1);
return float.IsFinite(elapsed) ? elapsed : 0;
}
private bool SimulateStep(float delta)
{
_time += delta;
try
{
int count = _nodes.Count;
bool alive = false;
for (int i = 0; i < count; i++)
{
_nodes[i].Step(Time, delta);
alive |= _nodes[i].Alive;
}
IsAlive = alive || _nodes.Count > count;
for (int i = _nodes.Count - 1; i >= 0; i--)
if (!_nodes[i].Alive)
{
_nodes[i].Dispose();
_nodes.RemoveAt(i);
}
if (Loop && RepeatInterval > 0 && Time - _lastRepeat >= RepeatInterval)
{
AddGroup(_groupId, Vector3.zero);
_lastRepeat = Time;
IsAlive = true;
}
if (Loop && !IsAlive && RepeatInterval <= 0)
{
ResetSimulation(false);
return false;
}
return true;
}
catch (Exception ex)
{
Error = ex.ToString();
ClearNodes();
IsAlive = false;
Debug.LogException(ex);
return false;
}
}
public void Seek(float time)
{
if (_disposed)
return;
time = Mathf.Clamp(float.IsFinite(time) ? time : 0, 0, 600);
bool paused = Paused, loop = Loop;
float speed = Speed;
ResetSimulation();
Paused = false;
Loop = false;
Speed = 1;
_suppressEvents = true;
try
{
Advance(time);
}
finally
{
_suppressEvents = false;
Paused = paused;
Loop = loop;
Speed = speed;
}
}
public void Render(Camera camera)
{
QuadCount = 0;
foreach (OriginalEffectNode node in _nodes)
{
node.Render(camera);
QuadCount += node.QuadCount;
}
}
private void Update()
{
if (!AutoAdvance)
return;
AdvanceFrame(UnityEngine.Time.deltaTime);
if (DestroyOnComplete && !Loop && !IsAlive && Time > 0)
OriginalEffectResources.Destroy(gameObject);
}
private void LateUpdate()
{
if (AutoAdvance)
Render(Camera.main);
}
private void ClearNodes()
{
foreach (OriginalEffectNode node in _nodes)
node.Dispose();
_nodes.Clear();
QuadCount = 0;
}
private void OnDestroy()
{
_disposed = true;
ClearNodes();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7b4e14dc881ee4e348d1125f142c9dc4
@@ -0,0 +1,400 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Game.Effect.Original
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Core.DataReader;
using Core.DataReader.Data;
using Core.DataReader.Cvd;
using Core.DataReader.Par;
using Core.FileSystem;
using Data;
using Engine.Core.Implementation;
using Engine.Core.Abstraction;
using UnityEngine;
using UnityEngine.Rendering;
public sealed class OriginalEffectResources : IDisposable
{
private readonly ICpkFileSystem _fileSystem;
private readonly int _codepage;
private readonly Dictionary<string, Texture2D> _textures = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, ParticleFile> _particles = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, byte[]> _particleBytes = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, ParticleFile> _overrideParticles = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, ParticleShapeFile> _shapes = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, CvdFile> _models = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<(string, bool, bool, int), Material> _materials = new();
private readonly Dictionary<int, string[]> _diagnostics = new();
private readonly Dictionary<int, string[]> _overrideDiagnostics = new();
private OriginalEffectOverrides _cachedOverrides;
private string _cachedOverridesJson;
private EffectDefinitionFile _definitions;
public EffectDefinitionFile Definitions => _definitions ??= Read<EffectDefinitionFile>("cbdata\\flexeff.data", new EffectDefinitionFileReader());
public OriginalEffectResources(ICpkFileSystem fileSystem, int codepage = 936)
{
_fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem));
_codepage = codepage;
}
public static string Normalize(string path)
{
path = path.Replace('/', '\\');
return path.StartsWith("basedata.cpk\\", StringComparison.OrdinalIgnoreCase) ? path : "basedata.cpk\\" + path;
}
public byte[] Bytes(string path) => _fileSystem.ReadAllBytes(Normalize(path));
public T Read<T>(string path, IFileReader<T> reader) => reader.Read(Bytes(path), _codepage);
public ITextureResourceProvider ModelTextureProvider(string file) => new ModelTextures(this, file);
private sealed class ModelTextures : ITextureResourceProvider
{
private readonly OriginalEffectResources _owner;
private readonly string _file;
public ModelTextures(OriginalEffectResources owner, string file)
{
_owner = owner;
_file = file;
}
public string GetTexturePath(string name) => RelativeTo(_file, name);
public ITexture2D GetTexture(string name) => GetTexture(name, out _);
public ITexture2D GetTexture(string name, out bool hasAlphaChannel)
{
hasAlphaChannel = true;
return new UnityTexture2D(_owner.Texture(GetTexturePath(name)));
}
}
public ParticleFile Particle(string path, OriginalEffectOverrides edits = null)
{
path = Normalize(path);
if (!_particles.TryGetValue(path, out ParticleFile file))
{
if (!_particleBytes.TryGetValue(path, out byte[] bytes))
_particleBytes[path] = bytes = Bytes(path);
_particles[path] = file = ((IFileReader<ParticleFile>)new ParticleFileReader()).Read(bytes, _codepage);
}
if (edits != null && edits.HasParticleEdits(path))
{
RefreshOverrideCache(edits);
if (!_overrideParticles.TryGetValue(path, out ParticleFile copy))
{
copy = ((IFileReader<ParticleFile>)new ParticleFileReader()).Read(_particleBytes[path], _codepage);
edits.ApplyParticle(path, copy);
_overrideParticles[path] = copy;
}
return copy;
}
return file;
}
private void RefreshOverrideCache(OriginalEffectOverrides edits)
{
// Public override fields also support scripts, Undo and the native
// Inspector. A content stamp catches those edits without relying on
// every caller to manually invalidate a revision counter.
string json = JsonUtility.ToJson(edits);
if (ReferenceEquals(edits, _cachedOverrides) && json == _cachedOverridesJson)
return;
_cachedOverrides = edits;
_cachedOverridesJson = json;
_overrideDiagnostics.Clear();
_overrideParticles.Clear();
}
public ParticleShapeFile Shape(string path)
{
if (!_shapes.TryGetValue(path, out ParticleShapeFile file))
_shapes.Add(path, file = Read(path, new ParticleShapeFileReader()));
return file;
}
public CvdFile Model(string path)
{
if (!_models.TryGetValue(path, out CvdFile file))
_models.Add(path, file = Read(path, new CvdFileReader()));
return file;
}
public static string RelativeTo(string file, string relative)
{
file = file.Replace('/', '\\');
int slash = file.LastIndexOf('\\');
return (slash < 0 ? "" : file[..(slash + 1)]) + relative.Replace('/', '\\');
}
public string ResolveTexture(string path)
{
path = Normalize(path);
string dds = Path.ChangeExtension(path, ".dds");
if (_fileSystem.FileExists(dds))
return dds;
if (_fileSystem.FileExists(path))
return path;
throw new FileNotFoundException($"Original effect texture not found: {path}", path);
}
public Texture2D Texture(string path)
{
path = ResolveTexture(path);
if (_textures.TryGetValue(path, out Texture2D cached))
return cached;
Texture2D texture;
if (path.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".png", StringComparison.OrdinalIgnoreCase))
{
texture = new Texture2D(2, 2, TextureFormat.RGBA32, false);
if (!texture.LoadImage(Bytes(path), true))
{
Destroy(texture);
throw new InvalidDataException($"Invalid image {path}");
}
}
else
{
var provider = new TextureProvider(_fileSystem, new TextureLoaderFactory(), new UnityTextureFactory(),
"basedata.cpk", usage: TextureUsage.Sprite);
texture = provider.GetTexture(path["basedata.cpk\\".Length..])?.NativeObject as Texture2D;
if (texture == null)
throw new InvalidDataException($"Could not load original effect texture {path}");
}
texture.name = path;
texture.wrapMode = TextureWrapMode.Repeat;
texture.hideFlags = HideFlags.DontSave;
_textures.Add(path, texture);
return texture;
}
public Material Material(string texture, bool additive, bool noZ, int alphaMode = 0)
{
var key = (texture, additive, noZ, alphaMode);
if (_materials.TryGetValue(key, out Material cached))
return cached;
Shader shader = Shader.Find("Pal3/OriginalEffect");
if (shader == null || !shader.isSupported)
throw new InvalidOperationException("OriginalEffect URP shader is unavailable");
var material = new Material(shader) { name = $"Original {texture}", hideFlags = HideFlags.DontSave };
try
{
material.mainTexture = string.IsNullOrEmpty(texture) ? Texture2D.whiteTexture : Texture(texture);
}
catch
{
Destroy(material);
throw;
}
material.SetInt("_SrcBlend", (int)(alphaMode == 1 ? BlendMode.One : BlendMode.SrcAlpha));
material.SetInt("_DstBlend", (int)(additive ? BlendMode.One : BlendMode.OneMinusSrcAlpha));
material.SetInt("_ZTest", (int)(noZ ? CompareFunction.Always : CompareFunction.LessEqual));
material.SetFloat("_AlphaMode", alphaMode);
_materials.Add(key, material);
return material;
}
// Validate the complete callback closure before choosing this backend.
public string[] Diagnose(int groupId, OriginalEffectOverrides edits = null)
{
if (edits != null)
RefreshOverrideCache(edits);
Dictionary<int, string[]> cache = edits == null ? _diagnostics : _overrideDiagnostics;
if (cache.TryGetValue(groupId, out string[] cached))
return cached;
var errors = new List<string>();
var visiting = new HashSet<int>();
var done = new HashSet<int>();
void ModelTextures(string path, CvdGeometryNode node)
{
if (node.IsGeometryNode)
foreach (CvdMeshSection section in node.Mesh.MeshSections)
{
string name = section.Material.TextureFileNames[0];
if (!string.IsNullOrEmpty(name))
ResolveTexture(RelativeTo(path, name));
}
foreach (CvdGeometryNode child in node.Children)
ModelTextures(path, child);
}
void Visit(int id)
{
if (done.Contains(id))
return;
if (!visiting.Add(id))
{
errors.Add($"Recursive callback cycle at group {id}");
return;
}
if (id < 0 || id >= Definitions.Groups.Length)
{
errors.Add($"Group {id} is outside flexeff");
visiting.Remove(id);
return;
}
EffectGroupObject[] objects = Definitions.Groups[id].Objects;
for (int index = 0; index < objects.Length; index++)
{
EffectGroupObject obj = objects[index];
Definitions.TryGetType(obj.TypeCrc, out EffectDefinition d);
try
{
EffectTask[] tasks = obj.Tasks;
if (!OriginalEffectOverrides.Resolve(edits, id, index, ref d, ref tasks))
continue;
string kind = EffectClass.Name(d.ClassNameCrc);
switch (kind)
{
case "callback":
foreach (EffectTask t in tasks)
foreach (var child in t.Callbacks())
Visit(child.groupId);
break;
case "audio":
break;
case "particle":
ParticleFile p = Particle(d.ParticleFileName, edits);
foreach (ParticleDescription pd in p.Particles)
ResolveTexture(RelativeTo(d.ParticleFileName, pd.Texture));
foreach (ParticleEmitter e in p.Emitters)
if (e.Shape == 2)
Shape(RelativeTo(d.ParticleFileName, e.ShapePath));
break;
case "quad":
case "cylinder":
case "meteor":
case "shock":
case "grid":
ResolveTexture(d.TextureName);
break;
case "model":
OriginalModelNode.ValidateTasks(tasks);
if (!_fileSystem.FileExists(Normalize(d.TextureName)))
throw new FileNotFoundException(d.TextureName);
if (!d.TextureName.EndsWith(".cvd", StringComparison.OrdinalIgnoreCase))
throw new NotSupportedException("Original POL effect adapter is not implemented");
foreach (CvdGeometryNode node in Model(d.TextureName).RootNodes)
ModelTextures(d.TextureName, node);
break;
default:
errors.Add($"Group {id}, {d.TypeName}: unsupported original class {kind}");
break;
}
}
catch (Exception ex)
{
errors.Add($"Group {id}, {d.TypeName}: {ex.Message}");
}
}
visiting.Remove(id);
done.Add(id);
}
Visit(groupId);
string[] result = errors.ToArray();
cache[groupId] = result;
return result;
}
public IEnumerable<int> Preload(int groupId, OriginalEffectOverrides edits = null)
{
var seen = new HashSet<int>();
var pending = new Stack<int>();
pending.Push(groupId);
while (pending.Count > 0)
{
int id = pending.Pop();
if (!seen.Add(id))
continue;
EffectGroupObject[] objects = Definitions.Groups[id].Objects;
for (int index = 0; index < objects.Length; index++)
{
EffectGroupObject obj = objects[index];
Definitions.TryGetType(obj.TypeCrc, out EffectDefinition d);
EffectTask[] tasks = obj.Tasks;
if (!OriginalEffectOverrides.Resolve(edits, id, index, ref d, ref tasks))
continue;
string kind = EffectClass.Name(d.ClassNameCrc);
if (kind == "callback")
foreach (EffectTask t in tasks)
foreach (var child in t.Callbacks())
pending.Push(child.groupId);
else if (kind == "particle")
foreach (ParticleDescription p in Particle(d.ParticleFileName, edits).Particles)
Texture(RelativeTo(d.ParticleFileName, p.Texture));
else if (kind != "audio" && kind != "model")
Texture(d.TextureName);
yield return id;
}
}
}
public void TrimUnusedRenderAssets(IEnumerable<GameObject> liveRoots)
{
var materials = new HashSet<Material>();
var textures = new HashSet<Texture>();
foreach (GameObject root in liveRoots)
{
if (root == null)
continue;
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
foreach (Material material in renderer.sharedMaterials)
{
if (material == null)
continue;
materials.Add(material);
if (material.mainTexture != null)
textures.Add(material.mainTexture);
}
}
foreach (var key in _materials.Where(p => !materials.Contains(p.Value)).Select(p => p.Key).ToArray())
{
Destroy(_materials[key]);
_materials.Remove(key);
}
foreach (string key in _textures.Where(p => !textures.Contains(p.Value)).Select(p => p.Key).ToArray())
{
Destroy(_textures[key]);
_textures.Remove(key);
}
}
public void Dispose()
{
foreach (Material m in _materials.Values)
Destroy(m);
foreach (Texture2D t in _textures.Values)
Destroy(t);
_materials.Clear();
_textures.Clear();
_particles.Clear();
_particleBytes.Clear();
_overrideParticles.Clear();
_shapes.Clear();
_models.Clear();
_diagnostics.Clear();
_overrideDiagnostics.Clear();
_cachedOverrides = null;
_cachedOverridesJson = null;
}
public static void Destroy(UnityEngine.Object value)
{
if (value == null)
return;
if (Application.isPlaying)
UnityEngine.Object.Destroy(value);
else
UnityEngine.Object.DestroyImmediate(value);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 6df74732b3a2d44b69e9ed674b10f621
@@ -0,0 +1,151 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Game.Effect.Original
{
using System;
using UnityEngine;
// Runtime controls for ResourceViewer; editor tooling uses the same player.
public sealed class OriginalEffectViewer : MonoBehaviour
{
private static int _nextWindowId = 25000;
private readonly int _windowId = _nextWindowId++;
private OriginalEffectResources _resources;
private Transform _parent;
private Action _beforeLoad;
private OriginalEffectPlayer _player;
private OriginalPortalEffect _portal;
private GameObject _root;
private string _id = "98", _diagnostics = "";
private Rect _window = new(15, 65, 330, 250);
private bool _visible;
public void Initialize(OriginalEffectResources resources, Transform parent, Action beforeLoad)
{
_resources = resources;
_parent = parent;
_beforeLoad = beforeLoad;
}
public void Load(int groupId)
{
Stop();
_beforeLoad?.Invoke();
_id = groupId.ToString();
_visible = true;
_diagnostics = "";
try
{
if (groupId < -1)
throw new ArgumentOutOfRangeException(nameof(groupId));
OriginalEffectOverrides edits = Resources.Load<OriginalEffectOverrides>("Effects/PAL3Overrides");
if (groupId >= 0)
{
_diagnostics = string.Join("\n", _resources.Diagnose(groupId, edits));
if (_diagnostics.Length > 0)
return;
}
_root = new GameObject(groupId < 0 ? "Original Transport" : $"Original PAL3 group {groupId}");
_root.transform.SetParent(_parent, false);
if (groupId < 0)
{
_portal = _root.AddComponent<OriginalPortalEffect>();
_portal.Initialize(_resources);
}
else
{
_player = _root.AddComponent<OriginalEffectPlayer>();
_player.Initialize(_resources, groupId, overrides: edits);
_diagnostics += _player.Error;
}
}
catch (Exception ex)
{
_diagnostics = ex.Message;
Stop();
}
}
public void Stop()
{
if (_root != null)
{
_root.SetActive(false);
OriginalEffectResources.Destroy(_root);
}
_root = null;
_player = null;
_portal = null;
}
public void Seek(float time)
{
time = Mathf.Clamp(float.IsFinite(time) ? time : 0, 0, 600);
if (_player != null)
_player.Seek(time);
if (_portal != null)
_portal.Sample(time);
}
public void Pause(bool value)
{
if (_player != null)
_player.Paused = value;
if (_portal != null)
_portal.AutoAdvance = !value;
}
private void OnDisable() => Stop();
private void OnGUI()
{
if (_resources == null)
return;
if (GUI.Button(new Rect(Screen.width - 145, 15, 130, 32), "Original PAL3 effects"))
_visible = !_visible;
if (_visible)
_window = GUI.Window(_windowId, _window, Draw, "Original PAL3 effect viewer");
}
private void Draw(int id)
{
GUILayout.BeginHorizontal();
GUILayout.Label("Group", GUILayout.Width(45));
_id = GUILayout.TextField(_id);
if (GUILayout.Button("Load") && int.TryParse(_id, out int group))
Load(group);
if (GUILayout.Button("Transport"))
Load(-1);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if (GUILayout.Button("Play"))
Pause(false);
if (GUILayout.Button("Pause"))
Pause(true);
if (GUILayout.Button("Reset"))
Seek(0);
if (GUILayout.Button("Stop"))
Stop();
GUILayout.EndHorizontal();
if (_player != null)
{
_player.Speed = GUILayout.HorizontalSlider(_player.Speed, 0, 4);
GUILayout.Label($"Speed {_player.Speed:0.00}x");
float time = GUILayout.HorizontalSlider(_player.Time, 0, Mathf.Max(30, _player.Time));
if (Mathf.Abs(time - _player.Time) > 0.001f)
{
Pause(true);
Seek(time);
}
GUILayout.Label($"{_player.Time:0.00}s objects {_player.NodeCount} quads/particles {_player.QuadCount}");
if (_player.Error != null)
GUILayout.Label(_player.Error);
}
GUILayout.Label(_diagnostics.Length == 0 ? "Original data / shared runtime" : _diagnostics);
GUI.DragWindow();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a67dbb1e7d0e340fe8b5dc4ca7bbecb5
@@ -0,0 +1,128 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Game.Effect.Original
{
using Core.DataReader.Data;
using UnityEngine;
internal sealed class OriginalGeometryNode : OriginalEffectNode
{
private readonly EffectMeshBuffer _mesh;
private readonly string _kind;
private readonly Vector3[] _points;
private readonly int _columns, _rows;
public override int QuadCount => _mesh.QuadCount;
public OriginalGeometryNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, OriginalEffectResources resources, string kind)
: base(root, d, tasks, origin, birth)
{
_kind = kind;
Scale = new Vector3(d.InitSize, 1, d.InitSize);
_mesh = new EffectMeshBuffer(root, resources.Material(d.TextureName, d.IsAdditiveBlend, d.IsZTestIgnored));
if (kind == "cylinder")
{
_columns = Mathf.Clamp(Mathf.RoundToInt(d.DivisionCount), 1, 4096);
_rows = 1;
_points = new Vector3[(_columns + 1) * 2];
for (int i = 0; i <= _columns; i++)
{
float a = i * d.RotationAngle / _columns;
float top = d.TopRadius + d.TopRadiusIncreaseSpeed * a - (i % 2 == 1 ? d.TopShrink : 0);
float bottom = d.BottomRadius + d.BottomRadiusIncreaseSpeed * a - (i % 2 == 1 ? d.BottomShrink : 0);
float rad = a * Mathf.Deg2Rad;
_points[i * 2] = new Vector3(Mathf.Sin(rad) * bottom, d.BottomRiseSpeed * a, Mathf.Cos(rad) * bottom);
_points[i * 2 + 1] = new Vector3(Mathf.Sin(rad) * top, d.Width + d.TopRiseSpeed * a, Mathf.Cos(rad) * top);
}
}
else
{
_columns = Mathf.Clamp(Mathf.RoundToInt(d.RotationAngle), 1, 128);
_rows = Mathf.Clamp(Mathf.RoundToInt(d.DivisionCount), 1, 128);
_points = new Vector3[(_columns + 1) * (_rows + 1)];
for (int z = 0; z <= _rows; z++)
for (int x = 0; x <= _columns; x++)
_points[z * (_columns + 1) + x] = new Vector3((x - _columns * 0.5f) * d.Width, 0, (_rows * 0.5f - z) * d.Width);
}
}
protected override void Apply(EffectTask t, OriginalTaskClock clock, float dt)
{
base.Apply(t, clock, dt);
if (_kind == "cylinder")
{
Scale.z = Scale.x;
// The union at CreateTimeSlot is UV speed for cylinders, not
// Z stretch. GameBox resets a positive V offset after one turn.
if (TextureOffset > 1)
TextureOffset = 0;
}
else
{
// Grid Z stretch shares CreateTimeSlot; YStretchSpeed is not
// used by CEffGrid (height comes from its flap calculation).
Scale.y = 1;
}
}
public override void Render(Camera camera)
{
_mesh.Clear();
if (!Alive || !Visible)
{
_mesh.Upload();
return;
}
var uv = Atlas(LocalTime);
Quaternion rot = RawRotation(Rotation);
Vector3 P(int index)
{
Vector3 p = _points[index];
if (_kind == "grid")
{
float x = index % (_columns + 1), z = index / (_columns + 1);
float sin = Mathf.Sin((LocalTime + x + 1) * Definition.BottomRadius + z + 1);
float cos = Mathf.Cos((LocalTime + z + 1) * Definition.BottomRadius + x + 1);
p.x += (sin - cos) * Definition.TopRadius;
p.z += (cos + sin) * Definition.TopRadius;
p.y += Mathf.Sin(LocalTime * Definition.TopRadiusIncreaseSpeed + x) * Definition.TextureRepeat;
}
return UnityPosition(Position + Orbit + rot * Vector3.Scale(p, Scale));
}
if (_kind == "cylinder")
{
float repeat = Definition.TextureRepeat;
for (int i = 0; i < _columns; i++)
{
float u0 = uv.min.x + (uv.max.x - uv.min.x) * repeat * i / _columns;
float u1 = uv.min.x + (uv.max.x - uv.min.x) * repeat * (i + 1) / _columns;
_mesh.Quad(P(i * 2), P(i * 2 + 2), P(i * 2 + 3), P(i * 2 + 1),
new Vector2(u0, uv.min.y + TextureOffset), new Vector2(u1, uv.max.y + TextureOffset), Tint);
}
}
else
{
for (int z = 0; z < _rows; z++)
for (int x = 0; x < _columns; x++)
{
int i = z * (_columns + 1) + x;
Vector2 a = Vector2.Lerp(uv.min, uv.max, 0);
a.x = Mathf.Lerp(uv.min.x, uv.max.x, (float)x / _columns);
a.y = Mathf.Lerp(uv.min.y, uv.max.y, (float)z / _rows);
Vector2 b = new(Mathf.Lerp(uv.min.x, uv.max.x, (float)(x + 1) / _columns), Mathf.Lerp(uv.min.y, uv.max.y, (float)(z + 1) / _rows));
_mesh.Quad(P(i), P(i + 1), P(i + _columns + 2), P(i + _columns + 1), a, b, Tint);
}
}
_mesh.Upload();
}
public override void Dispose()
{
_mesh.Dispose();
base.Dispose();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: b4096b3ce200a447ba269be4a95c0f5a
@@ -0,0 +1,88 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Game.Effect.Original
{
using System;
using Core.DataReader.Data;
using Engine.Core.Implementation;
using Rendering.Material;
using Rendering.Renderer;
using UnityEngine;
internal sealed class OriginalModelNode : OriginalEffectNode
{
private const float ReferenceFramesPerSecond = 60f;
private readonly CvdModelRenderer _model;
private readonly GameMaterialManager _materials;
private readonly Renderer[] _renderers;
private float _animationStart;
public OriginalModelNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, OriginalEffectResources resources)
: base(root, d, tasks, origin, birth)
{
ValidateTasks(Tasks);
if (!d.TextureName.EndsWith(".cvd", StringComparison.OrdinalIgnoreCase))
throw new NotSupportedException($"Original model adapter requires CVD: {d.TextureName}");
// Use the same texture resolution and existing CVD renderer as the game.
_materials = new GameMaterialManager(new UnityMaterialFactory(), false);
_model = root.AddComponent<CvdModelRenderer>();
try
{
_model.Init(resources.Model(d.TextureName), resources.ModelTextureProvider(d.TextureName), _materials);
}
catch
{
_model.Dispose();
_materials.Dispose();
throw;
}
_renderers = root.GetComponentsInChildren<Renderer>();
foreach (Transform child in root.GetComponentsInChildren<Transform>())
child.gameObject.layer = root.layer;
}
internal static void ValidateTasks(EffectTask[] tasks)
{
// CEffModel uses normalized alpha, unlike the 0..255 color tasks.
// The CVD renderer does not yet expose its model-wide blend override.
if (Array.Exists(tasks, task => task.SpeedAlpha != 0))
throw new NotSupportedException("Original CVD model opacity tasks are not implemented");
}
protected override void Apply(EffectTask t, OriginalTaskClock clock, float dt)
{
if (clock.StartedNow)
_animationStart = LocalTime;
base.Apply(t, clock, dt);
}
protected override void ApplyRotationAndStretch(EffectTask t, float dt)
{
// CEffModel.cpp:238-245 adds these values once per update. Normalize
// to our chosen 60 FPS compatibility reference, independently of
// the display frame rate and the editor/seek integration step.
base.ApplyRotationAndStretch(t, dt * ReferenceFramesPerSecond);
}
public override void Render(Camera camera)
{
Root.transform.localPosition = UnityPosition(Position + Orbit);
Root.transform.localRotation = UnityRotation(Rotation);
Root.transform.localScale = Scale;
foreach (Renderer renderer in _renderers)
renderer.enabled = Alive && Visible;
if (Alive && Visible)
_model.SetCurrentTime(Mathf.Max(0, LocalTime - _animationStart));
}
public override void Dispose()
{
_model.Dispose();
_materials.Dispose();
base.Dispose();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 931441919a39d495fa8277a0dca473d0
@@ -0,0 +1,279 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Game.Effect.Original
{
using System;
using Core.DataReader.Data;
using Core.DataReader.Par;
using Core.Primitives;
using UnityEngine;
using UnityEngine.Rendering;
// sgpar's sampled curves and drag do not match Shuriken modules exactly.
// Simulate those semantics in C#, and use the native particle renderer.
// This is PAL3's CEffgbParticle -> ParticleEffect/particle.cpp path, not
// gbengine9/physics/gbparteffect.cpp: the combat implementation scales both
// scope and displacement and forces ONE/ONE blending regardless of BlendMode.
internal sealed class OriginalParticleNode : OriginalEffectNode
{
private struct Unit
{
public Vector3 Position, Velocity;
public float Age, Life, Size, Rotation, Direction;
public int Row;
public bool Alive;
}
private sealed class Controller
{
public ParticleDescription Particle;
public ParticleEmitter Emitter;
public ParticleShapeFile Shape;
public ParticleSystem System;
public ParticleSystem.Particle[] Output;
public Unit[] Units;
public float CycleTime, Accumulator;
public int Count;
public bool Emitting = true;
}
private readonly ParticleFile _file;
private readonly Controller[] _controllers;
private readonly System.Random _random;
private float _spaceScale;
private bool _loopEmission;
public override int QuadCount
{
get
{
int n = 0;
foreach (Controller c in _controllers)
n += c.Count;
return n;
}
}
public OriginalParticleNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth,
OriginalEffectResources resources, uint seed, OriginalEffectOverrides edits) : base(root, d, tasks, origin, birth)
{
_random = new System.Random(unchecked((int)seed));
_file = resources.Particle(d.ParticleFileName, edits);
_spaceScale = d.InitSize;
_controllers = new Controller[_file.Controllers.Length];
for (int i = 0; i < _controllers.Length; i++)
{
ParticleController source = _file.Controllers[i];
var c = new Controller { Particle = _file.Particles[source.ParticleIndex], Emitter = _file.Emitters[source.EmitterIndex] };
int capacity = Mathf.Clamp(_file.Capacity, 1, 65536);
c.Units = new Unit[capacity];
c.Output = new ParticleSystem.Particle[capacity];
var child = new GameObject(c.Particle.Name) { hideFlags = HideFlags.DontSave, layer = root.layer };
child.transform.SetParent(root.transform, false);
c.System = child.AddComponent<ParticleSystem>();
c.System.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
var main = c.System.main;
main.playOnAwake = false;
main.maxParticles = capacity;
main.simulationSpace = ParticleSystemSimulationSpace.Local;
main.gravityModifier = 0;
main.startSpeed = 0;
main.startLifetime = 10000;
main.startSize = 1;
main.cullingMode = ParticleSystemCullingMode.AlwaysSimulate;
c.System.useAutoRandomSeed = false;
c.System.randomSeed = seed + (uint)i;
var emission = c.System.emission;
emission.enabled = false;
var shape = c.System.shape;
shape.enabled = false;
var renderer = c.System.GetComponent<ParticleSystemRenderer>();
renderer.sharedMaterial = resources.Material(OriginalEffectResources.RelativeTo(d.ParticleFileName, c.Particle.Texture), true, false, 1);
renderer.renderMode = ParticleSystemRenderMode.Billboard;
renderer.alignment = ParticleSystemRenderSpace.View;
renderer.minParticleSize = 0;
renderer.maxParticleSize = 100;
renderer.shadowCastingMode = ShadowCastingMode.Off;
renderer.receiveShadows = false;
renderer.sortMode = ParticleSystemSortMode.None;
var atlas = c.System.textureSheetAnimation;
atlas.enabled = true;
atlas.numTilesX = c.Particle.Columns;
atlas.numTilesY = c.Particle.Rows;
atlas.animation = ParticleSystemAnimationType.WholeSheet;
atlas.cycleCount = 1;
atlas.frameOverTime = new ParticleSystem.MinMaxCurve(1, AnimationCurve.Linear(0, 0, 1, 1));
// A stopped system can discard externally supplied particles in
// editor preview. Keep it initialized and paused; C# owns time.
c.System.Play(false);
c.System.Pause(false);
if (c.Emitter.Shape == 2)
c.Shape = resources.Shape(OriginalEffectResources.RelativeTo(d.ParticleFileName, c.Emitter.ShapePath));
_controllers[i] = c;
}
}
protected override void Apply(EffectTask t, OriginalTaskClock clock, float dt)
{
if (clock.StartedNow)
_loopEmission = true;
Position += new Vector3(t.SpeedX, t.SpeedY, t.SpeedZ) * dt;
_spaceScale = Mathf.Max(0.001f, _spaceScale + t.XStretchSpeed * dt);
Vector3 axis = new(t.CircleAxisX, t.CircleAxisY, t.CircleAxisZ);
Orbit = OrbitPosition(axis, (LocalTime - clock.StartedAt) * t.CircleSpeed, t.CircleRadius);
}
public override void Step(float time, float dt)
{
foreach (Controller c in _controllers)
{
ParticleEmitter e = c.Emitter;
ParticleDescription p = c.Particle;
float cycle = Mathf.Max(0.000001f, e.CycleMin - e.CycleMax);
c.CycleTime += dt;
// sgpar starts with one active emitter cycle. CEffgbParticle
// updates it before the tasks, which control future looping;
// disabling looping lets the current cycle finish normally.
if (c.CycleTime > cycle)
{
c.Emitting = _loopEmission;
if (_loopEmission)
c.CycleTime = 0;
}
float phase = c.CycleTime / cycle;
int lo = (int)(e.Emission.Evaluate(phase, 0) * e.SpeedMultiplier);
int hi = (int)(e.Emission.Evaluate(phase, 1) * e.SpeedMultiplier);
if (c.Emitting)
{
c.Accumulator += RandomRange(lo, hi) * dt;
int number = Mathf.Clamp((int)c.Accumulator, 0, c.Units.Length);
c.Accumulator -= number;
for (int n = 0; n < number; n++)
{
int slot = Array.FindIndex(c.Units, u => !u.Alive);
if (slot < 0)
{
if (_file.Overflow == 0)
break;
slot = _file.Overflow == 2 ? _random.Next(c.Units.Length) : Oldest(c.Units);
}
c.Units[slot] = Spawn(c, phase);
}
}
c.Count = 0;
for (int i = 0; i < c.Units.Length; i++)
{
ref Unit u = ref c.Units[i];
if (!u.Alive)
continue;
u.Age += dt;
if (u.Age > u.Life)
{
u.Alive = false;
continue;
}
float t = u.Age / u.Life;
if (u.Velocity.magnitude > p.NoResistanceSpeed)
{
Vector3 drag = u.Velocity * p.Resistance;
if (p.SizeResistancePower != 0)
drag += u.Velocity.normalized * (u.Size * p.Resistance);
u.Velocity -= drag * dt;
}
u.Size = p.Size.Evaluate(t);
u.Rotation = (u.Rotation + (p.Rotation.Evaluate(t) + RandomRange(p.RotationStart, p.RotationEnd)) * dt) * u.Direction;
Vector3 offset = u.Velocity * dt;
offset.y -= p.Gravity * dt * dt / 2;
u.Velocity.y -= p.Gravity * dt;
u.Position += offset * _spaceScale;
c.Count++;
}
}
base.Step(time, dt);
if (!Alive)
_loopEmission = false;
foreach (Controller c in _controllers)
Alive |= c.Count > 0;
}
private Unit Spawn(Controller c, float t)
{
ParticleEmitter e = c.Emitter;
ParticleDescription p = c.Particle;
Vector3 direction = new(e.Direction.Evaluate(t, 0), e.Direction.Evaluate(t, 1), e.Direction.Evaluate(t, 2));
Vector3 scope = Raw(e.Scope) * _spaceScale;
Vector3 velocity = direction * RandomRange(e.RandomVelocity.Evaluate(t, 0), e.RandomVelocity.Evaluate(t, 1))
+ new Vector3(RandomRange(-scope.x, scope.x), RandomRange(-scope.y, scope.y), RandomRange(-scope.z, scope.z));
Vector3 position;
if (e.Shape == 2)
position = Raw(c.Shape.Points[_random.Next(c.Shape.Points.Length)]);
else if (e.Shape == 1)
position = new Vector3(RandomRange(-100, 100), RandomRange(-100, 100), RandomRange(-100, 100)).normalized
* RandomRange(0, _random.Next(2) == 0 ? e.Hotspot : e.Hotspot + e.Falloff);
else
position = new Vector3(RandomRange(e.BoxMin.X, e.BoxMax.X), RandomRange(e.BoxMin.Y, e.BoxMax.Y), RandomRange(e.BoxMin.Z, e.BoxMax.Z));
position = (position + Raw(e.Position)) * _spaceScale;
return new Unit
{
Alive = true,
Position = position,
Velocity = velocity,
Direction = p.RandomRotationDirection && _random.Next(2) == 0 ? -1 : 1,
Life = Mathf.Max(0.000001f, RandomRange(e.Life.Evaluate(t, 0), e.Life.Evaluate(t, 1))),
Size = p.Size.Evaluate(0),
Row = _random.Next(p.Rows)
};
}
public override void Render(Camera camera)
{
foreach (Controller c in _controllers)
{
int n = 0;
ParticleDescription p = c.Particle;
for (int i = 0; i < c.Units.Length; i++)
{
Unit u = c.Units[i];
if (!u.Alive)
continue;
float phase = u.Age / u.Life;
int frame = Mathf.Min(p.Columns - 1, (int)(phase * p.Columns));
// Native texture-sheet lookup uses normalized remaining life.
float atlasLife = (u.Row * p.Columns + frame + 0.25f) / (p.Rows * p.Columns);
var color = new UnityEngine.Color(p.Color.Evaluate(phase, 0) / 255, p.Color.Evaluate(phase, 1) / 255,
p.Color.Evaluate(phase, 2) / 255, p.Alpha.Evaluate(phase));
// CEffgbParticle translates the view for the entire effect,
// even for sgpar's world-space mode. Task motion therefore
// moves existing particles as well as newly emitted ones.
c.Output[n++] = new ParticleSystem.Particle
{
position = UnityPosition(u.Position + Position + Orbit),
startSize = Mathf.Abs(u.Size * _spaceScale / 20),
rotation = -u.Rotation,
startColor = color,
startLifetime = 1,
remainingLifetime = 1 - atlasLife,
randomSeed = (uint)(i + 1)
};
}
c.System.SetParticles(c.Output, n);
}
}
private float RandomRange(float a, float b) => a + (b - a) * ((float)_random.Next(1, 10001) / 10000);
private static Vector3 Raw(GameBoxVector3 v) => new(v.X, v.Y, v.Z);
private static int Oldest(Unit[] units)
{
int result = 0;
for (int i = 1; i < units.Length; i++)
if (units[i].Age > units[result].Age)
result = i;
return result;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 13f42c5931db146b8a60320470832551
@@ -0,0 +1,73 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Game.Effect.Original
{
using UnityEngine;
// MXTransport is a scene effect, not flexeff group zero.
public sealed class OriginalPortalEffect : MonoBehaviour
{
private EffectMeshBuffer _base, _outer, _inner;
private float _time;
public bool AutoAdvance { get; set; } = true;
public void Initialize(OriginalEffectResources resources)
{
GameObject Child(string name)
{
var go = new GameObject(name) { hideFlags = HideFlags.DontSave, layer = gameObject.layer };
go.transform.SetParent(transform, false);
return go;
}
_base = new EffectMeshBuffer(Child("Transport plane"), resources.Material("effect\\trans.tga", true, false, 2));
_outer = new EffectMeshBuffer(Child("Transport outer cone"), resources.Material("effect\\ray.tga", true, false, 2));
_inner = new EffectMeshBuffer(Child("Transport inner cone"), resources.Material("effect\\ray.tga", true, false, 2));
Sample(0);
}
public void Sample(float time)
{
_time = time;
if (_base == null)
return;
_base.Clear();
Quaternion rotation = Quaternion.AngleAxis(-time * 32 * 0.2f, Vector3.up);
Vector3 P(float x, float z) => OriginalEffectNode.UnityPosition(rotation * new Vector3(x, 0, z));
_base.Quad(P(-36, -36), P(-36, 36), P(36, 36), P(36, -36), Vector2.zero, Vector2.one, Color.white);
_base.Upload();
Cone(_outer, 41, 28, 50, rotation, new Color32(245, 188, 28, 255));
Cone(_inner, 34, 18, 68, Quaternion.AngleAxis(-time * 32 * 2, Vector3.up), new Color32(10, 67, 227, 255));
}
private static void Cone(EffectMeshBuffer mesh, float top, float bottom, float height, Quaternion rotation, Color32 color)
{
mesh.Clear();
Vector3 P(int i, float radius, float y)
{
float a = i * 2 * Mathf.PI / 6;
return OriginalEffectNode.UnityPosition(rotation * new Vector3(Mathf.Cos(a) * radius, y, Mathf.Sin(a) * radius));
}
for (int i = 0; i < 6; i++)
mesh.Quad(P(i, bottom, 0), P(i + 1, bottom, 0), P(i + 1, top, height), P(i, top, height),
new Vector2(i / 3f, 0), new Vector2((i + 1) / 3f, 0.94f), color);
mesh.Upload();
}
private void Update()
{
if (AutoAdvance)
Sample(_time + Time.deltaTime);
}
private void OnDestroy()
{
_base?.Dispose();
_outer?.Dispose();
_inner?.Dispose();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 279668a7de3554dc9b94b925ca64ee9d
@@ -0,0 +1,147 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Game.Effect.Original
{
using System.Collections.Generic;
using Core.DataReader.Data;
using UnityEngine;
internal sealed class OriginalQuadNode : OriginalEffectNode
{
private sealed class Quad
{
public Vector3 Position, Rotation, Orbit;
public Vector2 Size;
public Color Color;
public float Age;
public Quad Copy() => new() { Position = Position, Rotation = Rotation, Orbit = Orbit, Size = Size, Color = Color };
}
private readonly List<Quad> _quads = new();
private readonly EffectMeshBuffer _mesh;
private readonly float[] _spawnAt, _lastSpawn;
private readonly int _loops;
public override int QuadCount => _mesh.QuadCount;
public OriginalQuadNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, OriginalEffectResources resources)
: base(root, d, tasks, origin, birth)
{
_mesh = new EffectMeshBuffer(root, resources.Material(d.TextureName, d.IsAdditiveBlend, d.IsZTestIgnored));
_spawnAt = new float[Tasks.Length];
_lastSpawn = new float[Tasks.Length];
for (int i = 0; i < Tasks.Length; i++)
{
_spawnAt[i] = -1;
_loops = Tasks[i].RequireLoops;
}
}
public override void Step(float time, float dt)
{
foreach (Quad q in _quads)
q.Age += dt;
if (Definition.FramePerSecond > 0)
_quads.RemoveAll(q => q.Age * Definition.FramePerSecond >= Mathf.Max(1, Definition.FrameCount) * Mathf.Max(1, _loops));
base.Step(time, dt);
bool emitting = false;
for (int i = 0; i < Tasks.Length; i++)
{
if (Clocks[i].StartedAt < 0)
{
emitting |= !Clocks[i].Finished;
continue;
}
EffectTask t = Tasks[i];
if (_spawnAt[i] < 0 && LocalTime > Clocks[i].StartedAt + 0.000001f)
{
Spawn();
_spawnAt[i] = _lastSpawn[i] = LocalTime;
}
if (_spawnAt[i] < 0)
{
emitting = true;
continue;
}
if (t.CreateNew && LocalTime - _spawnAt[i] <= t.Duration + 0.000001f)
{
if (LocalTime - _lastSpawn[i] >= t.CreateTimeSlot)
{
Spawn();
_lastSpawn[i] = LocalTime;
}
emitting = true;
}
}
Alive |= emitting;
if (!Alive)
_quads.Clear();
}
private void Spawn()
{
if (_quads.Count >= Mathf.Clamp(Definition.MaxQuadCount, 1, 1024))
return;
_quads.Add(_quads.Count > 0 ? _quads[^1].Copy() : new Quad
{
Position = Position,
Rotation = Rotation,
Size = Vector2.one * Definition.InitSize,
Color = Tint
});
}
protected override void Apply(EffectTask t, OriginalTaskClock clock, float dt)
{
int start = t.ModifyLast ? Mathf.Max(0, _quads.Count - 1) : 0;
Vector3 axis = new(t.CircleAxisX, t.CircleAxisY, t.CircleAxisZ);
Vector3 orbit = OrbitPosition(axis, (LocalTime - clock.StartedAt) * t.CircleSpeed, t.CircleRadius);
for (int i = start; i < _quads.Count; i++)
{
Quad q = _quads[i];
q.Size += new Vector2(t.XStretchSpeed, t.YStretchSpeed) * dt;
q.Position += new Vector3(t.SpeedX, t.SpeedY, t.SpeedZ) * dt;
q.Rotation += new Vector3(t.RotAxisX, t.SpeedRot + t.RotAxisY, t.RotAxisZ) * dt;
q.Color = ChangedColor(q.Color, t, dt);
q.Orbit = orbit;
}
}
public override void Render(Camera camera)
{
_mesh.Clear();
foreach (Quad q in _quads)
{
var uv = Atlas(q.Age);
Vector3 center = UnityPosition(q.Position + q.Orbit);
if (Definition.IsBillboard)
{
Vector3 right = camera != null ? Root.transform.InverseTransformVector(camera.transform.right) : Vector3.right;
Vector3 up = camera != null ? Root.transform.InverseTransformVector(camera.transform.up) : Vector3.up;
Vector3 forward = Vector3.Cross(right, up).normalized;
Quaternion spin = Quaternion.AngleAxis(-q.Rotation.y, forward);
right = spin * right * (q.Size.x / 20);
up = spin * up * (q.Size.y / 20);
_mesh.Quad(center - right - up, center + right - up, center + right + up, center - right + up, uv.min, uv.max, q.Color);
}
else
{
Quaternion r = RawRotation(q.Rotation);
Vector3 P(float x, float z) => UnityPosition(q.Position + q.Orbit + r * new Vector3(x, 0, z));
_mesh.Quad(P(-q.Size.x, q.Size.y), P(q.Size.x, q.Size.y), P(q.Size.x, -q.Size.y), P(-q.Size.x, -q.Size.y), uv.min, uv.max, q.Color);
}
}
_mesh.Upload();
}
public override void Dispose()
{
_mesh.Dispose();
base.Dispose();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 81978aa3bb0d146e1ba874a04516b592
@@ -0,0 +1,200 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Game.Effect.Original
{
using System;
using System.Collections.Generic;
using Core.DataReader.Data;
using UnityEngine;
internal sealed class OriginalTrailNode : OriginalEffectNode
{
private readonly EffectMeshBuffer _mesh, _trailMesh;
private readonly string _kind;
private readonly System.Random _random;
private readonly Vector3 _origin;
private readonly List<Vector3>[] _trails;
private readonly Vector3[] _positions, _velocities;
private readonly bool[] _launched;
private float _meteorTime, _lum;
private readonly float[] _shockFrame, _shockLimit;
private readonly int _shockNodes, _cascades;
public override int QuadCount => _mesh.QuadCount + (_trailMesh?.QuadCount ?? 0);
public OriginalTrailNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth,
OriginalEffectResources resources, string kind, uint seed) : base(root, d, tasks, origin, birth)
{
_kind = kind;
_origin = origin;
_random = new System.Random(unchecked((int)seed));
_mesh = new EffectMeshBuffer(root, resources.Material(d.TextureName, d.IsAdditiveBlend, d.IsZTestIgnored));
_launched = new bool[Tasks.Length];
if (kind == "meteor")
{
var child = new GameObject("Original meteor chain") { hideFlags = HideFlags.DontSave, layer = root.layer };
child.transform.SetParent(root.transform, false);
// CMeteorChain always uses depth-tested additive blending. When
// the meteor has a textured head, its ribbon is untextured.
_trailMesh = new EffectMeshBuffer(child, resources.Material(d.RotationAngle > 0 ? null : d.TextureName, true, false));
_lum = d.TextureRepeat;
int count = Mathf.Clamp(Mathf.Abs(Mathf.RoundToInt(d.RotationAngle)), 1, 512);
_trails = new List<Vector3>[count];
_positions = new Vector3[count];
_velocities = new Vector3[count];
for (int i = 0; i < count; i++)
_trails[i] = new List<Vector3>();
}
else
{
_shockNodes = Mathf.Clamp(Mathf.RoundToInt(d.RotationAngle), 1, 512);
_cascades = Mathf.Clamp(Mathf.RoundToInt(d.Width), 1, 64);
_shockFrame = new float[_shockNodes * _cascades];
_shockLimit = new float[_shockFrame.Length];
}
}
protected override void Apply(EffectTask t, OriginalTaskClock clock, float dt)
{
int task = Array.IndexOf(Tasks, t);
if (_kind == "shock")
{
if (clock.StartedNow)
for (int i = 0; i < _shockFrame.Length; i++)
{
_shockFrame[i] = (float)_random.NextDouble() * Mathf.Max(1, Definition.FrameCount);
_shockLimit[i] = t.RequireLoops + _shockFrame[i] + (i % _cascades) * Definition.BottomRadius;
}
return; // Original shock tasks only trigger the animated plane stack.
}
Vector3 launchPosition = Position;
base.Apply(t, clock, dt);
_lum = Mathf.Clamp(_lum + t.SpeedAlpha * dt, 0, 255);
if (!_launched[task] && LocalTime - clock.StartedAt >= t.SpeedRed)
{
_launched[task] = true;
for (int i = 0; i < _trails.Length; i++)
{
_trails[i].Clear();
_positions[i] = launchPosition;
float a = i * 2 * Mathf.PI / _trails.Length;
_velocities[i] = new Vector3(Definition.BottomRiseSpeed,
_trails.Length == 1 ? Definition.TopShrink : Mathf.Sin(a) * Definition.TopShrink,
_trails.Length == 1 ? Definition.BottomShrink : Mathf.Cos(a) * Definition.BottomShrink);
}
}
}
public override void Step(float time, float dt)
{
base.Step(time, dt);
if (_kind == "shock")
{
for (int i = 0; i < _shockFrame.Length; i++)
_shockFrame[i] += Definition.FramePerSecond * dt;
return;
}
bool running = false;
for (int i = 0; i < _launched.Length; i++)
running |= _launched[i] && !Clocks[i].Finished;
if (!running)
return;
_meteorTime += dt;
Vector3 target = _origin + new Vector3(Definition.TopRadiusIncreaseSpeed, Definition.BottomRadiusIncreaseSpeed, Definition.TopRiseSpeed);
while (_meteorTime + 0.000001f >= 0.02f)
{
_meteorTime -= 0.02f;
for (int i = 0; i < _trails.Length; i++)
{
_velocities[i] += (target - _positions[i]) * 0.02f;
_positions[i] += _velocities[i] * 0.02f;
_trails[i].Insert(0, _positions[i]);
int capacity = Mathf.Clamp(Mathf.RoundToInt(Definition.DivisionCount), 2, 4096);
if (_trails[i].Count > capacity)
_trails[i].RemoveAt(_trails[i].Count - 1);
}
}
}
public override void Render(Camera camera)
{
_mesh.Clear();
_trailMesh?.Clear();
if (!Alive || !Visible)
{
_mesh.Upload();
_trailMesh?.Upload();
return;
}
if (_kind == "shock")
{
Quaternion rot = RawRotation(Rotation);
for (int i = 0; i < _shockFrame.Length; i++)
{
if (_shockFrame[i] > Mathf.Max(1, Definition.FrameCount) * _shockLimit[i])
continue;
int node = i / _cascades;
float h = Definition.TopRadius;
float top = h + node * (h - Definition.TextureRepeat), half = Definition.DivisionCount / 2;
Vector3 P(float x, float y) => UnityPosition(Position + rot * (new Vector3(x, y, 0) * Definition.InitSize));
var uv = Atlas(Definition.FramePerSecond == 0 ? 0 : _shockFrame[i] / Definition.FramePerSecond);
_mesh.Quad(P(-half, top), P(half, top), P(half, top - h), P(-half, top - h), uv.min, uv.max, Tint);
}
}
else
{
Vector3 cameraPosition = camera != null ? Root.transform.InverseTransformPoint(camera.transform.position) : new Vector3(0, 0, -10);
for (int chain = 0; chain < _trails.Length; chain++)
{
List<Vector3> nodes = _trails[chain];
for (int i = 0; i + 1 < nodes.Count; i++)
{
float age = i * 0.02f;
float width = Definition.Width - Definition.BottomRadius * age;
float brightness = _lum - Definition.TopRadius * age;
if (width <= 0 || brightness <= 0)
break;
Vector3 a = UnityPosition(nodes[i]), b = UnityPosition(nodes[i + 1]);
Vector3 side = Vector3.Cross(a - b, a - cameraPosition).normalized * (width / 40);
// GameBox renders a strip with a separate width, camera
// cross vector and luminosity at each chain node. Share
// those endpoints to avoid cracks between tapered quads.
Vector3 endSide = i + 2 < nodes.Count
? Vector3.Cross(b - UnityPosition(nodes[i + 2]), b - cameraPosition).normalized
* (Mathf.Max(0, Definition.Width - Definition.BottomRadius * (age + 0.02f)) / 40)
: side;
Color color = Tint;
color.a = Mathf.Clamp01(brightness / 255);
Color endColor = Tint;
endColor.a = Mathf.Clamp01((_lum - Definition.TopRadius * (age + 0.02f)) / 255);
_trailMesh.Quad(a - side, b - endSide, b + endSide, a + side, new Vector2((float)i / nodes.Count, 0),
new Vector2((float)(i + 1) / nodes.Count, 1), color, endColor, endColor, color);
}
if (Definition.RotationAngle > 0 && nodes.Count > 0)
{
Vector3 center = UnityPosition(nodes[0]);
Vector3 right = camera != null ? Root.transform.InverseTransformVector(camera.transform.right) : Vector3.right;
Vector3 up = camera != null ? Root.transform.InverseTransformVector(camera.transform.up) : Vector3.up;
var spin = Quaternion.AngleAxis(-Rotation.z, Vector3.Cross(right, up));
right = spin * right * Scale.x / 20;
up = spin * up * Scale.z / 20;
var uv = Atlas(LocalTime);
_mesh.Quad(center - right - up, center + right - up, center + right + up, center - right + up, uv.min, uv.max, Tint);
}
}
}
_mesh.Upload();
_trailMesh?.Upload();
}
public override void Dispose()
{
_mesh.Dispose();
_trailMesh?.Dispose();
base.Dispose();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5b9bae354ece74ad9a9def2a773f3f6e
@@ -14,11 +14,11 @@ namespace Pal3.Game.Effect
public sealed class PortalEffect : GameEntityScript, IEffect
{
#if PAL3
#if PAL3
private const string PORTAL_BASE_TEXTURE_NAME = "trans.dds";
#elif PAL3A
#elif PAL3A
private const string PORTAL_BASE_TEXTURE_NAME = "trans.tga";
#endif
#endif
private const float PORTAL_DEFAULT_SIZE = 1.3f;
private const float PORTAL_ANIMATION_ROTATION_SPEED = 5f;
@@ -34,6 +34,9 @@ namespace Pal3.Game.Effect
public void Init(GameResourceProvider resourceProvider, uint _)
{
#if PAL3
_rayEffect = resourceProvider.OptionalVfx.AttachPortal(GameEntity);
#else
_baseEffect = GameEntity.AddComponent<RotatingSpriteEffect>();
_baseEffect.Init(resourceProvider,
PORTAL_BASE_TEXTURE_NAME,
@@ -41,6 +44,7 @@ namespace Pal3.Game.Effect
PORTAL_ANIMATION_ROTATION_SPEED);
_rayEffect = resourceProvider.OptionalVfx.Attach(PORTAL_RAY_EFFECT_ID, GameEntity);
#endif
}
private void OnDestroy() => Dispose();
@@ -58,4 +62,4 @@ namespace Pal3.Game.Effect
_rayEffect = null;
}
}
}
}
@@ -32,6 +32,7 @@ namespace Pal3.ResourceViewer
using Engine.Services;
using Engine.Utilities;
using Game.Constants;
using Game.Effect.Original;
using Game.Data;
using Game.Rendering.Toon;
using Game.Rendering.Renderer;
@@ -63,6 +64,7 @@ namespace Pal3.ResourceViewer
[SerializeField] private AudioSource audioSource;
[SerializeField] private FpsCounter fpsCounter;
private OriginalEffectViewer _effectViewer;
private ICpkFileSystem _fileSystem;
private GameResourceProvider _resourceProvider;
private GameSettings _gameSettings;
@@ -74,7 +76,7 @@ namespace Pal3.ResourceViewer
private IList<string> _movFiles;
private IList<string> _mp3Files;
private static readonly Random Random = new ();
private static readonly Random Random = new();
private GameObject _renderingRoot;
private Light _previewKey;
@@ -99,12 +101,20 @@ namespace Pal3.ResourceViewer
_renderingRoot = new GameObject("Model");
_renderingRoot.transform.SetParent(null);
#if PAL3
_effectViewer = GetComponent<OriginalEffectViewer>() ?? gameObject.AddComponent<OriginalEffectViewer>();
_effectViewer.enabled = true;
_effectViewer.Initialize(_resourceProvider.OriginalEffects, _renderingRoot.transform, DestroyExistingRenderingObjects);
DebugLogConsole.AddCommand<int>("Effect.Load", "Play an original PAL3 flexeff group (-1: transport point).", _effectViewer.Load);
DebugLogConsole.AddCommand<float>("Effect.Seek", "Reset and resimulate the original effect to a time.", _effectViewer.Seek);
DebugLogConsole.AddCommand<bool>("Effect.Pause", "Pause or resume the original effect.", _effectViewer.Pause);
#endif
#if UNITY_2022_1_OR_NEWER
#if UNITY_2022_1_OR_NEWER
int monitorRefreshRate = (int)Screen.currentResolution.refreshRateRatio.value;
#else
#else
var monitorRefreshRate = Screen.currentResolution.refreshRate;
#endif
#endif
if (Application.platform is RuntimePlatform.IPhonePlayer or RuntimePlatform.Android)
{
@@ -124,7 +134,7 @@ namespace Pal3.ResourceViewer
}
IDictionary<string, IList<string>> searchResults =
_fileSystem.BatchSearch(new[] {".pol", ".cvd", ".mv3", ".mov", ".mp3"});
_fileSystem.BatchSearch(new[] { ".pol", ".cvd", ".mv3", ".mov", ".mp3" });
_polFiles = searchResults[".pol"];
_cvdFiles = searchResults[".cvd"];
@@ -138,15 +148,15 @@ namespace Pal3.ResourceViewer
randomMovButton.onClick.AddListener(RandMov);
randomMp3Button.onClick.AddListener(RandMp3);
#if UNITY_EDITOR
#if UNITY_EDITOR
extractAllCpkFilesButton.onClick.AddListener(ExtractAllCpkArchives);
#else
#else
extractAllCpkFilesButton.interactable = false;
#endif
#endif
DebugLogConsole.AddCommand<string>("Search", "Search files using keyword.", Search);
DebugLogConsole.AddCommand<string, bool>("Load", "Load a file to the viewer (.pol, .cvd, .mp3 or .mv3).", Load);
#if UNITY_EDITOR
#if UNITY_EDITOR
DebugLogConsole.AddCommand("DecompileAllSceScripts",
"Decompile all .sce scripts into txt format.",
() => DecompileAllSceScripts(dialogueOnly: false));
@@ -159,7 +169,7 @@ namespace Pal3.ResourceViewer
DebugLogConsole.AddCommand("ExportAllGdbFiles",
"Export all .gdb files into the output directory.",
ExportAllGdbFiles);
#endif
#endif
//__Malicious__Dev_Only__();
}
@@ -208,15 +218,25 @@ namespace Pal3.ResourceViewer
{
if (propertyName == nameof(GameSettings.AntiAliasing))
_antiAliasing?.Apply(_gameSettings.AntiAliasing);
if (_previewKey != null) ToonLighting.ConfigureKeyShadows(_previewKey, _gameSettings);
if (_previewKey != null)
ToonLighting.ConfigureKeyShadows(_previewKey, _gameSettings);
}
private void OnDisable()
{
if (_gameSettings != null) _gameSettings.OnGameSettingsChanged -= OnRenderingSettingsChanged;
if (_effectViewer != null)
_effectViewer.enabled = false;
#if PAL3
DebugLogConsole.RemoveCommand("Effect.Load");
DebugLogConsole.RemoveCommand("Effect.Seek");
DebugLogConsole.RemoveCommand("Effect.Pause");
#endif
if (_gameSettings != null)
_gameSettings.OnGameSettingsChanged -= OnRenderingSettingsChanged;
_antiAliasing?.Dispose();
_toonCameraLighting?.Detach();
if (_previewKey != null) _previewKey.enabled = false;
if (_previewKey != null)
_previewKey.enabled = false;
}
private void Update()
@@ -227,27 +247,37 @@ namespace Pal3.ResourceViewer
private void RandPol()
{
while (!LoadPol(_polFiles[Random.Next(0, _polFiles.Count)])) { }
while (!LoadPol(_polFiles[Random.Next(0, _polFiles.Count)]))
{
}
}
private void RandCvd()
{
while (!LoadCvd(_cvdFiles[Random.Next(0, _cvdFiles.Count)])) { }
while (!LoadCvd(_cvdFiles[Random.Next(0, _cvdFiles.Count)]))
{
}
}
private void RandMv3()
{
while (!LoadMv3(_mv3Files[Random.Next(0, _mv3Files.Count)])) { }
while (!LoadMv3(_mv3Files[Random.Next(0, _mv3Files.Count)]))
{
}
}
private void RandMov()
{
while (!LoadMov(_movFiles[Random.Next(0, _movFiles.Count)])) { }
while (!LoadMov(_movFiles[Random.Next(0, _movFiles.Count)]))
{
}
}
private void RandMp3()
{
while (!LoadMp3(_mp3Files[Random.Next(0, _mp3Files.Count)])) { }
while (!LoadMp3(_mp3Files[Random.Next(0, _mp3Files.Count)]))
{
}
}
private void Search(string keyword)
@@ -291,7 +321,7 @@ namespace Pal3.ResourceViewer
ITextureResourceProvider textureProvider = _resourceProvider.CreateTextureResourceProvider(
CoreUtility.GetDirectoryName(filePath, CpkConstants.DirectorySeparatorChar));
GameObject mesh = new (CoreUtility.GetFileName(filePath, CpkConstants.DirectorySeparatorChar));
GameObject mesh = new(CoreUtility.GetFileName(filePath, CpkConstants.DirectorySeparatorChar));
PolyModelRenderer meshRenderer = mesh.AddComponent<PolyModelRenderer>();
mesh.transform.SetParent(_renderingRoot.transform);
meshRenderer.Render(polyFile,
@@ -327,7 +357,7 @@ namespace Pal3.ResourceViewer
ITextureResourceProvider textureProvider = _resourceProvider.CreateTextureResourceProvider(
CoreUtility.GetDirectoryName(filePath, CpkConstants.DirectorySeparatorChar));
GameObject animationNode = new (CoreUtility.GetFileName(filePath, CpkConstants.DirectorySeparatorChar));
GameObject animationNode = new(CoreUtility.GetFileName(filePath, CpkConstants.DirectorySeparatorChar));
CvdModelRenderer meshRenderer = animationNode.AddComponent<CvdModelRenderer>();
animationNode.transform.SetParent(_renderingRoot.transform);
@@ -443,7 +473,7 @@ namespace Pal3.ResourceViewer
ITextureResourceProvider textureProvider = _resourceProvider.CreateTextureResourceProvider(
CoreUtility.GetDirectoryName(mtlFilePath, CpkConstants.DirectorySeparatorChar));
GameObject animationNode = new (CoreUtility.GetFileName(filePath, CpkConstants.DirectorySeparatorChar));
GameObject animationNode = new(CoreUtility.GetFileName(filePath, CpkConstants.DirectorySeparatorChar));
animationNode.transform.SetParent(_renderingRoot.transform);
SkeletalModelRenderer skeletalModelRenderer = animationNode.AddComponent<SkeletalModelRenderer>();
@@ -469,7 +499,7 @@ namespace Pal3.ResourceViewer
}
}
#if UNITY_EDITOR
#if UNITY_EDITOR
private void DecompileAllSceScripts(bool dialogueOnly)
{
IEnumerable<string> sceFiles = _fileSystem.Search(".sce")
@@ -478,7 +508,8 @@ namespace Pal3.ResourceViewer
string title = dialogueOnly ? "选择脚本导出目录(仅对话)" : "选择脚本导出目录";
string outputFolderPath = EditorUtility.SaveFolderPanel(title, "", "");
if (string.IsNullOrWhiteSpace(outputFolderPath)) return;
if (string.IsNullOrWhiteSpace(outputFolderPath))
return;
outputFolderPath += $"{Path.DirectorySeparatorChar}{GameConstants.AppName}" + (dialogueOnly ? "_对话脚本" : "");
@@ -487,7 +518,9 @@ namespace Pal3.ResourceViewer
Directory.CreateDirectory(outputFolderPath);
}
foreach (string sceFile in sceFiles) if (!DecompileSce(sceFile, outputFolderPath, dialogueOnly)) break;
foreach (string sceFile in sceFiles)
if (!DecompileSce(sceFile, outputFolderPath, dialogueOnly))
break;
// _charSet = new HashSet<char>();
@@ -532,7 +565,8 @@ namespace Pal3.ResourceViewer
private void ExportAllGdbFiles()
{
string outputFolderPath = EditorUtility.SaveFolderPanel("选择GDB文件解包后的导出目录", "", "");
if (string.IsNullOrWhiteSpace(outputFolderPath)) return;
if (string.IsNullOrWhiteSpace(outputFolderPath))
return;
outputFolderPath += Path.DirectorySeparatorChar + GameConstants.AppName + Path.DirectorySeparatorChar;
@@ -571,7 +605,8 @@ namespace Pal3.ResourceViewer
private void ExtractAllCpkArchives()
{
string outputFolderPath = EditorUtility.SaveFolderPanel("选择CPK解包后的导出目录", "", "");
if (string.IsNullOrWhiteSpace(outputFolderPath)) return;
if (string.IsNullOrWhiteSpace(outputFolderPath))
return;
outputFolderPath += Path.DirectorySeparatorChar + GameConstants.AppName + Path.DirectorySeparatorChar;
@@ -586,6 +621,7 @@ namespace Pal3.ResourceViewer
}
private bool _isMovieCpkMounted = false;
private IEnumerator ExtractAllCpkArchivesInternalAsync(string outputFolderPath)
{
// Movie CPKs are not mounted by default since we don't need them in normal gameplay.
@@ -623,9 +659,10 @@ namespace Pal3.ResourceViewer
consoleTextUI.text = "全部CPK文件已解包完成!";
extractAllCpkFilesButton.interactable = true;
}
#endif
#endif
private readonly Dictionary<string, int> _actorDialogueCountMap = new();
private readonly Dictionary<string, int> _actorDialogueCountMap = new ();
private bool DecompileSce(string filePath, string outputFolderPath, bool dialogueOnly)
{
StringBuilder output = new();
@@ -648,7 +685,7 @@ namespace Pal3.ResourceViewer
output.Append($"----------------------------------------------------------");
output.Append($"\n{scriptBlock.Value.Id} {scriptBlock.Value.Description}\n");
using SafeBinaryReader scriptDataReader = new (scriptBlock.Value.ScriptData);
using SafeBinaryReader scriptDataReader = new(scriptBlock.Value.ScriptData);
int dialogueIndex = 1;
ICommand lastCommand = null;
@@ -670,7 +707,7 @@ namespace Pal3.ResourceViewer
{
string dialogueText = command is DialogueRenderTextCommand textCommand
? textCommand.DialogueText
: ((DialogueRenderTextWithTimeLimitCommand) command).DialogueText;
: ((DialogueRenderTextWithTimeLimitCommand)command).DialogueText;
bool isTimeLimited = command is DialogueRenderTextWithTimeLimitCommand;
@@ -695,8 +732,10 @@ namespace Pal3.ResourceViewer
if (dialogueText.Contains(":"))
{
var actorName = dialogueText.Substring(0, dialogueText.IndexOf(":", StringComparison.Ordinal));
if (_actorDialogueCountMap.ContainsKey(actorName)) _actorDialogueCountMap[actorName]++;
else _actorDialogueCountMap.Add(actorName, 1);
if (_actorDialogueCountMap.ContainsKey(actorName))
_actorDialogueCountMap[actorName]++;
else
_actorDialogueCountMap.Add(actorName, 1);
}
dialogueIndex++;
@@ -725,7 +764,9 @@ namespace Pal3.ResourceViewer
output.AppendLine().AppendLine();
output.Append("-----角色对话统计----\n");
foreach (var actorDialogueCount in from entry
in _actorDialogueCountMap orderby entry.Value descending select entry)
in _actorDialogueCountMap
orderby entry.Value descending
select entry)
{
output.Append($"{actorDialogueCount.Key} - {actorDialogueCount.Value}句\n");
}
@@ -766,6 +807,8 @@ namespace Pal3.ResourceViewer
private void DestroyExistingRenderingObjects()
{
if (_effectViewer != null)
_effectViewer.Stop();
foreach (Transform child in _renderingRoot.transform)
{
child.gameObject.Destroy();
@@ -819,4 +862,4 @@ namespace Pal3.ResourceViewer
return bytes.ToArray();
}
}
}
}
@@ -0,0 +1,123 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Core.Tests
{
using System;
using System.IO;
using System.Linq;
using DataReader;
using DataReader.Cpk;
using DataReader.Cpk.Lzo;
using DataReader.Data;
using DataReader.Par;
using NUnit.Framework;
public sealed class OriginalEffectFormatTests
{
[Test]
public void FlexeffReadsFloatSizeTaskPaddingAndFirstValidDuplicate()
{
byte[] bytes = SyntheticTable();
var file = ((IFileReader<EffectDefinitionFile>)new EffectDefinitionFileReader()).Read(bytes, 936);
Assert.That(file.Groups.Length, Is.EqualTo(560));
Assert.That(file.TryGetType(123, out EffectDefinition d), Is.True);
Assert.That(d.InitSize, Is.EqualTo(1.25f));
EffectTask task = file.Groups[0].Objects.Single().Tasks.Single();
Assert.That(task.SpeedX, Is.EqualTo(12.5f));
Assert.That(task.YStretchSpeed, Is.EqualTo(-2f));
Assert.That(task.Duration, Is.EqualTo(3.5f));
}
[Test]
public void OrdinaryLzoRejectsTrailingBytesButExplicitPrefixReportsConsumedLength()
{
byte[] stream = { 21, 10, 20, 30, 40, 17, 0, 0, 99 };
var output = new byte[4];
Assert.Throws<OverflowException>(() => MiniLzo.Decompress(stream, output));
Assert.That(MiniLzo.DecompressPrefix(stream, output), Is.EqualTo(8));
Assert.That(output, Is.EqualTo(new byte[] { 10, 20, 30, 40 }));
}
[Test]
public void CallbackAndSoundUnionsRetainOriginalFieldOrder()
{
var task = new EffectTask
{
XStretchSpeed = 10,
SpeedX = 1,
SpeedY = 2,
SpeedZ = 3,
CircleRadius = 20,
RotAxisX = 4,
RotAxisY = 5,
RotAxisZ = 6,
CircleAxisX = 30,
CircleAxisY = 7,
CircleAxisZ = 8,
CircleSpeed = 9,
SpeedAlpha = 40,
SpeedRed = 11,
SpeedGreen = 12,
SpeedBlue = 13
};
Assert.That(task.Callbacks().Select(c => c.groupId), Is.EqualTo(new[] { 10, 20, 30, 40 }));
Assert.That(task.Callbacks().Last().position.Z, Is.EqualTo(13));
Assert.That(task.Sounds().Select(s => s.delay), Is.EqualTo(new[] { 1f, 3f, 4f, 6f }));
}
[Test]
public void ParticleCurvePreservesReversingSamplesAndUsesOriginalBracketLookup()
{
var points = Enumerable.Range(0, 101).Select(i => new Primitives.GameBoxVector3(i / 100f, i / 100f * 2, 0)).ToArray();
var curve = new ParticleCurve { Channels = 1, Samples = new[] { points, points, points } };
Assert.That(curve.Evaluate(0.325f), Is.EqualTo(0.65f).Within(0.00001f));
Assert.That(curve.Evaluate(1.1f), Is.Zero);
points[43].X = 0.41f;
Assert.That(curve.Evaluate(0.425f), Is.EqualTo(0.87f).Within(0.00001f));
}
[Test]
public void TruncatedCsfAndUnknownParticleVersionAreRejected()
{
Assert.Throws<EndOfStreamException>(() => ((IFileReader<ParticleShapeFile>)new ParticleShapeFileReader()).Read(new byte[] { 99, 115, 102, 0 }, 936));
byte[] par = { 115, 103, 112, 97, 114, 0, 2, 0, 1, 0 };
Assert.Throws<InvalidDataException>(() => ((IFileReader<ParticleFile>)new ParticleFileReader()).Read(par, 936));
}
private static byte[] SyntheticTable()
{
var bytes = new byte[EffectDefinitionFileReader.Pal3Size];
using var stream = new MemoryStream(bytes);
using var w = new BinaryWriter(stream);
for (int i = 0; i < 2; i++)
{
stream.Position = i * 280;
w.Write(0x71756164u);
stream.Position = i * 280 + 36;
w.Write(123u);
stream.Position = i * 280 + 200;
w.Write(i == 0 ? 1.25f : 7f);
stream.Position = i * 280 + 212;
w.Write((byte)1);
}
stream.Position = 1324 * 280;
w.Write(1);
w.Write(123u);
long task = 1324 * 280 + 68;
stream.Position = task + 4;
w.Write(12.5f);
stream.Position = task + 76;
w.Write(3.5f);
stream.Position = task + 88;
w.Write((byte)1);
w.Write((byte)0);
w.Write((byte)0);
w.Write((byte)0xCC);
w.Write(-2f);
return bytes;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c8efb240fc6a64537ba57e4b865f14de
@@ -0,0 +1,921 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Game.Tests
{
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using Core.DataReader.Cpk;
using Core.FileSystem;
using Effect.Original;
using Core.DataReader.Data;
using Core.Utilities;
using Engine.Core.Implementation;
using Settings;
using System.Reflection;
using UnityEditor;
using NUnit.Framework;
using UnityEngine;
[Category("LocalGameData")]
public sealed class OriginalEffectTests
{
// Script groups plus the scene groups. Numeric IDs are integration
// contracts, not copied original binary fixtures.
public static readonly int[] SceneGroups = { 6,12,14,15,25,83,98,175,224,240,251,252,254,255,256,257,
259,260,261,262,263,264,265,266,270,275,276,277,278,290,295,297,314,331,332,337,339,341,
368,369,376,389,400,450,451,452,453,454,455,456,457,458,465,467,468,515 };
private static OriginalEffectResources Open()
{
string path = Environment.GetEnvironmentVariable("PAL3_TEST_DATA_ROOT") ?? Path.GetFullPath("../Game Data/PAL3");
if (!Directory.Exists(path))
Assert.Ignore("Set PAL3_TEST_DATA_ROOT to the local PAL3 data directory");
var crc = new Crc32Hash();
crc.Init();
var fs = new CpkFileSystem(path, crc, 936);
fs.Mount("basedata/basedata.cpk", 936);
return new OriginalEffectResources(fs);
}
[Test]
public void EverySceneGroupHasACompleteOriginalDependencyClosure()
{
using var resources = Open();
var errors = SceneGroups.SelectMany(id => resources.Diagnose(id).Select(e => $"{id}: {e}")).ToArray();
Assert.That(errors, Is.Empty, string.Join("\n", errors));
}
[Test]
public void EverySceneGroupCreatesSimulatesRendersAndDisposes()
{
using var resources = Open();
var cameraRoot = new GameObject("Effect test camera");
var camera = cameraRoot.AddComponent<Camera>();
camera.enabled = false;
var errors = new List<string>();
try
{
foreach (int id in SceneGroups)
{
var root = new GameObject($"Original effect test {id}");
try
{
var player = root.AddComponent<OriginalEffectPlayer>();
player.AutoAdvance = false;
player.Initialize(resources, id, 123);
Assert.That(player.Error, Is.Null, $"{id} initialization");
int maximum = 0;
for (int tick = 0; tick < 650; tick++)
{
player.Advance(0.02f);
if (tick % 10 == 0)
{
player.Render(camera);
maximum = Math.Max(maximum, player.QuadCount);
}
if (player.Error != null)
break;
}
Assert.That(player.Error, Is.Null, $"{id} simulation");
Assert.That(maximum, Is.GreaterThan(0), $"{id}: no visible geometry or particles");
}
catch (Exception ex)
{
errors.Add($"{id}: {ex}");
}
finally
{
UnityEngine.Object.DestroyImmediate(root);
}
}
}
finally
{
UnityEngine.Object.DestroyImmediate(cameraRoot);
}
Assert.That(errors, Is.Empty, string.Join("\n", errors));
}
[Test]
public void SeekReproducesGeometryAndDoesNotReplayAudio()
{
using var resources = Open();
var root = new GameObject("Effect deterministic test");
var cameraRoot = new GameObject("Camera");
var camera = cameraRoot.AddComponent<Camera>();
camera.enabled = false;
try
{
int audio = 0;
var player = root.AddComponent<OriginalEffectPlayer>();
player.AutoAdvance = false;
player.Initialize(resources, 254, 123, sound: _ => audio++);
for (int i = 0; i < 150; i++)
player.Advance(0.02f);
player.Render(camera);
int sounds = audio;
Assert.That(sounds, Is.GreaterThan(0), "Original audio tasks must execute during forward playback");
Vector3[] expected = Vertices(root);
player.Seek(1);
player.Seek(3);
player.Render(camera);
Assert.That(audio, Is.EqualTo(sounds));
Assert.That(Vertices(root), Is.EqualTo(expected));
}
finally
{
UnityEngine.Object.DestroyImmediate(root);
UnityEngine.Object.DestroyImmediate(cameraRoot);
}
}
[Test]
public void ParticleCurveOverridesDoNotMutateCachedOriginalData()
{
using var resources = Open();
var edits = ScriptableObject.CreateInstance<OriginalEffectOverrides>();
try
{
const string path = "effect\\gbParticle\\yiwai3.par";
Assert.That(OriginalEffectResources.RelativeTo("effect/gbParticle/yiwai3.par", "partexture/guangdianer.jpg"),
Is.EqualTo("effect\\gbParticle\\partexture\\guangdianer.jpg"));
float original = resources.Particle(path).Particles[0].Size.Evaluate(0.5f);
edits.ParticleCurves.Add(new OriginalParticleCurveOverride
{
File = path,
Parameter = "Size",
Index = 0,
Channels = new[] { AnimationCurve.Constant(0, 1, 17) }
});
Assert.That(resources.Particle(path, edits).Particles[0].Size.Evaluate(0.5f), Is.EqualTo(17));
Assert.That(resources.Particle(path).Particles[0].Size.Evaluate(0.5f), Is.EqualTo(original));
}
finally
{
UnityEngine.Object.DestroyImmediate(edits);
}
}
[Test]
public void NativeParticleRendererRetainsManuallySimulatedParticles()
{
using var resources = Open();
var root = new GameObject("Native particle handoff");
var cameraRoot = new GameObject("Camera");
var camera = cameraRoot.AddComponent<Camera>();
camera.enabled = false;
try
{
var player = root.AddComponent<OriginalEffectPlayer>();
player.AutoAdvance = false;
player.Initialize(resources, 175, 123);
for (int i = 0; i < 100; i++)
player.Advance(0.02f);
player.Render(camera);
Assert.That(root.GetComponentsInChildren<ParticleSystem>().Sum(ps => ps.particleCount), Is.GreaterThan(0));
Vector3[] positions = ParticlePositions(root);
player.Seek(1);
player.Seek(2);
player.Render(camera);
Assert.That(ParticlePositions(root), Is.EqualTo(positions), "Fixed-seed particle replay must match forward simulation");
}
finally
{
UnityEngine.Object.DestroyImmediate(root);
UnityEngine.Object.DestroyImmediate(cameraRoot);
}
}
[Test]
public void PersistentGroup275KeepsEmittingPastItsOriginalRepeatInterval()
{
using var resources = Open();
var root = new GameObject("Persistent effect test");
try
{
var player = root.AddComponent<OriginalEffectPlayer>();
player.AutoAdvance = false;
player.Initialize(resources, 275);
player.Loop = true;
player.RepeatInterval = 9.5f;
for (int i = 0; i < 1500; i++)
player.Advance(0.02f);
Assert.That(player.Error, Is.Null);
Assert.That(player.IsAlive, Is.True);
Assert.That(player.Time, Is.EqualTo(30).Within(0.001f));
Assert.That(player.NodeCount, Is.LessThan(150));
}
finally
{
UnityEngine.Object.DestroyImmediate(root);
}
}
[Test]
public void TransportSceneEffectIsIndependentOfFlexeffGroupZero()
{
using var resources = Open();
var root = new GameObject("Transport test");
try
{
var portal = root.AddComponent<OriginalPortalEffect>();
portal.AutoAdvance = false;
portal.Initialize(resources);
portal.Sample(2);
Assert.That(root.GetComponentsInChildren<MeshFilter>().Sum(m => m.sharedMesh.vertexCount), Is.EqualTo(13 * 4));
portal.Sample(1);
Vector3 vertex = root.GetComponentsInChildren<MeshFilter>().Single(m => m.name == "Transport outer cone").sharedMesh.vertices[0];
Assert.That(vertex.x, Is.EqualTo(-1.4f * Mathf.Cos(6.4f * Mathf.Deg2Rad)).Within(0.00001f));
Assert.That(vertex.z, Is.EqualTo(1.4f * Mathf.Sin(6.4f * Mathf.Deg2Rad)).Within(0.00001f));
}
finally
{
UnityEngine.Object.DestroyImmediate(root);
}
}
[Test]
public void ZeroOrbitAxisPreservesRadiusAndInvalidTasksStayDisabled()
{
using var resources = Open();
var edits = ScriptableObject.CreateInstance<OriginalEffectOverrides>();
var root = new GameObject("Orbit semantics");
var cameraRoot = new GameObject("Camera");
try
{
var edit = OverrideObject(resources, 15, 0);
edits.Objects.Add(edit);
for (int i = 1; i < resources.Definitions.Groups[15].Objects.Length; i++)
edits.Objects.Add(new OriginalEffectObjectOverride { GroupId = 15, ObjectIndex = i, Hidden = true });
edit.Definition.InitXPosition = edit.Definition.InitYPosition = edit.Definition.InitZPosition = 0;
edit.Definition.FramePerSecond = 0;
edit.Tasks = new[] { new EffectTask { IsValid = true, StartTime = -1, Duration = 10, CircleRadius = 20 } };
var camera = cameraRoot.AddComponent<Camera>();
camera.enabled = false;
var player = root.AddComponent<OriginalEffectPlayer>();
player.AutoAdvance = false;
player.Initialize(resources, 15, overrides: edits);
player.Advance(0.04f);
player.Render(camera);
Assert.That(player.QuadCount, Is.GreaterThan(0), "A negative wait starts after init in the same update");
player.Seek(0.2f);
player.Render(camera);
Assert.That(Vertices(root).Average(v => v.z), Is.EqualTo(1).Within(0.00001f), "Identity orbit rotation retains the radius vector");
edit.Tasks[0].IsValid = false;
player.Seek(0.2f);
player.Render(camera);
Assert.That(player.NodeCount, Is.Zero);
Assert.That(player.QuadCount, Is.Zero);
}
finally
{
UnityEngine.Object.DestroyImmediate(root);
UnityEngine.Object.DestroyImmediate(cameraRoot);
UnityEngine.Object.DestroyImmediate(edits);
}
}
[Test]
public void DiagnosisIncludesCallbackOverridesAndDoesNotPoisonOriginalCache()
{
using var resources = Open();
var edits = ScriptableObject.CreateInstance<OriginalEffectOverrides>();
try
{
Assert.That(resources.Diagnose(275), Is.Empty);
var edit = OverrideObject(resources, 273, 0);
edits.Objects.Add(edit);
edit.Definition.TextureName = "effect\\missing-review-texture.tga";
Assert.That(resources.Diagnose(275, edits).Any(e => e.Contains("missing-review-texture")), Is.True);
Assert.That(resources.Diagnose(275), Is.Empty);
edit.Hidden = true;
Assert.That(resources.Diagnose(275, edits), Is.Empty);
}
finally
{
UnityEngine.Object.DestroyImmediate(edits);
}
}
[Test]
public void NonFiniteOverrideParametersAreRejectedBeforeSimulation()
{
using var resources = Open();
var edits = ScriptableObject.CreateInstance<OriginalEffectOverrides>();
try
{
var edit = OverrideObject(resources, 15, 0);
edits.Objects.Add(edit);
edit.Tasks[0].SpeedX = float.NaN;
Assert.That(resources.Diagnose(15, edits).Any(e => e.Contains("finite")), Is.True);
}
finally
{
UnityEngine.Object.DestroyImmediate(edits);
}
}
[Test]
public void TaperedMeteorStripSharesEndpointsAndInterpolatesLuminosity()
{
using var resources = Open();
var edits = ScriptableObject.CreateInstance<OriginalEffectOverrides>();
var root = new GameObject("Meteor strip continuity");
var cameraRoot = new GameObject("Camera");
try
{
var edit = OverrideObject(resources, 240, 0);
edits.Objects.Add(edit);
for (int i = 1; i < resources.Definitions.Groups[240].Objects.Length; i++)
edits.Objects.Add(new OriginalEffectObjectOverride { GroupId = 240, ObjectIndex = i, Hidden = true });
Assert.That(EffectClass.Name(edit.Definition.ClassNameCrc), Is.EqualTo("meteor"));
edit.Definition.RotationAngle = -1;
edit.Definition.Width = 20;
edit.Definition.DivisionCount = 16;
edit.Definition.BottomRadius = 10;
edit.Definition.TopRadius = 100;
edit.Definition.TextureRepeat = 255;
edit.Definition.BottomRiseSpeed = 100;
edit.Definition.TopShrink = edit.Definition.BottomShrink = 0;
edit.Tasks = new[] { new EffectTask { IsValid = true, Duration = 2 } };
var camera = cameraRoot.AddComponent<Camera>();
camera.enabled = false;
camera.transform.position = new Vector3(0, 5, -10);
edit.Definition.InitXPosition = edit.Definition.InitYPosition = edit.Definition.InitZPosition = 0;
edit.Definition.TopRadiusIncreaseSpeed = edit.Definition.BottomRadiusIncreaseSpeed = edit.Definition.TopRiseSpeed = 0;
edit.Definition.RotationAngle = 1;
edit.Tasks[0].SpeedX = 20;
var player = root.AddComponent<OriginalEffectPlayer>();
player.AutoAdvance = false;
player.Initialize(resources, 240, overrides: edits);
player.Advance(0.04f);
player.Render(camera);
Mesh head = root.GetComponentInChildren<MeshFilter>().sharedMesh;
Assert.That(head.vertices.Average(v => v.x), Is.EqualTo(-0.1f).Within(0.00001f), "StartMeteor captures position before the task moves the emitter");
edit.Definition.RotationAngle = -1;
edit.Tasks[0].SpeedX = 0;
player.Seek(0.5f);
player.Render(camera);
Mesh mesh = root.GetComponentsInChildren<MeshFilter>().Single(m => m.name == "Original meteor chain").sharedMesh;
Vector3[] vertices = mesh.vertices;
Color32[] colors = mesh.colors32;
Assert.That(vertices.Length, Is.GreaterThanOrEqualTo(8));
for (int i = 0; i + 7 < vertices.Length; i += 4)
{
Assert.That(Vector3.Distance(vertices[i + 1], vertices[i + 4]), Is.LessThan(0.00001f));
Assert.That(Vector3.Distance(vertices[i + 2], vertices[i + 7]), Is.LessThan(0.00001f));
}
Assert.That(colors[0].a, Is.GreaterThan(colors[1].a));
}
finally
{
UnityEngine.Object.DestroyImmediate(root);
UnityEngine.Object.DestroyImmediate(cameraRoot);
UnityEngine.Object.DestroyImmediate(edits);
}
}
[Test]
public void ParticleEmitterRunsItsInitialCycleBeforeTheDelayedTaskEnablesLooping()
{
using var resources = Open();
var edits = ScriptableObject.CreateInstance<OriginalEffectOverrides>();
var root = new GameObject("Initial particle cycle");
var cameraRoot = new GameObject("Camera");
try
{
var edit = OverrideObject(resources, 175, 0);
edits.Objects.Add(edit);
for (int i = 1; i < resources.Definitions.Groups[175].Objects.Length; i++)
edits.Objects.Add(new OriginalEffectObjectOverride { GroupId = 175, ObjectIndex = i, Hidden = true });
var par = resources.Particle(edit.Definition.ParticleFileName);
float cycle = par.Emitters.Max(e => e.CycleMin - e.CycleMax);
edit.Tasks = new[] { new EffectTask { IsValid = true, StartTime = cycle + 1, Duration = 0.2f } };
for (int i = 0; i < par.Emitters.Length; i++)
edits.ParticleCurves.Add(new OriginalParticleCurveOverride
{
File = edit.Definition.ParticleFileName,
Emitter = true,
Index = i,
Parameter = "Life",
Channels = Enumerable.Range(0, par.Emitters[i].Life.Channels)
.Select(_ => AnimationCurve.Constant(0, 1, 0.1f)).ToArray()
});
var camera = cameraRoot.AddComponent<Camera>();
camera.enabled = false;
var player = root.AddComponent<OriginalEffectPlayer>();
player.AutoAdvance = false;
player.Initialize(resources, 175, overrides: edits);
player.Seek(0.1f);
player.Render(camera);
Assert.That(player.QuadCount, Is.GreaterThan(0), "The first emitter cycle does not wait for the task start time");
player.Seek(cycle + 0.5f);
player.Render(camera);
Assert.That(player.QuadCount, Is.Zero, "The nonlooping initial cycle must stop and drain before the delayed task");
}
finally
{
UnityEngine.Object.DestroyImmediate(root);
UnityEngine.Object.DestroyImmediate(cameraRoot);
UnityEngine.Object.DestroyImmediate(edits);
}
}
[Test]
public void CombatParticleTaskMotionMovesTheWholeCloudInWorldSpaceParFiles()
{
using var resources = Open();
var edits = ScriptableObject.CreateInstance<OriginalEffectOverrides>();
var root = new GameObject("Combat particle task motion");
var cameraRoot = new GameObject("Camera");
try
{
var edit = OverrideObject(resources, 175, 0);
edits.Objects.Add(edit);
for (int i = 1; i < resources.Definitions.Groups[175].Objects.Length; i++)
edits.Objects.Add(new OriginalEffectObjectOverride { GroupId = 175, ObjectIndex = i, Hidden = true });
Assert.That(resources.Particle(edit.Definition.ParticleFileName).Space, Is.Zero);
edit.Tasks = new[] { new EffectTask { IsValid = true, Duration = 2 } };
var camera = cameraRoot.AddComponent<Camera>();
camera.enabled = false;
var player = root.AddComponent<OriginalEffectPlayer>();
player.AutoAdvance = false;
player.Initialize(resources, 175, 123, edits);
player.Seek(0.5f);
player.Render(camera);
Vector3[] stationary = ParticlePositions(root);
edit.Tasks[0].SpeedX = 20;
player.Seek(0.5f);
player.Render(camera);
Vector3[] moving = ParticlePositions(root);
Assert.That(moving.Length, Is.GreaterThan(1));
Assert.That(moving.Length, Is.EqualTo(stationary.Length));
Vector3 translation = moving[0] - stationary[0];
Assert.That(translation.x, Is.LessThan(-0.4f));
for (int i = 1; i < moving.Length; i++)
Assert.That(Vector3.Distance(moving[i] - stationary[i], translation), Is.LessThan(0.00001f), "The combat wrapper translates existing particles uniformly");
}
finally
{
UnityEngine.Object.DestroyImmediate(root);
UnityEngine.Object.DestroyImmediate(cameraRoot);
UnityEngine.Object.DestroyImmediate(edits);
}
}
[Test]
public void FailedTextureAndModelInitializationReleaseMaterials()
{
using var resources = Open();
var edits = ScriptableObject.CreateInstance<OriginalEffectOverrides>();
var root = new GameObject("Failed resource cleanup");
try
{
int before = Resources.FindObjectsOfTypeAll<Material>().Length;
for (int i = 0; i < 3; i++)
Assert.Throws<FileNotFoundException>(() => resources.Material("effect\\missing-review-texture.tga", true, false));
Assert.That(Resources.FindObjectsOfTypeAll<Material>().Length, Is.EqualTo(before));
var edit = OverrideObject(resources, 173, 0);
edits.Objects.Add(edit);
Assert.That(EffectClass.Name(edit.Definition.ClassNameCrc), Is.EqualTo("model"));
edit.Definition.TextureName = "effect\\missing-review-model.cvd";
var player = root.AddComponent<OriginalEffectPlayer>();
player.AutoAdvance = false;
for (int i = 0; i < 3; i++)
{
player.Initialize(resources, 173, overrides: edits);
Assert.That(player.Error, Is.Not.Null);
}
Assert.That(Resources.FindObjectsOfTypeAll<Material>().Length, Is.EqualTo(before));
}
finally
{
UnityEngine.Object.DestroyImmediate(root);
UnityEngine.Object.DestroyImmediate(edits);
}
}
[Test]
public void EditorReloadKeepsWorkingCopyAndInvalidDataPathLeavesNoBrokenProvider()
{
using var resources = Open();
Type type = TypeCache.GetTypesDerivedFrom<EditorWindow>().FirstOrDefault(t => t.FullName == "Editor.OriginalEffectEditor");
Assert.That(type, Is.Not.Null);
var window = (EditorWindow)ScriptableObject.CreateInstance(type);
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
void Call(string name) => type.GetMethod(name, flags).Invoke(window, null);
try
{
var working = (OriginalEffectOverrides)type.GetField("_edits", flags).GetValue(window);
working.Objects.Add(OverrideObject(resources, 15, 0));
Call("MarkChanged");
Assert.That(window.hasUnsavedChanges, Is.True);
Call("OnDisable");
Call("OnEnable");
Assert.That(type.GetField("_edits", flags).GetValue(window), Is.SameAs(working));
Assert.That(window.hasUnsavedChanges, Is.True);
type.GetField("_dataPath", flags).SetValue(window, Path.GetFullPath("Assets"));
Call("LoadData");
Assert.That(type.GetField("_resources", flags).GetValue(window), Is.Null);
Assert.That((string)type.GetField("_error", flags).GetValue(window), Is.Not.Empty);
}
finally
{
window.DiscardChanges();
UnityEngine.Object.DestroyImmediate(window);
}
}
[TestCase(60)]
[TestCase(120)]
[TestCase(144)]
public void RuntimeFrameClockMovesOnEveryFrameWhileFixedSeekingStaysRepeatable(int fps)
{
using var resources = Open();
var edits = ScriptableObject.CreateInstance<OriginalEffectOverrides>();
var root = new GameObject("Frame clock");
var cameraRoot = new GameObject("Camera");
try
{
var edit = SoloObject(resources, edits, 15);
edit.Definition.FramePerSecond = 0;
edit.Tasks = new[] { new EffectTask { IsValid = true, Duration = 5, SpeedX = 20 } };
var camera = cameraRoot.AddComponent<Camera>();
camera.enabled = false;
var player = root.AddComponent<OriginalEffectPlayer>();
player.AutoAdvance = false;
player.Initialize(resources, 15, 123, edits);
float dt = 1f / fps;
for (int i = 0; i < 4; i++)
player.AdvanceFrame(dt);
player.Render(camera);
Vector3 previous = Vertices(root)[0];
for (int i = 0; i < fps / 2; i++)
{
player.AdvanceFrame(dt);
player.Render(camera);
Vector3 next = Vertices(root)[0];
Assert.That(next.x - previous.x, Is.EqualTo(-dt).Within(0.00001f), "Rendering must not repeat a 50 Hz position on faster displays");
previous = next;
}
float pausedAt = player.Time;
player.Paused = true;
player.AdvanceFrame(dt);
Assert.That(player.Time, Is.EqualTo(pausedAt));
player.Seek(0.5f);
player.Render(camera);
Vector3[] expected = Vertices(root);
player.Seek(0.2f);
player.Seek(0.5f);
player.Render(camera);
Assert.That(Vertices(root), Is.EqualTo(expected));
}
finally
{
UnityEngine.Object.DestroyImmediate(root);
UnityEngine.Object.DestroyImmediate(cameraRoot);
UnityEngine.Object.DestroyImmediate(edits);
}
}
[TestCase(30)]
[TestCase(50)]
[TestCase(60)]
[TestCase(120)]
[TestCase(144)]
[TestCase(240)]
public void ModelRotationAndStretchUse60FpsReferenceAcrossFrameRatesAndSeeking(int fps)
{
using var resources = Open();
var edits = ScriptableObject.CreateInstance<OriginalEffectOverrides>();
var root = new GameObject("Model frame rate");
try
{
var edit = SoloObject(resources, edits, 173);
Assert.That(EffectClass.Name(edit.Definition.ClassNameCrc), Is.EqualTo("model"));
edit.Definition.InitSize = 1;
edit.Definition.InitXPosition = edit.Definition.InitYPosition = edit.Definition.InitZPosition = 0;
edit.Definition.InitXRotation = 5;
edit.Definition.InitYRotation = -10;
edit.Definition.InitZRotation = 15;
edit.Tasks = new[] { new EffectTask { IsValid = true, StartTime = -1, Duration = 5,
SpeedX = 20, SpeedY = 10, SpeedZ = 5, RotAxisX = 0.2f, RotAxisY = 0.4f, RotAxisZ = -0.1f,
XStretchSpeed = 0.01f, YStretchSpeed = 0.02f, CreateTimeSlot = -0.005f } };
var player = root.AddComponent<OriginalEffectPlayer>();
player.AutoAdvance = false;
player.Initialize(resources, 173, 123, edits);
Assert.That(player.Error, Is.Null);
void Check(float seconds)
{
player.Render(null);
Transform model = root.transform.GetChild(0);
// Assert the chosen compatibility rate independently of
// both the model implementation and the seek step size.
float referenceFrames = seconds * 60f;
Vector3 rotation = new Vector3(5, -10, 15) + new Vector3(0.2f, 0.4f, -0.1f) * referenceFrames;
Quaternion expected = Quaternion.AngleAxis(rotation.x, Vector3.right) *
Quaternion.AngleAxis(-rotation.y, Vector3.up) * Quaternion.AngleAxis(-rotation.z, Vector3.forward);
Assert.That(Quaternion.Angle(model.localRotation, expected), Is.LessThan(0.06f), $"Rotation at {seconds}s");
Assert.That(Vector3.Distance(model.localScale, Vector3.one + new Vector3(0.01f, 0.02f, -0.005f) * referenceFrames),
Is.LessThan(0.00005f), $"Stretch at {seconds}s");
Assert.That(Vector3.Distance(model.localPosition, new Vector3(-1, 0.5f, 0.25f) * seconds), Is.LessThan(0.00001f));
}
for (int i = 0; i < fps; i++)
{
player.AdvanceFrame(1f / fps);
Check(player.Time);
}
Check(1);
player.Seek(0.02f);
Check(0.02f); // One seek step applies 1.2 reference frames.
player.Seek(0.4f);
player.Seek(1);
Check(1);
player.Seek(0);
player.Speed = 2;
for (int i = 0; i < fps / 2; i++)
player.AdvanceFrame(1f / fps);
Check(1);
}
finally
{
UnityEngine.Object.DestroyImmediate(root);
UnityEngine.Object.DestroyImmediate(edits);
}
}
[Test]
public void UnsupportedModelOpacityTasksAreDiagnosedInsteadOfSilentlyIgnored()
{
using var resources = Open();
var edits = ScriptableObject.CreateInstance<OriginalEffectOverrides>();
var root = new GameObject("Model opacity diagnosis");
try
{
var edit = SoloObject(resources, edits, 173);
edit.Tasks = new[] { new EffectTask { IsValid = true, StartTime = -1, Duration = 2, SpeedAlpha = -0.5f } };
Assert.That(resources.Diagnose(173, edits).Any(error => error.Contains("model opacity")), Is.True);
Assert.That(resources.Diagnose(173), Is.Empty, "Override errors must not affect the original group");
var player = root.AddComponent<OriginalEffectPlayer>();
player.AutoAdvance = false;
player.Initialize(resources, 173, overrides: edits);
Assert.That(player.Error, Does.Contain("model opacity"));
Assert.That(player.NodeCount, Is.Zero);
edit.Tasks[0].IsValid = false;
Assert.That(resources.Diagnose(173, edits), Is.Empty, "Disabled tasks must not block a group");
edit.Tasks[0].IsValid = true;
edit.Tasks[0].SpeedAlpha = 0;
Assert.That(resources.Diagnose(173, edits), Is.Empty);
}
finally
{
UnityEngine.Object.DestroyImmediate(root);
UnityEngine.Object.DestroyImmediate(edits);
}
}
[Test]
public void CombatParticleScalingAndBlendFollowPal3ParticleEffectRatherThanEngineGbParticleEffect()
{
using var resources = Open();
var edits = ScriptableObject.CreateInstance<OriginalEffectOverrides>();
var root = new GameObject("Legacy combat particle semantics");
var cameraRoot = new GameObject("Camera");
try
{
var edit = SoloObject(resources, edits, 175);
edit.Definition.InitXPosition = edit.Definition.InitYPosition = edit.Definition.InitZPosition = 0;
edit.Tasks = new[] { new EffectTask { IsValid = true, Duration = 2 } };
var par = resources.Particle(edit.Definition.ParticleFileName);
foreach (var e in par.Emitters)
{
e.Shape = 0;
e.Position = e.Scope = e.BoxMin = e.BoxMax = default;
e.CycleMin = 10;
e.CycleMax = 0;
e.SpeedMultiplier = 1;
e.Direction.OverrideEvaluation = (_, channel) => channel == 0 ? 1 : 0;
e.RandomVelocity.OverrideEvaluation = (_, _) => 10;
e.Emission.OverrideEvaluation = (_, _) => 100;
e.Life.OverrideEvaluation = (_, _) => 10;
}
foreach (var p in par.Particles)
{
p.Gravity = p.Resistance = 0;
p.BlendMode = 1;
}
var camera = cameraRoot.AddComponent<Camera>();
camera.enabled = false;
var player = root.AddComponent<OriginalEffectPlayer>();
player.AutoAdvance = false;
edit.Definition.InitSize = 20;
player.Initialize(resources, 175, 123, edits);
player.Advance(0.02f);
player.Render(camera);
// pal3/effect/particle.cpp: offset = velocity * dt; offset *=
// particleMultiSize. PAL3's wrapper fixes blend to ONE / ONE.
Assert.That(ParticlePositions(root)[0].x, Is.EqualTo(-10f * 0.02f * 20 / 20).Within(0.00001f));
Material material = root.GetComponentInChildren<ParticleSystemRenderer>().sharedMaterial;
Assert.That(material.GetInt("_SrcBlend"), Is.EqualTo((int)UnityEngine.Rendering.BlendMode.One));
Assert.That(material.GetInt("_DstBlend"), Is.EqualTo((int)UnityEngine.Rendering.BlendMode.One));
foreach (var e in par.Emitters)
{
e.Direction.OverrideEvaluation = (_, _) => 0;
e.RandomVelocity.OverrideEvaluation = (_, _) => 0;
e.Scope = new(1, 0, 0);
}
edit.Definition.InitSize = 1;
player.Initialize(resources, 175, 123, edits);
player.Advance(0.02f);
player.Render(camera);
Vector3[] small = ParticlePositions(root);
edit.Definition.InitSize = 20;
player.Initialize(resources, 175, 123, edits);
player.Advance(0.02f);
player.Render(camera);
Vector3[] large = ParticlePositions(root);
Assert.That(large.Length, Is.GreaterThan(0));
Assert.That(large.Length, Is.EqualTo(small.Length));
for (int i = 0; i < small.Length; i++)
Assert.That(Vector3.Distance(large[i], small[i] * 400), Is.LessThan(0.00001f), "PAL3 scales emitter scope and then particle displacement");
}
finally
{
UnityEngine.Object.DestroyImmediate(root);
UnityEngine.Object.DestroyImmediate(cameraRoot);
UnityEngine.Object.DestroyImmediate(edits);
}
}
[Test]
public void UnchangedOverridesReuseParticleAndDiagnosticCachesAndEditsInvalidateBoth()
{
using var resources = Open();
var edits = ScriptableObject.CreateInstance<OriginalEffectOverrides>();
try
{
const string path = "effect\\gbParticle\\yiwai3.par";
var curve = new OriginalParticleCurveOverride
{
File = path,
Parameter = "Size",
Index = 0,
Channels = new[] { AnimationCurve.Constant(0, 1, 17) }
};
edits.ParticleCurves.Add(curve);
var first = resources.Particle(path, edits);
Assert.That(resources.Particle(path, edits), Is.SameAs(first));
curve.Channels[0] = AnimationCurve.Constant(0, 1, 19);
var second = resources.Particle(path, edits);
Assert.That(second, Is.Not.SameAs(first));
Assert.That(second.Particles[0].Size.Evaluate(0.5f), Is.EqualTo(19));
var edit = OverrideObject(resources, 273, 0);
edits.Objects.Add(edit);
edit.Definition.TextureName = "effect\\missing-first.tga";
string[] diagnosis = resources.Diagnose(275, edits);
Assert.That(diagnosis, Is.Not.Empty);
Assert.That(resources.Diagnose(275, edits), Is.SameAs(diagnosis));
edit.Definition.TextureName = "effect\\missing-second.tga";
Assert.That(resources.Diagnose(275, edits).Any(e => e.Contains("missing-second")), Is.True);
}
finally
{
UnityEngine.Object.DestroyImmediate(edits);
}
}
[Test]
public void SceneCacheTrimPreservesLiveParticleAssetsAndEvictsUnusedAssets()
{
using var resources = Open();
var root = new GameObject("Live render assets");
try
{
var player = root.AddComponent<OriginalEffectPlayer>();
player.AutoAdvance = false;
player.Initialize(resources, 175);
Material live = root.GetComponentInChildren<ParticleSystemRenderer>().sharedMaterial;
Texture liveTexture = live.mainTexture;
Material unused = resources.Material("effect\\q08qiao.tga", true, false);
Texture unusedTexture = unused.mainTexture;
resources.TrimUnusedRenderAssets(new[] { root });
Assert.That(live != null && liveTexture != null, Is.True);
Assert.That(unused == null && unusedTexture == null, Is.True);
UnityEngine.Object.DestroyImmediate(root);
resources.TrimUnusedRenderAssets(Array.Empty<GameObject>());
Assert.That(live == null && liveTexture == null, Is.True);
}
finally
{
if (root != null)
UnityEngine.Object.DestroyImmediate(root);
}
}
[Test]
public void PrivateFallbackUsesActorParentWhileOriginalUsesSceneSnapshot()
{
string path = Environment.GetEnvironmentVariable("PAL3_TEST_DATA_ROOT") ?? Path.GetFullPath("../Game Data/PAL3");
if (!Directory.Exists(path))
Assert.Ignore("PAL3 data is unavailable");
var crc = new Crc32Hash();
crc.Init();
var fs = new CpkFileSystem(path, crc, 936);
fs.Mount("basedata/basedata.cpk", 936);
int sleepTimeout = Screen.sleepTimeout;
using var settings = new GameSettings(new InMemoryKeyValueStore());
settings.OptionalVfxEnabled = true;
Type type = typeof(OriginalEffectPlayer).Assembly.GetType("Pal3.Game.Effect.OptionalVfxPlayer");
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
var facade = (IDisposable)Activator.CreateInstance(type, flags, null, new object[] { settings, fs, 936 }, null);
var scene = new GameObject("Effect scene");
var actor = new GameObject("Effect actor");
var prefab = new GameObject("Synthetic private prefab");
try
{
var prefabs = (Dictionary<int, GameObject>)type.GetField("_prefabs", flags).GetValue(facade);
prefabs[-2] = prefab;
var sceneEntity = new GameEntity(scene);
var actorEntity = new GameEntity(actor);
bool original = (bool)type.GetMethod("Play", flags).Invoke(facade, new object[] { -2, sceneEntity, new Vector3(10, 0, 0), ((Engine.Core.Abstraction.IGameEntity)actorEntity, Vector3.zero) });
Assert.That(original, Is.False);
Transform fallback = actor.transform.GetChild(0);
actor.transform.position = new Vector3(7, 0, 0);
Assert.That(fallback.position.x, Is.EqualTo(7));
original = (bool)type.GetMethod("Play", flags).Invoke(facade, new object[] { 15, sceneEntity, new Vector3(10, 0, 0), ((Engine.Core.Abstraction.IGameEntity)actorEntity, Vector3.zero) });
Assert.That(original, Is.True);
Transform native = scene.transform.GetChild(0);
actor.transform.position = new Vector3(9, 0, 0);
Assert.That(native.position.x, Is.EqualTo(10));
}
finally
{
facade.Dispose();
UnityEngine.Object.DestroyImmediate(prefab);
UnityEngine.Object.DestroyImmediate(actor);
UnityEngine.Object.DestroyImmediate(scene);
Screen.sleepTimeout = sleepTimeout;
}
}
[Test]
public void EditorCoalescesTimelineRequestsBeforeResimulating()
{
Type type = TypeCache.GetTypesDerivedFrom<EditorWindow>().First(t => t.FullName == "Editor.OriginalEffectEditor");
var window = (EditorWindow)ScriptableObject.CreateInstance(type);
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
try
{
var player = (OriginalEffectPlayer)type.GetField("_player", flags).GetValue(window);
Assert.That(player, Is.Not.Null);
type.GetMethod("QueueSeek", flags).Invoke(window, new object[] { 1f });
type.GetMethod("QueueSeek", flags).Invoke(window, new object[] { 2f });
Assert.That(player.Time, Is.Zero, "Input events only queue the latest timeline request");
type.GetField("_seekAfter", flags).SetValue(window, 0d);
type.GetMethod("Tick", flags).Invoke(window, null);
Assert.That(player.Time, Is.EqualTo(2).Within(0.00001f));
}
finally
{
window.DiscardChanges();
UnityEngine.Object.DestroyImmediate(window);
}
}
private static OriginalEffectObjectOverride SoloObject(OriginalEffectResources resources, OriginalEffectOverrides edits, int group)
{
var edit = OverrideObject(resources, group, 0);
edits.Objects.Add(edit);
for (int i = 1; i < resources.Definitions.Groups[group].Objects.Length; i++)
edits.Objects.Add(new OriginalEffectObjectOverride { GroupId = group, ObjectIndex = i, Hidden = true });
return edit;
}
private static OriginalEffectObjectOverride OverrideObject(OriginalEffectResources resources, int group, int index)
{
EffectGroupObject source = resources.Definitions.Groups[group].Objects[index];
resources.Definitions.TryGetType(source.TypeCrc, out EffectDefinition definition);
return new OriginalEffectObjectOverride
{
GroupId = group,
ObjectIndex = index,
Definition = JsonUtility.FromJson<EffectDefinition>(JsonUtility.ToJson(definition)),
Tasks = source.Tasks.Select(t => JsonUtility.FromJson<EffectTask>(JsonUtility.ToJson(t))).ToArray()
};
}
private static Vector3[] Vertices(GameObject root) => root.GetComponentsInChildren<MeshFilter>().SelectMany(m => m.sharedMesh.vertices).ToArray();
private static Vector3[] ParticlePositions(GameObject root) => root.GetComponentsInChildren<ParticleSystem>().SelectMany(ps =>
{
var particles = new ParticleSystem.Particle[ps.particleCount];
ps.GetParticles(particles);
return particles.Select(p => p.position);
}).ToArray();
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 100011eb82a8643f695ea64a052075b4
@@ -1,6 +1,6 @@
{
"name": "Pal3.Game.Tests",
"references": ["Pal3.Core", "Pal3.Game"],
"references": ["Pal3.Core", "Pal3.Game", "Engine"],
"includePlatforms": ["Editor"],
"optionalUnityReferences": ["TestAssemblies"],
"autoReferenced": false,
+12 -1
View File
@@ -70,7 +70,9 @@
「游戏设置 → 画面与特效设置」提供接触阴影、角色光照、增强夜景火光和火光投影四个独立开关,在卡通画风中即时生效。接触阴影和火光投影在桌面设备默认开启,手持设备可按需开启。夜景火光使用暖色灯光与冷色环境底色。火光投影也适用于暗色迷宫,桌面默认四盏,控制台可通过 `Settings.ToonFireShadowBudget` 设置 0–4 盏,阴影图集随预算扩容。泛光可以独立开关,默认仅桌面原版画风开启。
上方截图来自旧版卡通渲染。可选剧情特效默认关闭。请在本地安装与 URP 兼容的编号预制体到 `Assets/Resources/Prefabs/VFX/PAL3/` 或 `Assets/Resources/Prefabs/VFX/PAL3A/`,再启用「可选剧情特效」。关闭时会立即隐藏当前可选特效。重新启用后,仍在场景中的持续特效会恢复,后续触发的剧情特效会照常显示。
上方截图来自旧版卡通渲染。PAL3 的剧情与场景特效默认由原版数据驱动,运行时读取本地 CPK 的特效组、任务、粒子、贴图和模型,使用自有 URP shader 与 Unity 原生渲染组件。Unity 菜单 `PAL3 → Original Effect Editor` 可浏览、播放、逐层检查、修改组任务和粒子曲线;覆盖资产保存到 `Assets/Resources/Effects/PAL3Overrides.asset` 后供游戏读取。ResourceViewer 提供原版特效控制面板及 `Effect.Load <组ID>`、`Effect.Seek <秒>`、`Effect.Pause true/false` 命令,组 ID `-1` 表示场景传送点。
迁移期间,PAL3 原版实现无法播放的组可以回退到本地私有 prefab;「可选剧情特效」仅控制这部分备用效果,不影响已接入的原版特效。PAL3A 暂时保留原有可选特效路径:在本地安装与 URP 兼容的编号预制体到 `Assets/Resources/Prefabs/VFX/PAL3A/` 后再开启。编辑器可并排预览原版实现与本地私有 prefab,后者只用于迁移对比。
公开构建请使用未导入本地付费素材的全新检出。若工程中有可选特效预制体、Hovl Studio、RealToon 或旧版卡通材质,Unity 会阻止构建。仅供个人使用的构建可通过环境变量 `PAL3_ALLOW_PRIVATE_ASSETS=1` 启动本地 Unity 来显式启用。工程打包菜单会将这类构建输出到带 `-Private` 后缀的版本目录。
@@ -83,6 +85,15 @@
仙剑奇侠传三以及仙剑奇侠传三外传的剧情部分已经全部完成,两部游戏都可以完整的从头玩到尾体验一遍剧情,也可以使用游戏内提供的剧情选择菜单跳转至预设好的剧情时间点。两部游戏中的迷宫机关也基本全部实现,剧情中出现的大部分特效也已经重新实现。但是战斗,小游戏以及围绕支持战斗系统的各类系统和功能均尚未完成。另外主菜单和大部分界面也需要重新设计和实现(毕竟现在还要做手机端的适配)。
## 如何贡献?
修改自有 C# 代码后,使用 `global.json` 指定的 .NET SDK,在工程根目录执行:
```sh
python3 tools/format-csharp.py
python3 tools/format-csharp.py --check
```
工具使用 SDK 自带的 `dotnet format`、`.editorconfig` 和固定版本的 StyleCop 布局规则,检查空格、缩进、函数/成员间空行及多条语句分行。默认只处理当前改动,分别检查 PAL3/PAL3A 条件分支,不需要 Unity 或游戏数据;StyleCop 仅用于开发工具,不进入 Unity 工程。PR 的 `Code style` 工作流执行相同检查。格式检查通过后仍需运行相关 Unity 测试;ShaderLab/HLSL 由人工整理并验证。
因为项目还处于早期实现过程中,很多系统还没有实现,暂时不接受比较大的Pull request,特别是feature类型,如果您有好的想法,意见或者发现了Bug请欢迎提交issue或者加入交流群与我讨论。
另外您还可以参考这个项目解析视频:https://www.bilibili.com/video/BV1Pr4y167sF
+6
View File
@@ -0,0 +1,6 @@
{
"sdk": {
"version": "10.0.403",
"rollForward": "disable"
}
}
+102
View File
@@ -0,0 +1,102 @@
#!/usr/bin/env python3
# ------------------------------------------------------------------------
# Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
# See LICENSE file in the project root for license information.
# ------------------------------------------------------------------------
"""Format owned C# changes with Roslyn and targeted StyleCop layout rules."""
import argparse
import os
from pathlib import Path
import subprocess
import tempfile
import xml.etree.ElementTree as ET
ROOT = Path(__file__).resolve().parents[1]
OWNED = ("Assets/Scripts/", "Assets/Tests/")
LAYOUT_RULES = ("SA1107", "SA1502", "SA1507", "SA1516")
def git_files(*args):
result = subprocess.check_output(["git", "-C", str(ROOT), *args, "-z"])
return {os.fsdecode(name) for name in result.split(b"\0") if name}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true", help="Fail instead of modifying files")
parser.add_argument("--verbose", action="store_true", help="Show detailed Roslyn/MSBuild diagnostics")
selection = parser.add_mutually_exclusive_group()
selection.add_argument("--base", help="Include C# changes since this Git ref")
selection.add_argument("--all", action="store_true", help="Include all owned C# sources")
parser.add_argument("paths", nargs="*", help="Optional repo-relative files or directories")
args = parser.parse_args()
if args.paths and (args.base or args.all):
parser.error("Explicit paths cannot be combined with --base or --all")
if args.all or args.paths:
files = git_files("ls-files", "--cached", "--others", "--exclude-standard")
else:
files = git_files("diff", "--name-only", "--diff-filter=ACMR", args.base or "HEAD")
files |= git_files("ls-files", "--others", "--exclude-standard")
files = sorted(name for name in files
if name.startswith(OWNED) and name.endswith(".cs") and (ROOT / name).is_file()
and (ROOT / name).resolve().is_relative_to(ROOT))
if args.paths:
requested = [(ROOT / path).resolve() for path in args.paths]
if any(not path.is_relative_to(ROOT) for path in requested):
parser.error("Paths must stay inside the repository")
files = [name for name in files if any(
(ROOT / name).resolve() == path or path in (ROOT / name).resolve().parents
for path in requested)]
if not files:
print("No owned C# changes to format.")
return 0
# A tiny format-only project avoids Unity-generated csproj files and needs
# no Unity install, game data or runtime third-party assemblies. Parsing
# both variants also checks whitespace inside #if PAL3 / #if PAL3A blocks.
workspace = ROOT.parent / "workspace"
temp_root = workspace / "Tooling" / "CodeStyle" if workspace.is_dir() else None
if temp_root is not None:
temp_root.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="pal3-format-", dir=temp_root) as temporary:
project = ET.Element("Project", Sdk="Microsoft.NET.Sdk")
properties = ET.SubElement(project, "PropertyGroup")
for name, value in {
"TargetFramework": "net10.0",
"EnableDefaultCompileItems": "false",
"GenerateAssemblyInfo": "false",
"NuGetAudit": "false",
"DefineConstants": "$(PAL3_FORMAT_VARIANT);UNITY_EDITOR",
}.items():
ET.SubElement(properties, name).text = value
items = ET.SubElement(project, "ItemGroup")
ET.SubElement(items, "PackageReference", Include="StyleCop.Analyzers", Version="1.3.180", PrivateAssets="all")
# The SDK discovers .editorconfig from each source path automatically.
# Adding it explicitly would register it twice in the Roslyn workspace.
for name in files:
ET.SubElement(items, "Compile", Include=str(ROOT / name))
project_path = Path(temporary) / "Formatting.csproj"
ET.ElementTree(project).write(project_path, encoding="utf-8", xml_declaration=True)
print(f"{'Checking' if args.check else 'Formatting'} {len(files)} C# files (PAL3 and PAL3A).", flush=True)
subprocess.run(["dotnet", "restore", str(project_path), "--verbosity", "quiet"], cwd=ROOT, check=True)
failed = False
for variant in ("PAL3", "PAL3A"):
for subcommand, extra in (("analyzers", ["--diagnostics", *LAYOUT_RULES]), ("whitespace", [])):
verbosity = "diagnostic" if args.verbose else "minimal"
command = ["dotnet", "format", subcommand, str(project_path), "--no-restore", "--verbosity", verbosity, *extra]
if args.check:
command.append("--verify-no-changes")
result = subprocess.run(command, cwd=ROOT, env={**os.environ, "PAL3_FORMAT_VARIANT": variant})
failed |= result.returncode != 0
return 1 if failed else 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except (OSError, subprocess.CalledProcessError) as error:
raise SystemExit(str(error)) from error
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env python3
# ------------------------------------------------------------------------
# Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
# See LICENSE file in the project root for license information.
# ------------------------------------------------------------------------
"""Exercise the actual formatter with missing member gaps in both variants."""
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
ROOT = Path(__file__).resolve().parents[2]
def run(command, cwd, success=True):
result = subprocess.run(command, cwd=cwd, capture_output=True, text=True, timeout=180,
env={**os.environ, "TMPDIR": str(cwd)})
if (result.returncode == 0) != success:
raise AssertionError(f"Unexpected exit {result.returncode}: {command}\n{result.stdout}\n{result.stderr}")
return result.stdout + result.stderr
def main():
workspace = ROOT.parent / "workspace"
temporary_root = workspace / "Tooling" / "CodeStyle" if workspace.is_dir() else None
if temporary_root is not None:
temporary_root.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="pal3-format-test-", dir=temporary_root) as directory:
fixture = Path(directory)
(fixture / "tools").mkdir()
for name in (".editorconfig", "global.json", "tools/format-csharp.py"):
shutil.copy2(ROOT / name, fixture / name)
source = fixture / "Assets/Scripts/Effect layout.cs"
source.parent.mkdir(parents=True)
good = ("internal sealed class Layout\n{\n#if PAL3\n"
" public int AOne() => 1;\n\n public int ATwo() => 2;\n"
"#elif PAL3A\n public int BOne() => 1;\n\n public int BTwo() => 2;\n#endif\n}\n")
source.write_bytes(good.replace("\n", "\r\n").encode())
plugin = fixture / "Assets/Plugins/Keep.cs"
plugin.parent.mkdir()
plugin.write_bytes(b"class Plugin{void One(){}void Two(){}}")
plugin_before = plugin.read_bytes()
run(["git", "init", "--quiet"], fixture)
run(["git", "add", "."], fixture)
run(["git", "-c", "user.name=Format fixture", "-c", "user.email=fixture@localhost",
"-c", "commit.gpgsign=false", "commit", "--quiet", "-m", "Fixture baseline"], fixture)
base = run(["git", "rev-parse", "HEAD"], fixture).strip()
command = [sys.executable, "tools/format-csharp.py"]
source.write_bytes(good.replace(";\n\n", ";\n").replace("\n", "\r\n").encode())
before = source.read_bytes()
output = run([*command, "--check"], fixture, success=False)
assert "SA1516" in output, output
assert source.read_bytes() == before, "Check mode modified the source"
run(command, fixture)
fixed = source.read_bytes()
assert b"AOne() => 1;\r\n\r\n" in fixed
assert b"BOne() => 1;\r\n\r\n" in fixed
run([*command, "--check", "--all"], fixture)
assert source.read_bytes() == fixed, "Formatting is not stable"
# A violation only in PAL3A must fail the same --base mode as PR CI.
source.write_bytes(fixed.replace(b"BOne() => 1;\r\n\r\n", b"BOne() => 1;\r\n"))
output = run([*command, "--check", "--base", base], fixture, success=False)
assert "SA1516" in output, output
assert plugin.read_bytes() == plugin_before, "Third-party source was modified"
print("Passed: missing member gaps fail, both variants auto-fix, check is read-only and stable, --base checks PAL3A, plugins stay untouched.")
if __name__ == "__main__":
main()