Remove prefab effect fallback and simplify effect editing

This commit is contained in:
Jiaqi (0x7c13) Liu committed 2026-11-14 03:46:07 +08:00
1 parent fc982180f0
commit 39522b1a74
36 files changed
+512 -948

No files matched your search

+6 -4
View File
@@ -11,10 +11,13 @@ The separate `Code style` workflow verifies changed owned C# files with the SDK'
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
It parses both PAL3 and PAL3A conditional branches without Unity or game data.
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.
Default and `--base` runs apply formatting only to changed lines and deletion
boundaries, preserving existing formatting elsewhere. Explicit file/directory
paths and `--all` format whole files. Check mode operates on temporary copies.
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;
@@ -26,8 +29,7 @@ The builder CLI is pinned to v0.1.73 so its behavior does not change independent
of the workflow. Update and validate this pin together with builder upgrades.
Keep the committed project configured for PAL3. PAL3A workflows switch their own
checkout before building. Public builds reject imported private VFX and legacy Toon assets;
do not add them or original game data to CI inputs.
checkout before building. Do not add original game data to CI inputs.
When investigating a failure, inspect the failed job's Unity/build logs first.
Retry an isolated runner or network failure after checking the log; fix reproducible
+10 -15
View File
@@ -77,20 +77,15 @@ crashlytics-build.properties
# Unity StreamingAssets folder
/Assets/StreamingAssets
# 3rd party plugin/assets
/Assets/Hovl Studio
/Assets/Hovl Studio.meta
/Assets/RealToon
/Assets/RealToon.meta
# VFX prefabs that are using 3rd party assets
/Assets/Resources/Prefabs/VFX/PAL3/*.prefab
/Assets/Resources/Prefabs/VFX/PAL3/*.meta
/Assets/Resources/Prefabs/VFX/PAL3A/*.prefab
/Assets/Resources/Prefabs/VFX/PAL3A/*.meta
# Materials that are using 3rd party assets
/Assets/Resources/Materials/
# VS Conde config file
.vsconfig
# Local asset imports
/Assets/Hovl Studio/
/Assets/Hovl Studio.meta
/Assets/RealToon/
/Assets/RealToon.meta
/Assets/Resources/Prefabs/VFX/
/Assets/Resources/Prefabs/VFX.meta
/Assets/Resources/Materials/
/Assets/Resources/Materials.meta
-8
View File
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 0b0b27c9e5e4d2e4fbc9b6584f828f7b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
-8
View File
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 2eaeb845461401e488e4640caf779ddf
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
-8
View File
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: b93923849ec63ad4ea52f79bf5bc9cb6
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,45 +0,0 @@
因为当前特效的实现方式使用了第三方插件和素材,所以此文件夹内的所有prefab均添加进了gitignore里。
请联系作者了解插件获取方式和特效prefab的获取方式。
0 => 传送法阵特效
15 => 单人传送特效
98 => 重楼施法帮龙葵恢复肉身时的特效
175 => 邪剑仙迷倒众人的特效
224 => 丁小侠剧情狼妖受击特效
251 => 邪剑仙变身特效
252 => 邪剑仙传送离开时的特效
254 => 重楼传送法术特效
255 => 龙葵穿衣服的特效
256 => 龙葵治疗他人特效
257 => 治疗咒施法特效
259 => 大型传送法施法前奏特效
260 => 大型传送法阵特效收尾
261 => 大型传送法阵特效开始
262 => 重楼当剑的时候剑插入地面的火光特效
263 => 火鬼王消失特效
264 => 古藤精施法特效
265 => 人物受到法术作用时候的特效
266 => 邪剑仙施法特效
270 => 天鬼皇复活后灵魂出窍特效
275 => 重楼创建的用来禁锢雪见/龙葵的法阵特效
276 => 迴魂施法结束特效
277 => 迴魂施法完全结束特效
278 => 迴魂施法特效
290 => 雪见传送出现时特效
295 => 重楼施法治疗特效
297 => 紫萱施法召唤水灵特效
337 => 古藤精风系法术特效
341 => 邪剑仙给镇妖剑施法特效
368 => 雷击单体施法特效
369 => 雷击范围施法特效
376 => 紫萱的土系法术特效
389 => 紫萱给江姑娘施法特效
452 => 花楹治疗他人特效
453 => 人物施法蓄力时的特效
454 => 龙葵施法让众人御剑飞行的特效
456 => 老婆婆施法特效
457 => 夕瑶给景天施法时的特效
458 => 灵力溢出特效
467 => 邪剑仙灰飞烟灭特效
468 => 蓝龙葵变红龙葵的特效
@@ -1,7 +0,0 @@
fileFormatVersion: 2
guid: 815b64a4a03e7b949bd85e1e5c19deb3
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
-8
View File
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: a637ebcead3359c4f849f936d41707ee
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,67 +0,0 @@
因为当前特效的实现方式使用了第三方插件和素材,所以此文件夹内的所有prefab均添加进了gitignore里。
请联系作者了解插件获取方式和特效prefab的获取方式。
0 => 传送法阵特效
9 => 茅山道士封印法术特效
40 => 单体风咒特效
50 => 单体雷咒特效
91 => 封印法术特效
157 => 角色传送出现特效
164 => 南宫煌变身狼形态时的特效
170 => 王蓬絮变身特效
171 => 人物施法特效
172 => 人物受到法术作用时候的特效
173 => 人物受到法术作用时候的特效
174 => 治疗特效
175 => 茅山术士打乱三杯盏特效
176 => 南宫煌打乱三杯盏特效
177 => 角色传送消失时的特效
178 => 南宫煌使关桃子的笼子消失的特效
179 => 南宫煌变出法桌的特效
181 => 南宫煌变出小东西的特效
182 => 南宫煌变出大东西的特效
186 => 大石块砸下后的尘土特效
189 => 地脉石门封印打开时的特效
198 => 南宫煌变出东西的特效
201 => 魁妖变小特效
205 => 照妖镜发光的特效
209 => 五灵轮特效
211 => 洒金笺特效
230 => 重楼施法消灭怪物的特效
254 => 重楼传送特效
257 => 隔空取物特效
258 => 迴魂传送特效
259 => 大型传送法施法前奏特效
260 => 大型传送法阵特效收尾
261 => 大型传送法阵特效开始
281 => 角色传送消失时的特效
282 => 雷咒特效
283 => 物品消失时的特效
285 => 南宫煌施法特效
287 => 土灵珠特效
289 => 血魂姬施法特效
290 => 回复法阵特效
292 => 五灵轮发光特效
299 => 重楼传送众人特效
314 => 倾国银弹波特效
315 => 南宫煌切换为人形态特效
316 => 魔物出现特效
318 => 千凝魔艮特效
320 => 幽娘变身特效
322 => 幽娘吸收怨气特效
323 => 幽娘收集怨气特效
325 => 陆北亭变身特效
328 => 风雅颂开心的特效
333 => 感月出现特效
355 => 王蓬絮治疗特效
359 => 蝎魃消失特效
360 => 星璇给南宫煌输入内力时的特效
367 => 五毒珠治疗特效
388 => 迴魂传送特效
389 => 迴魂传送特效
397 => 燎日变身特效
401 => 魔尊帮星璇灵肉合一的特效
404 => 思堂消失特效
408 => 星璇燎日变换时特效
424 => 王蓬絮对南宫煌施法特效
@@ -1,7 +0,0 @@
fileFormatVersion: 2
guid: f1d950c46b3119043a1919074fdc27c5
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -21,7 +21,7 @@ namespace Editor
using UnityEngine.SceneManagement;
using UnityEngine.UIElements;
public sealed class OriginalEffectEditor : EditorWindow
public sealed class EffectEditor : EditorWindow
{
private OriginalEffectResources _resources;
private OriginalEffectPlayer _player;
@@ -29,10 +29,10 @@ namespace Editor
private uint _portalType;
[SerializeField] private OriginalEffectOverrides _edits;
[SerializeField] private string _assetPath = "", _savedJson;
private GameObject _root, _private;
private GameObject _root;
private Scene _scene;
private Camera _camera;
private RenderTexture _target, _privateTarget;
private RenderTexture _target;
private string _dataPath, _search = "", _error;
[SerializeField] private bool _pal3a;
@@ -43,7 +43,7 @@ namespace Editor
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 bool _playing, _loop;
private uint _seed = 1;
private bool _emitterCurve;
private int _particleIndex, _curveIndex;
@@ -52,17 +52,17 @@ namespace Editor
private float? _pendingSeek;
private double _seekAfter;
[MenuItem("PAL3/Original Effect Editor")]
[MenuItem("PAL3/Effect Editor")]
public static void Open()
{
var window = GetWindow<OriginalEffectEditor>("Original Effects");
var window = GetWindow<EffectEditor>("Effects");
window.ChangeVariant(false);
}
[MenuItem("PAL3A/Original Effect Editor")]
[MenuItem("PAL3A/Effect Editor")]
public static void OpenPal3A()
{
var window = GetWindow<OriginalEffectEditor>("Original Effects");
var window = GetWindow<EffectEditor>("Effects");
window.ChangeVariant(true);
}
@@ -124,11 +124,6 @@ namespace Editor
_target.Release();
DestroyImmediate(_target);
}
if (_privateTarget != null)
{
_privateTarget.Release();
DestroyImmediate(_privateTarget);
}
if (_scene.IsValid())
EditorSceneManager.ClosePreviewScene(_scene);
}
@@ -247,8 +242,6 @@ namespace Editor
{
if (_root != null)
DestroyImmediate(_root);
if (_private != null)
DestroyImmediate(_private);
_player = null;
_portal = null;
}
@@ -287,23 +280,6 @@ namespace Editor
_error = _player.Error;
}
}
if (_compare)
{
GameObject prefab = Resources.Load<GameObject>($"Prefabs/VFX/{Variant}/{(_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)
{
@@ -341,9 +317,6 @@ namespace Editor
_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)
@@ -352,9 +325,6 @@ namespace Editor
_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)
@@ -463,12 +433,6 @@ namespace Editor
_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);
@@ -487,7 +451,7 @@ namespace Editor
Restart();
}
}
EditorGUILayout.LabelField($"Original nodes: {_player?.NodeCount ?? 0} Quads/particles: {_player?.QuadCount ?? 0} {_player?.Error}");
EditorGUILayout.LabelField($"Objects: {_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);
@@ -524,7 +488,7 @@ namespace Editor
}
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);
int w = Mathf.Max(1, (int)rect.width), h = Mathf.Max(1, (int)rect.height);
if (_target == null || _target.width != w || _target.height != h)
{
if (_target != null)
@@ -532,47 +496,21 @@ namespace Editor
_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 {Variant} data");
if (_compare)
Draw(_privateTarget, _root, new Rect(rect.x + w, rect.y, w, h), _private != null ? "Private prefab (comparison only)" : "No private prefab");
RenderPipeline.SubmitRenderRequest(_camera, new UniversalRenderPipeline.SingleCameraRequest { destination = _target });
GUI.DrawTexture(rect, _target, ScaleMode.StretchToFill, false);
GUI.Label(new Rect(rect.x + 8, rect.y + 8, rect.width - 16, 25), $"{Variant} effect data", EditorStyles.whiteBoldLabel);
}
private void DrawInspector()
{
EditorGUILayout.LabelField("Original object / task parameters", EditorStyles.boldLabel);
EditorGUILayout.LabelField("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);
@@ -1,61 +0,0 @@
// ------------------------------------------------------------------------
// 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.Linq;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
internal sealed class PrivateAssetBuildGuard : IPreprocessBuildWithReport
{
private const string PrivateBuildVariable = "PAL3_ALLOW_PRIVATE_ASSETS";
private const string StoryVfxPath = "/Resources/Prefabs/VFX/";
private const string HovlStudioPath = "/Hovl Studio/";
private const string RealToonPath = "/RealToon/";
private const string LegacyToonMaterialsPath = "Assets/Resources/Materials/";
private const string Pal3VfxReadme = "Assets/Resources/Prefabs/VFX/PAL3/README.txt";
private const string Pal3AVfxReadme = "Assets/Resources/Prefabs/VFX/PAL3A/README.txt";
internal static bool PrivateBuildEnabled =>
Environment.GetEnvironmentVariable(PrivateBuildVariable) == "1" &&
string.IsNullOrEmpty(Environment.GetEnvironmentVariable("CI")) &&
string.IsNullOrEmpty(Environment.GetEnvironmentVariable("GITHUB_ACTIONS"));
public int callbackOrder => int.MaxValue;
public void OnPreprocessBuild(BuildReport report) => Validate();
internal static void Validate()
{
if (PrivateBuildEnabled) return;
string privateAsset = AssetDatabase.GetAllAssetPaths().FirstOrDefault(IsPrivateAsset);
if (privateAsset == null) return;
throw new BuildFailedException(
$"Local optional VFX or legacy Toon assets are installed ({privateAsset}). " +
"Use a clean checkout for public builds. " +
$"For a private local build, launch Unity with {PrivateBuildVariable}=1.");
}
private static bool IsPrivateAsset(string assetPath)
{
if (assetPath.IndexOf(HovlStudioPath, StringComparison.OrdinalIgnoreCase) < 0 &&
assetPath.IndexOf(RealToonPath, StringComparison.OrdinalIgnoreCase) < 0 &&
!assetPath.StartsWith(LegacyToonMaterialsPath, StringComparison.OrdinalIgnoreCase) &&
assetPath.IndexOf(StoryVfxPath, StringComparison.OrdinalIgnoreCase) < 0)
{
return false;
}
return !assetPath.Equals(Pal3VfxReadme, StringComparison.OrdinalIgnoreCase) &&
!assetPath.Equals(Pal3AVfxReadme, StringComparison.OrdinalIgnoreCase) &&
!AssetDatabase.IsValidFolder(assetPath);
}
}
}
@@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: ac41b9b3ac5641d98126273f7efb452f
+7 -11
View File
@@ -131,15 +131,13 @@ namespace Editor
private static void BuildGame(Pal3BuildTarget buildTarget)
{
PrivateAssetBuildGuard.Validate();
BuildTargetGroup targetGroupBeforeBuild = EditorUserBuildSettings.selectedBuildTargetGroup;
BuildTarget targetBeforeBuild = EditorUserBuildSettings.activeBuildTarget;
string buildOutputPath = EditorUtility.SaveFolderPanel("Choose Location of Built Game", "", "");
if (string.IsNullOrWhiteSpace(buildOutputPath)) return;
string versionFolder = GetVersionFolderName(PrivateAssetBuildGuard.PrivateBuildEnabled);
string versionFolder = GetVersionFolderName();
buildOutputPath += $"{DirSeparator}{versionFolder}{DirSeparator}";
var buildConfigurations = new[]
@@ -271,14 +269,14 @@ namespace Editor
}
}
private static string GetVersionFolderName(bool privateBuild)
private static string GetVersionFolderName()
{
return PlayerSettings.bundleVersion + (privateBuild ? "-Private" : "");
return PlayerSettings.bundleVersion;
}
private static void ZipReleaseFiles()
{
string versionFolder = GetVersionFolderName(PrivateAssetBuildGuard.PrivateBuildEnabled);
string versionFolder = GetVersionFolderName();
string buildOutputPath = EditorUtility.SaveFolderPanel("Choose Location of Built Game",
versionFolder, versionFolder);
if (string.IsNullOrWhiteSpace(buildOutputPath)) return;
@@ -289,12 +287,10 @@ namespace Editor
{
string selectedFolder = Path.GetFileName(buildOutputPath.TrimEnd(
Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
bool privateBuild = selectedFolder == GetVersionFolderName(true);
if (!privateBuild && selectedFolder != GetVersionFolderName(false))
if (selectedFolder != GetVersionFolderName())
{
Debug.LogError($"Invalid build output path: {buildOutputPath}. " +
$"Please choose the current release build folder \"{GetVersionFolderName(false)}\" " +
$"or \"{GetVersionFolderName(true)}\".");
$"Please choose the current release build folder \"{GetVersionFolderName()}\".");
return;
}
@@ -313,7 +309,7 @@ namespace Editor
foreach ((string folderPath, Pal3BuildTarget target) in buildTargets)
{
string fullPath = $"{buildOutputPath}{DirSeparator}{folderPath}";
string zipFileName = $"{GameConstants.AppName}_v{GetVersionFolderName(privateBuild)}_{target.ToString()}.zip";
string zipFileName = $"{GameConstants.AppName}_v{GetVersionFolderName()}_{target.ToString()}.zip";
string zipFilePath = $"{releaseDirPath}{DirSeparator}{zipFileName}";
if (File.Exists(fullPath) || Directory.Exists(fullPath))
@@ -61,65 +61,5 @@ namespace Pal3.Core.Contract.Constants
"", 1f, 0.6f) },
};
#endif
#if PAL3
// Effect group id to sfx mapping
public static readonly Dictionary<int, string> EffectSfxInfo = new()
{
{ 251, "wd163" },
{ 252, "wd160" },
{ 254, "wd163" },
{ 255, "wd155" },
{ 256, "wd008" },
{ 257, "wd001" },
{ 261, "wd163" },
{ 264, "wd160" },
{ 266, "wd160" },
{ 276, "wd150" },
{ 278, "wd150" },
{ 297, "wd141" },
{ 341, "wd160" },
{ 457, "wd141" },
{ 458, "wd140" },
};
#elif PAL3A
public static readonly Dictionary<int, string> EffectSfxInfo = new()
{
{ 91, "WD156" },
{ 170, "WD155" },
{ 171, "WD163" },
{ 172, "WD189" },
{ 173, "WD189" },
{ 174, "WD308" },
{ 175, "WD051" },
{ 176, "WD051" },
{ 177, "WD159" },
{ 178, "WD032" },
{ 179, "WD497" },
{ 181, "WD018" },
{ 182, "WD018" },
{ 189, "WD035" },
{ 198, "WD018" },
{ 209, "WD309" },
{ 211, "WD002" },
{ 230, "WD342" },
{ 254, "WD163" },
{ 257, "WD008" },
{ 258, "WD165" },
{ 259, "WD163" },
{ 281, "WD159" },
{ 283, "WD018" },
{ 285, "WD422" },
{ 290, "WD418" },
{ 299, "WD150" },
{ 322, "WD163" },
{ 323, "WD189" },
{ 328, "WD532" },
{ 388, "WD165" },
{ 389, "WD165" },
{ 397, "WD459" },
{ 408, "WD459" },
};
#endif
}
}
@@ -67,7 +67,7 @@ namespace Pal3.Game.Data
private readonly int _codepage;
internal OptionalVfxPlayer OptionalVfx
internal EffectRuntime Effects
{
get;
}
@@ -86,7 +86,7 @@ namespace Pal3.Game.Data
_codepage = _gameSettings.Language == Language.SimplifiedChinese ? 936 : 950;
_gameDatabase = GetGameDatabaseFile(); // Initialize game database file
OptionalVfx = new OptionalVfxPlayer(_gameSettings, _fileSystem, _codepage);
Effects = new EffectRuntime(_fileSystem, _codepage);
CommandExecutorRegistry<ICommand>.Instance.Register(this);
}
@@ -115,7 +115,7 @@ namespace Pal3.Game.Data
}
_audioClipCache.Clear();
OptionalVfx.Dispose();
Effects.Dispose();
_materialManager.Dispose();
@@ -148,7 +148,7 @@ namespace Pal3.Game.Data
return _shadowSprite;
}
public Effect.Original.OriginalEffectResources OriginalEffects => OptionalVfx.Original;
public Effect.Original.OriginalEffectResources OriginalEffects => Effects.Original;
public IMaterialManager GetMaterialManager() => _materialManager;
@@ -601,7 +601,7 @@ namespace Pal3.Game.Data
}
}
OptionalVfx.ClearPrefabCache();
Effects.InvalidatePreloads();
}
}
-2
View File
@@ -513,8 +513,6 @@ namespace Pal3.Game.Dev
value => _gameSettings.ToonFireShadows = value);
AddOption("泛光", () => _gameSettings.BloomEnabled,
value => _gameSettings.BloomEnabled = value);
AddOption("可选剧情特效", () => _gameSettings.OptionalVfxEnabled,
value => _gameSettings.OptionalVfxEnabled = value);
CreateMenuButton("返回", _ => delegate
{
@@ -21,7 +21,7 @@ namespace Pal3.Game.Effect
public void Init(GameResourceProvider resourceProvider, uint effectParameter)
{
// Scene effects use the same native group scheduler as script effects.
_effect = resourceProvider.OptionalVfx.Attach((int)effectParameter, GameEntity);
_effect = resourceProvider.Effects.Attach((int)effectParameter, GameEntity);
}
private void OnDestroy() => Dispose();
@@ -30,9 +30,11 @@ namespace Pal3.Game.Effect
ICommandExecutor<SceneLeavingCurrentSceneNotification>,
ICommandExecutor<ResetGameStateCommand>
{
private readonly OptionalVfxPlayer _optionalVfx;
private readonly EffectRuntime _effects;
private readonly SceneManager _sceneManager;
private ICommand _effectPositionCommand;
#if PAL3A
private EffectAttachToActorCommand _attachedActor;
#endif
private Vector3 _originalPosition;
private const string EFFECT_LINKER_FILE_NAME = "efflinker.dat";
@@ -41,7 +43,7 @@ namespace Pal3.Game.Effect
public EffectManager(GameResourceProvider resourceProvider,
SceneManager sceneManager)
{
_optionalVfx = Requires.IsNotNull(resourceProvider, nameof(resourceProvider)).OptionalVfx;
_effects = Requires.IsNotNull(resourceProvider, nameof(resourceProvider)).Effects;
_sceneManager = Requires.IsNotNull(sceneManager, nameof(sceneManager));
_effectLinkerFile = resourceProvider.GetGameResourceFile<EffectLinkerFile>(
@@ -63,7 +65,7 @@ namespace Pal3.Game.Effect
// 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
Pal3.Instance.StartCoroutine(_optionalVfx.PreloadAsync(command.EffectGroupId));
Pal3.Instance.StartCoroutine(_effects.PreloadAsync(command.EffectGroupId));
#endif
}
@@ -72,23 +74,14 @@ namespace Pal3.Game.Effect
if (_sceneManager.GetCurrentScene() is not { } currentScene)
return;
#if PAL3A
if (_effectPositionCommand is EffectAttachToActorCommand attach &&
if (_attachedActor is { } attach &&
!currentScene.GetActorGameEntity(attach.ActorId).IsNullOrDisposed())
HandleNanGongHuangTransformEffect(attach, command, currentScene);
#endif
// Both games retain the last position when cmd_CEft_Role cannot find
// its actor. Playback uses that snapshot even if the actor is gone.
bool playedOriginal = _optionalVfx.Play(command.EffectGroupId,
_sceneManager.GetSceneRootGameEntity(), _originalPosition,
privateFallback: _effectPositionCommand is EffectAttachToActorCommand role
? (currentScene.GetActorGameEntity(role.ActorId), Vector3.zero) : null);
// 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));
}
_effects.Play(command.EffectGroupId,
_sceneManager.GetSceneRootGameEntity(), _originalPosition);
}
#if PAL3A
@@ -131,13 +124,17 @@ namespace Pal3.Game.Effect
public void Execute(EffectSetPositionCommand command)
{
_effectPositionCommand = command;
#if PAL3A
_attachedActor = null;
#endif
_originalPosition = new GameBoxVector3(command.GameBoxXPosition, command.GameBoxYPosition, command.GameBoxZPosition).ToUnityPosition();
}
public void Execute(EffectAttachToActorCommand command)
{
_effectPositionCommand = command;
#if PAL3A
_attachedActor = command;
#endif
var scene = _sceneManager.GetCurrentScene();
var actor = scene?.GetActorGameEntity(command.ActorId);
if (!actor.IsNullOrDisposed())
@@ -156,9 +153,11 @@ namespace Pal3.Game.Effect
private void ClearSceneEffects()
{
_effectPositionCommand = null;
#if PAL3A
_attachedActor = null;
#endif
_originalPosition = Vector3.zero;
_optionalVfx.ClearPlayedEffects();
_effects.ClearPlayedEffects();
}
}
}
@@ -0,0 +1,243 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Game.Effect
{
using System;
using System.Collections;
using System.Collections.Generic;
using Original;
using Core.FileSystem;
using Core.Command.SceCommands;
using Engine.Core.Abstraction;
using Engine.Core.Implementation;
using Engine.Extensions;
using Engine.Logging;
using UnityEngine;
internal sealed class EffectRuntime : IDisposable
{
private readonly OriginalEffectResources _original;
private readonly HashSet<int> _failures = new();
private readonly List<IGameEntity> _playedEffects = new();
private readonly List<PersistentEffect> _persistentEffects = new();
private int _preloadGeneration;
private bool _disposed;
internal OriginalEffectResources Original => _original;
internal EffectRuntime(ICpkFileSystem fileSystem, int codepage)
{
_original = new OriginalEffectResources(fileSystem, codepage);
}
internal IEnumerator PreloadAsync(int groupId)
{
if (_disposed)
yield break;
int generation = _preloadGeneration;
OriginalEffectOverrides edits;
try
{
edits = Resources.Load<OriginalEffectOverrides>(_original.OverridesPath);
string[] issues = _original.Diagnose(groupId, edits);
if (issues.Length != 0)
{
Report(groupId, string.Join("\n", issues));
yield break;
}
}
catch (Exception ex)
{
Report(groupId, ex.Message);
yield break;
}
using var preload = _original.Preload(groupId, edits).GetEnumerator();
while (!_disposed && generation == _preloadGeneration)
{
bool next;
try
{
next = preload.MoveNext();
}
catch (Exception ex)
{
Report(groupId, ex.Message);
break;
}
if (!next)
break;
yield return null;
}
}
private void Report(int groupId, string message)
{
if (_failures.Add(groupId))
EngineLogger.LogWarning($"Effect {groupId}: {message}");
}
private IGameEntity Create(int groupId, IGameEntity parent, uint portalType = 0)
{
if (_disposed || parent.IsNullOrDisposed())
return null;
GameObject root = null;
try
{
var edits = Resources.Load<OriginalEffectOverrides>(_original.OverridesPath);
string[] issues = groupId == -1 ? Array.Empty<string>() : _original.Diagnose(groupId, edits);
if (issues.Length != 0)
{
Report(groupId, string.Join("\n", issues));
return null;
}
root = new GameObject(groupId == -1 ? "Original transport" : $"Original effect {groupId}");
root.transform.SetParent((Transform)parent.Transform.NativeObject, false);
if (groupId == -1)
root.AddComponent<OriginalPortalEffect>().Initialize(_original, portalType);
else
{
var player = root.AddComponent<OriginalEffectPlayer>();
player.Initialize(_original, groupId, (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(root);
}
catch (Exception ex)
{
if (root != null)
{
root.SetActive(false);
OriginalEffectResources.Destroy(root);
}
Report(groupId, ex.Message);
return null;
}
}
internal bool Play(int groupId, IGameEntity parent, Vector3 localPosition)
{
if (Create(groupId, parent) is not { } instance)
return false;
instance.Transform.LocalPosition += localPosition;
_playedEffects.RemoveAll(effect => effect.IsNativeObjectDisposed);
_playedEffects.Add(instance);
return true;
}
internal IDisposable AttachPortal(IGameEntity parent, uint type = 0) => Attach(-1, parent, type);
internal IDisposable Attach(int groupId, IGameEntity parent, uint portalType = 0)
{
if (_disposed || parent.IsNullOrDisposed())
return null;
PruneDeadAttachments();
var effect = new PersistentEffect(this, groupId, parent, portalType);
_persistentEffects.Add(effect);
return effect;
}
internal void ClearPlayedEffects()
{
foreach (IGameEntity effect in _playedEffects)
Stop(effect);
_playedEffects.Clear();
InvalidatePreloads();
_failures.Clear();
if (_disposed)
return;
if (Application.isPlaying && Pal3.Instance != null)
Pal3.Instance.StartCoroutine(TrimSceneRenderAssetsAfterFrame());
else
_original.TrimUnusedRenderAssets(LiveRoots());
}
private IEnumerator TrimSceneRenderAssetsAfterFrame()
{
// Scene objects are destroyed at the end of the leaving frame.
yield return null;
if (_disposed)
yield break;
PruneDeadAttachments();
_original.TrimUnusedRenderAssets(LiveRoots());
}
private IEnumerable<GameObject> LiveRoots()
{
foreach (IGameEntity effect in _playedEffects)
if (!effect.IsNullOrDisposed())
yield return (GameObject)effect.NativeObject;
foreach (PersistentEffect effect in _persistentEffects)
if (effect.Root != null)
yield return effect.Root;
}
private static void Stop(IGameEntity effect)
{
if (effect.IsNullOrDisposed())
return;
((GameObject)effect.NativeObject).SetActive(false);
effect.Destroy();
}
private void PruneDeadAttachments()
{
for (int i = _persistentEffects.Count - 1; i >= 0; i--)
if (_persistentEffects[i].ParentIsDisposed)
_persistentEffects[i].Dispose();
}
internal void InvalidatePreloads()
{
PruneDeadAttachments();
_preloadGeneration++;
}
public void Dispose()
{
if (_disposed)
return;
_disposed = true;
ClearPlayedEffects();
foreach (PersistentEffect effect in _persistentEffects.ToArray())
effect.Dispose();
_original.Dispose();
}
private sealed class PersistentEffect : IDisposable
{
private readonly EffectRuntime _owner;
private readonly IGameEntity _parent;
private IGameEntity _instance;
internal bool ParentIsDisposed => _parent.IsNullOrDisposed();
internal GameObject Root => _instance.IsNullOrDisposed() ? null : (GameObject)_instance.NativeObject;
internal PersistentEffect(EffectRuntime owner, int groupId, IGameEntity parent, uint portalType)
{
_owner = owner;
_parent = parent;
_instance = owner.Create(groupId, parent, portalType);
if (Root != null && Root.GetComponent<OriginalEffectPlayer>() is { } player)
{
player.DestroyOnComplete = false;
player.Loop = true;
player.RepeatInterval = owner._original.GameVariant == "PAL3" && groupId == 275 ? 9.5f : 0;
}
}
public void Dispose()
{
_owner._persistentEffects.Remove(this);
Stop(_instance);
_instance = null;
}
}
}
}
@@ -1,362 +0,0 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Game.Effect
{
using System;
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;
using Engine.Logging;
using Settings;
using UnityEngine;
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 && (_original != null || _settings.OptionalVfxEnabled);
internal OptionalVfxPlayer(GameSettings settings, ICpkFileSystem fileSystem, int codepage)
{
_settings = settings;
_original = new OriginalEffectResources(fileSystem, codepage);
_settings.OnGameSettingsChanged += OnGameSettingsChanged;
}
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;
int generation = _prefabCacheGeneration;
bool useOriginal = false;
OriginalEffectOverrides edits = null;
try
{
edits = Resources.Load<OriginalEffectOverrides>(_original.OverridesPath);
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;
if (IsEnabled && generation == _prefabCacheGeneration && !_prefabs.ContainsKey(effectGroupId))
{
CachePrefab(effectGroupId, request.asset as GameObject);
}
}
private void CachePrefab(int effectGroupId, GameObject prefab)
{
_prefabs[effectGroupId] = prefab;
if (prefab == null)
{
EngineLogger.LogWarning($"VFX prefab not found: {effectGroupId}");
}
}
private IGameEntity Create(int effectGroupId, IGameEntity parent, (IGameEntity parent, Vector3 position)? privateFallback = null, bool allowOriginal = true, uint portalType = 0)
{
if (!IsEnabled || parent.IsNullOrDisposed())
return null;
if (allowOriginal && _original != null)
{
GameObject native = null;
try
{
var edits = Resources.Load<OriginalEffectOverrides>(_original.OverridesPath);
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, portalType);
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);
}
IGameEntity prefabParent = privateFallback.HasValue ? privateFallback.Value.parent : parent;
return prefab == null || prefabParent.IsNullOrDisposed() ? null :
GameEntityFactory.Create($"VFX_{effectGroupId}", prefab, prefabParent, worldPositionStays: false);
}
internal bool Play(int effectGroupId, IGameEntity parent, Vector3 localPosition,
(IGameEntity parent, Vector3 position)? privateFallback = null)
{
if (Create(effectGroupId, parent, privateFallback) is not { } instance)
return false;
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, uint type = 0) => Attach(-1, parent, portalType: type);
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 AttachPrivate(int effectGroupId, IGameEntity parent) => Attach(effectGroupId, parent, false);
internal IDisposable Attach(int effectGroupId, IGameEntity parent, bool allowOriginal = true, uint portalType = 0)
{
if (_disposed || parent.IsNullOrDisposed())
return null;
PruneDeadAttachments();
var effect = new PersistentEffect(this, effectGroupId, parent, allowOriginal, portalType);
_persistentEffects.Add(effect);
effect.Refresh();
return effect;
}
private void OnGameSettingsChanged(string propertyName)
{
if (propertyName != nameof(GameSettings.OptionalVfxEnabled))
return;
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(reconsiderPrivate: true);
}
}
internal void ClearPlayedEffects()
{
foreach (IGameEntity effect in _playedEffects)
{
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;
// Destroy is deferred to the end of the frame.
((GameObject)effect.NativeObject).SetActive(false);
effect.Destroy();
}
private void PruneDeadAttachments()
{
for (int i = _persistentEffects.Count - 1; i >= 0; i--)
{
if (_persistentEffects[i].ParentIsDisposed)
_persistentEffects[i].Dispose();
}
}
internal void ClearPrefabCache()
{
PruneDeadAttachments();
_prefabCacheGeneration++;
_prefabs.Clear();
}
public void Dispose()
{
_disposed = true;
_settings.OnGameSettingsChanged -= OnGameSettingsChanged;
ClearPlayedEffects();
foreach (PersistentEffect effect in _persistentEffects.ToArray())
{
effect.Dispose();
}
ClearPrefabCache();
_original?.Dispose();
}
private sealed class PersistentEffect : IDisposable
{
private readonly OptionalVfxPlayer _player;
private readonly int _effectGroupId;
private readonly IGameEntity _parent;
private IGameEntity _instance;
private bool _disposed;
private readonly bool _allowOriginal;
private readonly uint _portalType;
internal PersistentEffect(OptionalVfxPlayer player, int effectGroupId, IGameEntity parent, bool allowOriginal, uint portalType)
{
_player = player;
_effectGroupId = effectGroupId;
_parent = parent;
_allowOriginal = allowOriginal;
_portalType = portalType;
}
internal bool ParentIsDisposed => _parent.IsNullOrDisposed();
internal GameObject OriginalRoot => IsOriginal(_instance) ? (GameObject)_instance.NativeObject : null;
internal void Refresh(bool reconsiderPrivate = false)
{
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, allowOriginal: _allowOriginal, portalType: _portalType);
if (!_instance.IsNullOrDisposed() && ((GameObject)_instance.NativeObject).GetComponent<OriginalEffectPlayer>() is { } native)
{
native.DestroyOnComplete = false;
native.Loop = true;
native.RepeatInterval = _player._original.GameVariant == "PAL3" && _effectGroupId == 275 ? 9.5f : 0;
}
}
}
else
{
Stop(_instance);
_instance = null;
}
}
public void Dispose()
{
_disposed = true;
_player._persistentEffects.Remove(this);
Stop(_instance);
_instance = null;
}
}
}
}
@@ -17,7 +17,7 @@ namespace Pal3.Game.Effect
public void Init(GameResourceProvider resourceProvider, uint parameter)
{
_effect = resourceProvider.OptionalVfx.AttachPortal(GameEntity, parameter);
_effect = resourceProvider.Effects.AttachPortal(GameEntity, parameter);
}
private void OnDestroy() => Dispose();
@@ -1,88 +0,0 @@
// ------------------------------------------------------------------------
// Copyright (c) 2021-2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Game.Effect
{
using System;
using Data;
using Engine.Core.Abstraction;
using Engine.Core.Implementation;
using Engine.Extensions;
using UnityEngine;
public sealed class RotatingSpriteEffect : TickableGameEntityScript, IDisposable
{
private IGameEntity _root;
private SpriteRenderer _spriteRenderer;
private IMaterial _material;
private float _rotationSpeed;
protected override void OnDisableGameEntity()
{
Dispose();
}
public void Init(GameResourceProvider resourceProvider,
string textureName,
Vector3 scale,
float rotationSpeed)
{
_rotationSpeed = rotationSpeed;
ITexture2D texture = resourceProvider.GetEffectTexture(textureName, out var hasAlphaChannel);
_root = GameEntityFactory.Create($"RotatingSpriteEffect_{textureName}",
GameEntity, worldPositionStays: false);
_spriteRenderer = _root.AddComponent<SpriteRenderer>();
_spriteRenderer.sprite = texture.CreateSprite(0, 0,
texture.Width, texture.Height,
0.5f, 0.5f).NativeObject as Sprite;
if (!hasAlphaChannel)
{
_material = resourceProvider.GetMaterialManager()
.CreateOpaqueSpriteMaterial(texture);
_spriteRenderer.sharedMaterial = _material.NativeObject as Material;
}
Quaternion parentRotation = GameEntity.Transform.Rotation;
_root.Transform.LocalRotation = Quaternion.Euler(parentRotation.x + 90f, 0f, 0f);
_root.Transform.LocalScale = scale;
}
protected override void OnUpdateGameEntity(float deltaTime)
{
if (!_root.IsNullOrDisposed())
{
float rotationDelta = _rotationSpeed * deltaTime;
_root.Transform.LocalRotation *= Quaternion.Euler(0f, 0f, -rotationDelta);
}
}
public void Dispose()
{
if (_material != null)
{
_material.Destroy();
_material = null;
}
if (_spriteRenderer != null)
{
_spriteRenderer.Destroy();
_spriteRenderer = null;
}
if (_root != null)
{
_root.Destroy();
_root = null;
}
}
}
}
@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: 10c2b48514804783bc35a3b045455dd8
timeCreated: 1666333743
@@ -60,7 +60,6 @@ namespace Pal3.Game.Settings
RegisterVisualOption(nameof(ToonCharacterLighting), "角色光照", enabled => ToonCharacterLighting = enabled);
RegisterVisualOption(nameof(ToonNightFireBoost), "增强夜景火光", enabled => ToonNightFireBoost = enabled);
RegisterVisualOption(nameof(BloomEnabled), "泛光", enabled => BloomEnabled = enabled);
RegisterVisualOption(nameof(OptionalVfxEnabled), "可选剧情特效", enabled => OptionalVfxEnabled = enabled);
RegisterVisualOption(nameof(ToonFireShadows), "火光投影", enabled => ToonFireShadows = enabled);
RegisterVisualOption(nameof(ToonEnvironmentContrast), "环境明暗对比", enabled => ToonEnvironmentContrast = enabled);
@@ -185,9 +184,9 @@ namespace Pal3.Game.Settings
int screenRefreshRate = Screen.currentResolution.refreshRate;
#endif
// Only respect the target frame rate if it is higher than the screen refresh rate
if (SettingsStore.TryGet(nameof(TargetFrameRate), out int targetFrameRate) &&
targetFrameRate >= screenRefreshRate)
// Only respect the target frame rate if it is higher than the screen refresh rate
{
TargetFrameRate = targetFrameRate;
}
@@ -260,7 +259,6 @@ namespace Pal3.Game.Settings
|| nightFireBoost;
_sessionUsesToon ??= ToonRendering;
LoadBloomSetting(defaultEnabled: desktop && !_sessionUsesToon.Value);
OptionalVfxEnabled = SettingsStore.TryGet(nameof(OptionalVfxEnabled), out bool optionalVfx) && optionalVfx;
ToonFireShadows = SettingsStore.TryGet(FireShadowsSettingsKey, out bool fireShadows)
? fireShadows : desktop;
@@ -191,13 +191,6 @@ namespace Pal3.Game.Settings
internal set => SetBooleanOption(ref _bloomEnabled, value);
}
private bool _optionalVfxEnabled;
public bool OptionalVfxEnabled
{
get => _optionalVfxEnabled;
internal set => SetBooleanOption(ref _optionalVfxEnabled, value);
}
private bool _toonEnvironmentContrast;
public bool ToonEnvironmentContrast
{
@@ -24,7 +24,6 @@ namespace Pal3.Game.Tests
using Engine.Extensions;
using NUnit.Framework;
using Scene;
using Settings;
using UnityEngine;
[Category("LocalGameData")]
@@ -53,10 +52,7 @@ namespace Pal3.Game.Tests
public readonly GameScene Scene;
public readonly EffectManager Manager;
public readonly OriginalEffectResources Resources;
public readonly Dictionary<int, GameObject> Prefabs;
private readonly IDisposable _vfx;
private readonly GameSettings _settings;
private readonly int _sleepTimeout = Screen.sleepTimeout;
public readonly EffectRuntime Runtime;
public EffectScene()
{
@@ -65,24 +61,19 @@ namespace Pal3.Game.Tests
#else
var fs = OpenFileSystem("PAL3A");
#endif
_settings = new GameSettings(new InMemoryKeyValueStore());
Root.SetActive(false);
Scene = Root.AddComponent<GameScene>();
Type type = typeof(OriginalEffectPlayer).Assembly.GetType("Pal3.Game.Effect.OptionalVfxPlayer");
Runtime = new EffectRuntime(fs, 936);
Resources = Runtime.Original;
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
_vfx = (IDisposable)Activator.CreateInstance(type, flags, null, new object[] { _settings, fs, 936 }, null);
Resources = (OriginalEffectResources)type.GetField("_original", flags).GetValue(_vfx);
Prefabs = (Dictionary<int, GameObject>)type.GetField("_prefabs", flags).GetValue(_vfx);
var scenes = (SceneManager)FormatterServices.GetUninitializedObject(typeof(SceneManager));
typeof(SceneManager).GetField("_currentGameScene", flags).SetValue(scenes, Scene);
typeof(SceneManager).GetField("_currentSceneRoot", flags).SetValue(scenes, new GameEntity(Root));
Manager = (EffectManager)FormatterServices.GetUninitializedObject(typeof(EffectManager));
typeof(EffectManager).GetField("_sceneManager", flags).SetValue(Manager, scenes);
typeof(EffectManager).GetField("_optionalVfx", flags).SetValue(Manager, _vfx);
typeof(EffectManager).GetField("_effects", flags).SetValue(Manager, Runtime);
}
public void EnablePrivateFallback() => _settings.OptionalVfxEnabled = true;
public OriginalEffectPlayer PlayOriginal(int group = 15)
{
// These tests exercise command dispatch and placement, including
@@ -97,10 +88,8 @@ namespace Pal3.Game.Tests
public void Dispose()
{
_vfx.Dispose();
Runtime.Dispose();
UnityEngine.Object.DestroyImmediate(Root);
_settings.Dispose();
Screen.sleepTimeout = _sleepTimeout;
}
}
@@ -147,22 +136,29 @@ namespace Pal3.Game.Tests
}
[Test]
public void MissingActorDoesNotReparentPrivateFallbackToTheScene()
public void UnsupportedGroupsProduceOneDiagnosticWithoutCreatingPartialEffects()
{
using var scene = new EffectScene();
scene.EnablePrivateFallback();
var prefab = new GameObject("Missing actor private fallback");
UnityEngine.TestTools.LogAssert.Expect(LogType.Warning, new System.Text.RegularExpressions.Regex("Effect -2:"));
Assert.That(scene.Runtime.Play(-2, new GameEntity(scene.Root), Vector3.zero), Is.False);
Assert.That(scene.Runtime.Play(-2, new GameEntity(scene.Root), Vector3.zero), Is.False);
Assert.That(scene.Root.transform.childCount, Is.Zero);
}
[Test]
public void SceneCacheInvalidationCancelsAnInFlightPreload()
{
using var runtime = new EffectRuntime(OpenFileSystem("PAL3"), 936);
var preload = runtime.PreloadAsync(15);
try
{
scene.Prefabs[-2] = prefab;
scene.Manager.Execute(new EffectSetPositionCommand(80, 120, -160));
scene.Manager.Execute(new EffectAttachToActorCommand(32767));
scene.Manager.Execute(new EffectPlayCommand(-2));
Assert.That(scene.Root.transform.childCount, Is.Zero);
Assert.That(preload.MoveNext(), Is.True);
runtime.InvalidatePreloads();
Assert.That(preload.MoveNext(), Is.False);
}
finally
{
UnityEngine.Object.DestroyImmediate(prefab);
(preload as IDisposable)?.Dispose();
}
}
+19 -29
View File
@@ -504,7 +504,7 @@ namespace Pal3.Game.Tests
public void EditorReloadKeepsWorkingCopyAndInvalidDataPathLeavesNoBrokenProvider()
{
using var resources = Open();
Type type = TypeCache.GetTypesDerivedFrom<EditorWindow>().FirstOrDefault(t => t.FullName == "Editor.OriginalEffectEditor");
Type type = TypeCache.GetTypesDerivedFrom<EditorWindow>().FirstOrDefault(t => t.FullName == "Editor.EffectEditor");
Assert.That(type, Is.Not.Null);
var window = (EditorWindow)ScriptableObject.CreateInstance(type);
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
@@ -822,7 +822,7 @@ namespace Pal3.Game.Tests
}
[Test]
public void PrivateFallbackUsesActorParentWhileOriginalUsesSceneSnapshot()
public void RuntimeKeepsAttachedEffectsWhenPlayedEffectsAreCleared()
{
string path = Environment.GetEnvironmentVariable("PAL3_TEST_DATA_ROOT") ?? Path.GetFullPath("../Game Data/PAL3");
if (!Directory.Exists(path))
@@ -831,46 +831,36 @@ namespace Pal3.Game.Tests
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);
using var runtime = new Effect.EffectRuntime(fs, 936);
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));
runtime.Original.Definitions.Groups[15] = new EffectGroup();
using var attachment = runtime.Attach(15, new GameEntity(scene));
Assert.That(runtime.Play(15, new GameEntity(scene), new Vector3(10, 0, 0)), Is.True);
var players = scene.GetComponentsInChildren<OriginalEffectPlayer>();
Assert.That(players, Has.Length.EqualTo(2));
Assert.That(players.Single(p => p.Loop).DestroyOnComplete, Is.False);
Assert.That(players.Single(p => !p.Loop).transform.localPosition.x, Is.EqualTo(10));
runtime.ClearPlayedEffects();
players = scene.GetComponentsInChildren<OriginalEffectPlayer>();
Assert.That(players, Has.Length.EqualTo(1));
Assert.That(players[0].Loop, Is.True);
attachment.Dispose();
Assert.That(scene.transform.childCount, Is.Zero);
runtime.Dispose();
runtime.Dispose();
}
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");
Type type = TypeCache.GetTypesDerivedFrom<EditorWindow>().First(t => t.FullName == "Editor.EffectEditor");
var window = (EditorWindow)ScriptableObject.CreateInstance(type);
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
try
@@ -0,0 +1,44 @@
// ------------------------------------------------------------------------
// 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.IO.Compression;
using System.Linq;
using System.Reflection;
using Constants;
using NUnit.Framework;
using UnityEditor;
public sealed class ReleaseArchiveTests
{
[Test]
public void ArchiveUsesTheCurrentVersionDirectoryAndOriginalFileLayout()
{
string directory = Path.Combine(Path.GetTempPath(), "Pal3ReleaseTest-" + Guid.NewGuid().ToString("N"));
string output = Path.Combine(directory, PlayerSettings.bundleVersion);
string playerPath = Path.Combine(output, GameConstants.AppName, "Windows_x64", GameConstants.AppName + ".exe");
try
{
Directory.CreateDirectory(Path.GetDirectoryName(playerPath));
File.WriteAllBytes(playerPath, new byte[] { 1, 2, 3 });
Type pipeline = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetType("Editor.ReleaseBuildPipeline")).First(t => t != null);
MethodInfo zip = pipeline.GetMethod("ZipReleaseFiles", BindingFlags.Static | BindingFlags.NonPublic, null, new[] { typeof(string) }, null);
zip.Invoke(null, new object[] { output });
string archive = Path.Combine(output, "Release", $"{GameConstants.AppName}_v{PlayerSettings.bundleVersion}_Windows_x64.zip");
Assert.That(File.Exists(archive), Is.True);
using var contents = ZipFile.OpenRead(archive);
Assert.That(contents.Entries.Select(e => e.FullName), Is.EqualTo(new[] { GameConstants.AppName + ".exe" }));
}
finally
{
if (Directory.Exists(directory))
Directory.Delete(directory, true);
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8580799c18e841bba1c2cf6e2f92a52e
+4 -2
View File
@@ -71,9 +71,11 @@ Both games default to the original visual style in URP, preserving the original
The visual effects settings provide independent switches for contact shadows, character lighting, enhanced night fire lighting, and fire shadows. Contact shadows and fire shadows default to enabled on desktop devices. Enhanced fire lighting combines warm lights with a cool ambient tone. Fire shadows also work in dark maze scenes. Desktop defaults to four shadowed fires. Set `Settings.ToonFireShadowBudget` to 0–4 in the debug console. The shadow atlas grows with the budget. Bloom has a separate switch and defaults to enabled only for the original style on desktop.
The screenshots above show the previous toon renderer. Optional story VFX are off by default. Install URP-compatible numbered prefabs locally in `Assets/Resources/Prefabs/VFX/PAL3/` or `Assets/Resources/Prefabs/VFX/PAL3A/`, then enable optional story VFX in the visual effects settings. Turning the setting off hides active optional effects immediately. Turning it back on restores persistent effects in the current scene and shows newly triggered story effects.
The screenshots above show the previous toon renderer. Supported story and scene effects in both games use the original data: effect groups, tasks, particles, textures, and models loaded from local CPK archives, rendered with this project's URP shaders and Unity components. Open `PAL3 / PAL3A → Effect Editor` in Unity to select a game, play effects, inspect objects, and edit group tasks and legacy particle curves. Save overrides to `Assets/Resources/Effects/PAL3Overrides.asset` or `PAL3AOverrides.asset` for use in the game. ResourceViewer provides an original effects panel and the commands `Effect.Load <group ID>`, `Effect.Seek <seconds>`, and `Effect.Pause true/false`. Group ID `-1` supports transport points in both games.
Use a fresh checkout for public builds. Unity blocks player builds when it finds local optional VFX prefabs, Hovl Studio assets, RealToon assets, or legacy toon materials. To build for private use, launch your local Unity editor with `PAL3_ALLOW_PRIVATE_ASSETS=1`. The project build menu places these builds in a version folder with the `-Private` suffix.
The current inventory covers all 56 PAL3 and 93 PAL3A story and scene root groups using original data. Transport points reproduce the original disc, two light cones, and colors selected by scene parameters. SPar keyframes, paths, six controller slots, and material blending are implemented independently; raw SPar fields are read-only in the editor. Unsupported types such as battle directors produce diagnostics and will be added alongside their related systems.
All implementation code, shaders, and build resources are included in this repository. The game reads the player's local original game data at runtime; that data is not distributed with this project.
## Controls
- Mouse and keyboard: Left mouse button to click and control character movement (arrow keys can also be used), A/D to control camera rotation, Spacebar to interact with nearby items or NPCs (also used as the jump button when available), M key to toggle the big map, U key or ESC key to open the story selection menu, Tab key to switch characters (in the maze).
+4 -4
View File
@@ -70,11 +70,11 @@
「游戏设置 → 画面与特效设置」提供接触阴影、角色光照、增强夜景火光和火光投影四个独立开关,在卡通画风中即时生效。接触阴影和火光投影在桌面设备默认开启,手持设备可按需开启。夜景火光使用暖色灯光与冷色环境底色。火光投影也适用于暗色迷宫,桌面默认四盏,控制台可通过 `Settings.ToonFireShadowBudget` 设置 0–4 盏,阴影图集随预算扩容。泛光可以独立开关,默认仅桌面原版画风开启。
上方截图来自旧版卡通渲染。两作已支持的剧情与场景特效由原版数据驱动,运行时读取本地 CPK 的特效组、任务、粒子、贴图和模型,使用自有 URP shader 与 Unity 原生渲染组件。Unity 菜单 `PAL3 / PAL3A → Original Effect Editor` 可选择作品、播放、检查对象、修改组任务和旧粒子曲线;覆盖资产分别保存到 `Assets/Resources/Effects/PAL3Overrides.asset` 或 `PAL3AOverrides.asset` 后供游戏读取。ResourceViewer 提供原版特效面板及 `Effect.Load <组ID>`、`Effect.Seek <秒>`、`Effect.Pause true/false` 命令;组 ID `-1` 支持 PAL3/PAL3A 两作传送点。
上方截图来自旧版卡通渲染。两作已支持的剧情与场景特效由原版数据驱动,运行时读取本地 CPK 的特效组、任务、粒子、贴图和模型,使用自有 URP shader 与 Unity 原生渲染组件。Unity 菜单 `PAL3 / PAL3A → Effect Editor` 可选择作品、播放、检查对象、修改组任务和旧粒子曲线;覆盖资产分别保存到 `Assets/Resources/Effects/PAL3Overrides.asset` 或 `PAL3AOverrides.asset` 后供游戏读取。ResourceViewer 提供原版特效面板及 `Effect.Load <组ID>`、`Effect.Seek <秒>`、`Effect.Pause true/false` 命令;组 ID `-1` 支持 PAL3/PAL3A 两作传送点。
迁移期间,原版实现无法完整播放的组回退到本地私有 prefab,再回退到不播放;「可选剧情特效」仅控制这部分备用效果,不影响已接入的原版特效。PAL3A 已接入当前识别的 93 个剧情/场景根组,包含 26 个 SPar 根组;传送点按原版圆盘、双光锥及场景参数配色播放。SPar 关键帧、路径、六槽控制器和材质混合独立实现,原始 SPar 字段在编辑器中只读。战斗导演专用类型仍有待实现。私有编号预制体按作品放在 `Assets/Resources/Prefabs/VFX/PAL3/` 或 `PAL3A/`。编辑器可并排预览,私有 prefab 只用于迁移对比,不作为原版标准。
PAL3 已覆盖当前清单中的 56 个剧情/场景根组,PAL3A 已覆盖 93 个,均由原版数据驱动。传送点按原版圆盘、双光锥及场景参数配色播放。SPar 关键帧、路径、六槽控制器和材质混合独立实现,原始 SPar 字段在编辑器中只读。尚未实现的战斗导演等类型会给出诊断,留待对应系统开发时补齐。
公开构建请使用未导入本地付费素材的全新检出。若工程中有可选特效预制体、Hovl Studio、RealToon 或旧版卡通材质,Unity 会阻止构建。仅供个人使用的构建可通过环境变量 `PAL3_ALLOW_PRIVATE_ASSETS=1` 启动本地 Unity 来显式启用。工程打包菜单会将这类构建输出到带 `-Private` 后缀的版本目录。
实现所需的代码、Shader 和构建资源均随本仓库提供。运行时读取玩家本地的原版游戏数据;原版数据不随项目分发。
## 按键以及操作
- 鼠标键盘:鼠标左键点击操作人物行走方向(键盘方向键也可以),AD控制镜头旋转,空格与周边附近的物品或者NPC交互(也是跳跃键),M键打开大地图,U键或ESC键打开剧情选择菜单,Tab键切换角色(迷宫中)。
@@ -92,7 +92,7 @@ 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 由人工整理并验证。
工具使用 SDK 自带的 `dotnet format`、`.editorconfig` 和固定版本的 StyleCop 布局规则,检查空格、缩进、函数/成员间空行及多条语句分行。默认只应用改动行及删除边界上的格式修正,保留其他行的既有格式;显式路径或 `--all` 可检查整个文件。工具分别检查 PAL3/PAL3A 条件分支,不需要 Unity 或游戏数据;StyleCop 仅用于开发工具,不进入 Unity 工程。PR 的 `Code style` 工作流执行相同检查。格式检查通过后仍需运行相关 Unity 测试;ShaderLab/HLSL 由人工整理并验证。
因为项目还处于早期实现过程中,很多系统还没有实现,暂时不接受比较大的Pull request,特别是feature类型,如果您有好的想法,意见或者发现了Bug请欢迎提交issue或者加入交流群与我讨论。
另外您还可以参考这个项目解析视频:https://www.bilibili.com/video/BV1Pr4y167sF
+79 -5
View File
@@ -7,8 +7,10 @@
"""Format owned C# changes with Roslyn and targeted StyleCop layout rules."""
import argparse
import difflib
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import xml.etree.ElementTree as ET
@@ -24,6 +26,51 @@ def git_files(*args):
return {os.fsdecode(name) for name in result.split(b"\0") if name}
def select_formatting(baseline, original, formatted):
"""Keep formatter edits touching changed lines or a deletion boundary."""
if baseline is None:
return formatted
# Existing files may predate the current CRLF policy. Keep their line-ending
# convention instead of converting the whole file or introducing mixed EOLs.
newline = b"\r\n" if original.count(b"\r\n") > original.count(b"\n") / 2 else b"\n"
formatted = formatted.replace(b"\r\n", b"\n").replace(b"\n", newline)
before = original.splitlines(keepends=True)
after = formatted.splitlines(keepends=True)
content = lambda lines: [line.rstrip(b"\r\n") for line in lines]
old_source = baseline.splitlines(keepends=True)
old_lines = content(old_source)
current_lines = content(before)
dirty = set()
boundaries = set()
for tag, old_start, _, start, end in difflib.SequenceMatcher(
None, old_lines, current_lines, autojunk=False).get_opcodes():
if tag == "equal":
dirty.update(index for index in range(start, end)
if before[index].endswith(b"\n") !=
old_source[old_start + index - start].endswith(b"\n"))
else:
dirty.update(range(start, end))
if start == end:
boundaries.add(start)
result = []
# Match surviving lines independently of spacing so an inserted member gap
# does not pull an adjacent, inherited indentation fix into the same edit.
tokens = lambda lines: [b"".join(line.split()) for line in lines]
for tag, start, end, target_start, target_end in difflib.SequenceMatcher(
None, tokens(before), tokens(after), autojunk=False).get_opcodes():
if tag == "equal":
result.extend(after[target_start + index - start] if index in dirty else before[index]
for index in range(start, end))
continue
touches_change = any(index in dirty for index in range(start, end))
touches_change |= any(start <= boundary < end or start == end == boundary
for boundary in boundaries)
if start == end:
touches_change |= start in dirty or start - 1 in dirty
result.extend(after[target_start:target_end] if touches_change else before[start:end])
return b"".join(result)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true", help="Fail instead of modifying files")
@@ -31,7 +78,7 @@ def main():
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")
parser.add_argument("paths", nargs="*", help="Format whole files at these repo-relative paths")
args = parser.parse_args()
if args.paths and (args.base or args.all):
parser.error("Explicit paths cannot be combined with --base or --all")
@@ -55,6 +102,14 @@ def main():
print("No owned C# changes to format.")
return 0
originals = {name: (ROOT / name).read_bytes() for name in files}
baselines = {}
if not args.all and not args.paths:
for name in files:
result = subprocess.run(["git", "-C", str(ROOT), "show", f"{args.base or 'HEAD'}:{name}"],
capture_output=True)
baselines[name] = result.stdout if result.returncode == 0 else None
# 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.
@@ -63,6 +118,14 @@ def main():
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:
# Format copies so --check is read-only and failures cannot leave partial edits.
source_root = Path(temporary) / "sources"
source_root.mkdir()
shutil.copy2(ROOT / ".editorconfig", source_root / ".editorconfig")
for name, source in originals.items():
path = source_root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(source)
project = ET.Element("Project", Sdk="Microsoft.NET.Sdk")
properties = ET.SubElement(project, "PropertyGroup")
for name, value in {
@@ -78,7 +141,7 @@ def main():
# 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))
ET.SubElement(items, "Compile", Include=str(source_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)
@@ -88,11 +151,22 @@ def main():
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 failed:
return 1
changed = False
for name, original in originals.items():
formatted = (source_root / name).read_bytes()
selected = select_formatting(baselines.get(name), original, formatted)
if selected == original:
continue
changed = True
if args.check:
print(f"Formatting required: {name}")
else:
(ROOT / name).write_bytes(selected)
return 1 if args.check and changed else 0
if __name__ == "__main__":
+32 -4
View File
@@ -4,11 +4,12 @@
# See LICENSE file in the project root for license information.
# ------------------------------------------------------------------------
"""Exercise the actual formatter with missing member gaps in both variants."""
"""Exercise layout fixes, change boundaries and read-only checks with Roslyn."""
import os
from pathlib import Path
import shutil
import runpy
import subprocess
import sys
import tempfile
@@ -26,6 +27,16 @@ def run(command, cwd, success=True):
def main():
select = runpy.run_path(str(ROOT / "tools/format-csharp.py"))["select_formatting"]
legacy = b"int A;\r\n\r\nint B;\r\n"
changed = legacy.replace(b"int B", b"int B")
formatted = b"int A;\r\n\r\nint B;\r\n"
assert select(legacy, changed, formatted) == legacy
assert select(legacy, legacy, formatted) == legacy
assert select(None, changed, formatted) == formatted
assert select(legacy.replace(b"\r\n", b"\n"), changed.replace(b"\r\n", b"\n"), formatted) == legacy.replace(b"\r\n", b"\n")
assert select(legacy, legacy[:-2], formatted) == legacy, "Newly removed final newline was missed"
assert select(legacy, legacy.replace(b";\r\n\r\n", b";\r\n"), formatted) == legacy
workspace = ROOT.parent / "workspace"
temporary_root = workspace / "Tooling" / "CodeStyle" if workspace.is_dir() else None
if temporary_root is not None:
@@ -54,7 +65,7 @@ def main():
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 "Formatting required:" in output, output
assert source.read_bytes() == before, "Check mode modified the source"
run(command, fixture)
fixed = source.read_bytes()
@@ -65,9 +76,26 @@ def main():
# 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 "Formatting required:" in output, output
run(command, fixture)
# Keep inherited formatting outside the edit, even in the same file.
legacy = fixture / "Assets/Scripts/Legacy.cs"
legacy.write_bytes(b"class Legacy\r\n{\r\n int Untouched;\r\n\r\n int Changed;\r\n}\r\n")
run(["git", "add", "."], fixture)
run(["git", "-c", "user.name=Format fixture", "-c", "user.email=fixture@localhost",
"-c", "commit.gpgsign=false", "commit", "--quiet", "-m", "Legacy baseline"], fixture)
legacy.write_bytes(legacy.read_bytes().replace(b"int Changed", b"int Changed"))
before = legacy.read_bytes()
run([*command, "--check"], fixture, success=False)
assert legacy.read_bytes() == before, "Changed-line check modified the source"
run(command, fixture)
assert b"int Untouched;" in legacy.read_bytes(), "Inherited formatting was changed"
assert b"int Changed;" in legacy.read_bytes(), "Modified line was not formatted"
run([*command, "--check"], fixture)
# Explicit paths still provide an intentional whole-file format/audit.
run([*command, "--check", str(legacy.relative_to(fixture))], fixture, success=False)
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.")
print("Passed: both variants fix member gaps, checks are read-only, --base checks PAL3A, inherited formatting and plugins stay untouched, explicit paths audit whole files.")
if __name__ == "__main__":