Compare commits

...
31 Commits
Author SHA1 Message Date
Jackie Liu 97272bbf0f v0.28 2022-10-10 03:38:48 -07:00
Jackie Liu 4a68472423 Remember last scene state for camera 2022-10-10 03:35:25 -07:00
Jackie Liu 51a5163fc1 Bug fix 2022-10-09 15:12:22 -07:00
Jackie Liu fd3e89c23b Fixed a racing condition when PlayMusicCommand is queued at start of the scene 2022-10-09 14:09:32 -07:00
Jackie Liu 170a78a0bf Use monitor's refresh rate as target frame rate in GameResourceViewer 2022-10-09 12:38:49 -07:00
Jackie Liu 5b69fd1c7f Fixed a bug where player actor might be accidentally activated 2022-10-08 22:31:00 -07:00
Jackie Liu be861dc536 v0.27 2022-10-08 07:07:19 -07:00
Jackie Liu 6dfff9ff57 Draw order issue temp fix 2022-10-08 06:13:58 -07:00
Jiaqi Liu cbe4f82489 Minor refactoring 2022-10-07 19:42:10 -07:00
Jackie Liu 01a41fa834 Proper reloading logic when executing commands from save file 2022-10-07 08:52:56 -07:00
Jackie Liu cb821a0901 Update Pal3AMv3TextureTilingIssue.cs 2022-10-07 04:42:36 -07:00
Jackie Liu 4b36a38b21 Fix render queue and cutoff for Mv3ModelRenderer 2022-10-06 22:10:05 -07:00
Jackie Liu 17ebee5b28 Use alpha blending based on BlendFlag setting 2022-10-06 21:44:16 -07:00
Jackie Liu f0e1b2db98 Properly implement HuaYing's pet following behavior 2022-10-06 18:28:57 -07:00
Jackie Liu 23673aae2a SaveManager WIP 2022-10-06 08:21:07 -07:00
Jackie Liu ca3b28a089 Use monitor's refresh rate as target fps, use Vulkan as default graphics API for Linux build
Use monitor's refresh rate as target fps, use Vulkan as default graphics API for Linux build. Also disable vSync for desktop clients.
2022-10-05 18:00:47 -07:00
Jackie Liu 45b5971ede Fixed a bug where camera is not correctly set for PAL3A start scene 2022-10-05 09:18:22 -07:00
Jiaqi Liu ad97b6a817 Minor fixes 2022-10-05 08:43:28 -07:00
Jackie Liu c92716f3e5 Minor fixes 2022-10-05 03:21:47 -07:00
Jackie Liu 7538ebe506 v0.26 2022-10-05 03:16:00 -07:00
Jackie Liu 1c5623ad7d Introduce UITheme 2022-10-05 03:02:59 -07:00
Jackie Liu eda6c9a1bf Fixed an issue where actor might stuck during collision 2022-10-05 02:47:32 -07:00
Jackie Liu fc4aec4e4d AudioManager bug fixes and refatcotring 2022-10-05 02:05:03 -07:00
Jackie Liu 84355c168f Code refactoring and bug fixes 2022-10-05 00:43:24 -07:00
Jackie Liu 809e55de82 Persist LongKui's current mode in save file 2022-10-04 04:53:24 -07:00
Jackie Liu 7d606ab1f6 Persist actor and object activation state in save file + PlaySfx command proper impl
Persist actor and object activation state in save file + PlaySfx command proper impl
2022-10-04 04:30:15 -07:00
Jackie Liu 14b006dc87 Fixed a bug in DialogueManager
Fixed a bug in DialogueManager where waiter is not properly handled when multiple commands fired at once due to invalid scripts
2022-10-04 01:52:34 -07:00
Jackie Liu 840de611dd UX tweaks and improvements 2022-10-04 01:16:52 -07:00
Jackie Liu 67209cb26e UI tweaks 2022-10-03 23:46:45 -07:00
Jackie Liu caf8c9cf3c Fixed a dialogue rendering issue caused by invalid script 2022-10-03 18:44:26 -07:00
Jiaqi Liu 7746523600 Set NSPrefersDisplaySafeAreaCompatibilityMode for mac build 2022-10-03 03:14:12 -07:00
77 changed files with 1192 additions and 624 deletions

No files matched your search

@@ -100,9 +100,9 @@ MonoBehaviour:
m_Transition: 1
m_Colors:
m_NormalColor: {r: 0.15686275, g: 0.15686275, b: 0.15686275, a: 0.78431374}
m_HighlightedColor: {r: 0.23529412, g: 0.23529412, b: 0.23529412, a: 0.78431374}
m_PressedColor: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 0.78431374}
m_SelectedColor: {r: 0.23529412, g: 0.23529412, b: 0.23529412, a: 0.9019608}
m_HighlightedColor: {r: 0.11764706, g: 0.29411766, b: 0.54901963, a: 0.78431374}
m_PressedColor: {r: 0.078431375, g: 0.19607843, b: 0.39215687, a: 0.78431374}
m_SelectedColor: {r: 0.11764706, g: 0.29411766, b: 0.54901963, a: 0.78431374}
m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608}
m_ColorMultiplier: 1
m_FadeDuration: 0.1
@@ -11,6 +11,18 @@ PrefabInstance:
propertyPath: m_Name
value: IngameDebugConsole
objectReference: {fileID: 0}
- target: {fileID: 11414302, guid: 67117722a812a2e46ab8cb8eafbf5f5e, type: 3}
propertyPath: m_Navigation.m_Mode
value: 0
objectReference: {fileID: 0}
- target: {fileID: 11420596, guid: 67117722a812a2e46ab8cb8eafbf5f5e, type: 3}
propertyPath: m_Navigation.m_Mode
value: 0
objectReference: {fileID: 0}
- target: {fileID: 11437802, guid: 67117722a812a2e46ab8cb8eafbf5f5e, type: 3}
propertyPath: m_Navigation.m_Mode
value: 0
objectReference: {fileID: 0}
- target: {fileID: 11452418, guid: 67117722a812a2e46ab8cb8eafbf5f5e, type: 3}
propertyPath: toggleBinding.m_Id
value: 06175ea3-1b47-4b6e-bcd7-4d191ce555d1
@@ -19,6 +31,18 @@ PrefabInstance:
propertyPath: toggleBinding.m_SingletonActionBindings.Array.data[0].m_Id
value: badbacc7-7d97-42d1-ac38-980883100f6e
objectReference: {fileID: 0}
- target: {fileID: 11466918, guid: 67117722a812a2e46ab8cb8eafbf5f5e, type: 3}
propertyPath: m_Navigation.m_Mode
value: 0
objectReference: {fileID: 0}
- target: {fileID: 11472314, guid: 67117722a812a2e46ab8cb8eafbf5f5e, type: 3}
propertyPath: m_Navigation.m_Mode
value: 0
objectReference: {fileID: 0}
- target: {fileID: 11477250, guid: 67117722a812a2e46ab8cb8eafbf5f5e, type: 3}
propertyPath: m_Navigation.m_Mode
value: 0
objectReference: {fileID: 0}
- target: {fileID: 22426080, guid: 67117722a812a2e46ab8cb8eafbf5f5e, type: 3}
propertyPath: m_AnchorMax.x
value: 0
@@ -235,6 +259,22 @@ PrefabInstance:
propertyPath: m_AnchoredPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 114000010993257018, guid: 67117722a812a2e46ab8cb8eafbf5f5e, type: 3}
propertyPath: m_Navigation.m_Mode
value: 0
objectReference: {fileID: 0}
- target: {fileID: 114466839828933532, guid: 67117722a812a2e46ab8cb8eafbf5f5e, type: 3}
propertyPath: m_Navigation.m_Mode
value: 0
objectReference: {fileID: 0}
- target: {fileID: 114664465529608634, guid: 67117722a812a2e46ab8cb8eafbf5f5e, type: 3}
propertyPath: m_Navigation.m_Mode
value: 0
objectReference: {fileID: 0}
- target: {fileID: 114786672304321734, guid: 67117722a812a2e46ab8cb8eafbf5f5e, type: 3}
propertyPath: m_Navigation.m_Mode
value: 0
objectReference: {fileID: 0}
- target: {fileID: 224619367409363176, guid: 67117722a812a2e46ab8cb8eafbf5f5e, type: 3}
propertyPath: m_AnchorMax.y
value: 0
@@ -286,36 +326,3 @@ PrefabInstance:
m_RemovedComponents:
- {fileID: 11492840, guid: 67117722a812a2e46ab8cb8eafbf5f5e, type: 3}
m_SourcePrefab: {fileID: 100100000, guid: 67117722a812a2e46ab8cb8eafbf5f5e, type: 3}
--- !u!1 &2755888773260686779 stripped
GameObject:
m_CorrespondingSourceObject: {fileID: 109254, guid: 67117722a812a2e46ab8cb8eafbf5f5e, type: 3}
m_PrefabInstance: {fileID: 2755888773260713853}
m_PrefabAsset: {fileID: 0}
--- !u!114 &2755888771526933940
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2755888773260686779}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 01614664b831546d2ae94a42149d80ac, type: 3}
m_Name:
m_EditorClassIdentifier:
m_MoveRepeatDelay: 0.5
m_MoveRepeatRate: 0.1
m_XRTrackingOrigin: {fileID: 0}
m_ActionsAsset: {fileID: -944628639613478452, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_PointAction: {fileID: -1654692200621890270, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_MoveAction: {fileID: -8784545083839296357, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_SubmitAction: {fileID: 392368643174621059, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_CancelAction: {fileID: 7727032971491509709, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_LeftClickAction: {fileID: 3001919216989983466, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_MiddleClickAction: {fileID: -2185481485913320682, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_RightClickAction: {fileID: -4090225696740746782, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_ScrollWheelAction: {fileID: 6240969308177333660, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_TrackedDevicePositionAction: {fileID: 6564999863303420839, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_TrackedDeviceOrientationAction: {fileID: 7970375526676320489, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_DeselectOnBackgroundClick: 0
m_PointerBehavior: 0
+2 -100
View File
@@ -166,7 +166,6 @@ GameObject:
- component: {fileID: 311849592}
- component: {fileID: 311849591}
- component: {fileID: 311849595}
- component: {fileID: 311849594}
- component: {fileID: 7927220425085558669}
m_Layer: 0
m_Name: GameCamera
@@ -242,102 +241,6 @@ AudioListener:
m_GameObject: {fileID: 311849590}
m_Enabled: 1
--- !u!82 &311849595
AudioSource:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 311849590}
m_Enabled: 1
serializedVersion: 4
OutputAudioMixerGroup: {fileID: 0}
m_audioClip: {fileID: 0}
m_PlayOnAwake: 1
m_Volume: 1
m_Pitch: 1
Loop: 0
Mute: 0
Spatialize: 0
SpatializePostEffects: 0
Priority: 128
DopplerLevel: 1
MinDistance: 1
MaxDistance: 500
Pan2D: 0
rolloffMode: 0
BypassEffects: 0
BypassListenerEffects: 0
BypassReverbZones: 0
rolloffCustomCurve:
serializedVersion: 2
m_Curve:
- serializedVersion: 3
time: 0
value: 1
inSlope: 0
outSlope: 0
tangentMode: 0
weightedMode: 0
inWeight: 0.33333334
outWeight: 0.33333334
- serializedVersion: 3
time: 1
value: 0
inSlope: 0
outSlope: 0
tangentMode: 0
weightedMode: 0
inWeight: 0.33333334
outWeight: 0.33333334
m_PreInfinity: 2
m_PostInfinity: 2
m_RotationOrder: 4
panLevelCustomCurve:
serializedVersion: 2
m_Curve:
- serializedVersion: 3
time: 0
value: 0
inSlope: 0
outSlope: 0
tangentMode: 0
weightedMode: 0
inWeight: 0.33333334
outWeight: 0.33333334
m_PreInfinity: 2
m_PostInfinity: 2
m_RotationOrder: 4
spreadCustomCurve:
serializedVersion: 2
m_Curve:
- serializedVersion: 3
time: 0
value: 0
inSlope: 0
outSlope: 0
tangentMode: 0
weightedMode: 0
inWeight: 0.33333334
outWeight: 0.33333334
m_PreInfinity: 2
m_PostInfinity: 2
m_RotationOrder: 4
reverbZoneMixCustomCurve:
serializedVersion: 2
m_Curve:
- serializedVersion: 3
time: 0
value: 1
inSlope: 0
outSlope: 0
tangentMode: 0
weightedMode: 0
inWeight: 0.33333334
outWeight: 0.33333334
m_PreInfinity: 2
m_PostInfinity: 2
m_RotationOrder: 4
--- !u!82 &311849594
AudioSource:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
@@ -951,7 +854,7 @@ MonoBehaviour:
m_Name:
m_EditorClassIdentifier:
m_Material: {fileID: 0}
m_Color: {r: 0, g: 0, b: 0, a: 1}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_RaycastTarget: 1
m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0}
m_Maskable: 1
@@ -1164,7 +1067,7 @@ MonoBehaviour:
m_Name:
m_EditorClassIdentifier:
m_Material: {fileID: 0}
m_Color: {r: 0, g: 0, b: 0, a: 1}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_RaycastTarget: 1
m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0}
m_Maskable: 1
@@ -4132,7 +4035,6 @@ MonoBehaviour:
mainCamera: {fileID: 311849592}
curtainImage: {fileID: 147356289}
musicSource: {fileID: 311849595}
sfxSource: {fileID: 311849594}
videoPlayerCanvas: {fileID: 5102776189801015787}
videoPlayer: {fileID: 4844794614659113022}
noteCanvasGroup: {fileID: 6941303344842138483}
@@ -100,9 +100,9 @@ MonoBehaviour:
m_Transition: 1
m_Colors:
m_NormalColor: {r: 0, g: 0, b: 0, a: 0.7058824}
m_HighlightedColor: {r: 0.15686275, g: 0.15686275, b: 0.15686275, a: 0.6666667}
m_PressedColor: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 0.6666667}
m_SelectedColor: {r: 0.23529412, g: 0.23529412, b: 0.23529412, a: 0.9019608}
m_HighlightedColor: {r: 0.11764706, g: 0.29411766, b: 0.54901963, a: 0.6666667}
m_PressedColor: {r: 0.07450981, g: 0.19607843, b: 0.39215687, a: 0.6666667}
m_SelectedColor: {r: 0.11764706, g: 0.29411766, b: 0.54901963, a: 0.9019608}
m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608}
m_ColorMultiplier: 1
m_FadeDuration: 0.1
@@ -100,9 +100,9 @@ MonoBehaviour:
m_Transition: 1
m_Colors:
m_NormalColor: {r: 0.15686275, g: 0.15686275, b: 0.15686275, a: 0.78431374}
m_HighlightedColor: {r: 0.23529412, g: 0.23529412, b: 0.23529412, a: 0.78431374}
m_PressedColor: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 0.78431374}
m_SelectedColor: {r: 0.23529412, g: 0.23529412, b: 0.23529412, a: 0.9019608}
m_HighlightedColor: {r: 0.11764706, g: 0.29411766, b: 0.54901963, a: 0.78431374}
m_PressedColor: {r: 0.07450981, g: 0.19607843, b: 0.39215687, a: 0.78431374}
m_SelectedColor: {r: 0.11764706, g: 0.29411766, b: 0.54901963, a: 0.9019608}
m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608}
m_ColorMultiplier: 1
m_FadeDuration: 0.1
@@ -0,0 +1,49 @@
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
#if UNITY_EDITOR_OSX
namespace Build.Editor
{
using System.IO;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.iOS.Xcode;
using UnityEngine;
/// <summary>
/// Set NSPrefersDisplaySafeAreaCompatibilityMode in XCode project settings (Info.plist)
/// </summary>
public static class SetDisplaySafeAreaCompatibilityModeProcessor
{
[PostProcessBuild]
public static void ChangeXcodePlist(BuildTarget buildTarget, string pathToBuiltProject)
{
if (buildTarget != BuildTarget.StandaloneOSX) return;
// Get plist
#if PAL3
string plistPath = pathToBuiltProject + "/PAL3/Info.plist";
#elif PAL3A
string plistPath = pathToBuiltProject + "/PAL3A/Info.plist";
#endif
PlistDocument plist = new PlistDocument();
plist.ReadFromString(File.ReadAllText(plistPath));
// Get root
PlistElementDict rootDict = plist.root;
rootDict.SetBoolean("NSPrefersDisplaySafeAreaCompatibilityMode", false);
// Write to file
File.WriteAllText(plistPath, plist.WriteToString());
Debug.Log("NSPrefersDisplaySafeAreaCompatibilityMode set to NO.");
}
}
}
#endif
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: acf008c658174728b71ceb4a88b76bc6
timeCreated: 1664790861
@@ -32,7 +32,7 @@ namespace Core.DataLoader
DxtHeader header = DxtHeader.ReadHeader(reader);
var format = header.DxtPixelFormat.Format;
hasAlphaChannel = format == "DXT1";
hasAlphaChannel = true;
_width = header.Width;
_height = header.Height;
@@ -81,7 +81,7 @@ namespace Core.DataLoader
public Texture2D ToTexture2D()
{
if (_rawData == null) return null;
Texture2D texture = new Texture2D(_width, _height, _format, false);
Texture2D texture = new Texture2D(_width, _height, _format, mipChain: false);
texture.LoadRawTextureData(_rawData);
texture.Apply();
return texture;
@@ -74,7 +74,7 @@ namespace Core.DataLoader
public Texture2D ToTexture2D()
{
if (_pixels == null) return null;
var texture = new Texture2D(_width, _height);
var texture = new Texture2D(_width, _height, TextureFormat.RGBA32, mipChain: false);
texture.SetPixels32(_pixels);
texture.Apply();
return texture;
@@ -111,14 +111,17 @@ namespace Core.DataReader.Bmp
public Texture2D ToTexture2D()
{
var tex = new Texture2D(info.absWidth, info.absHeight);
var texture = new Texture2D(info.absWidth,
info.absHeight,
TextureFormat.RGBA32,
mipChain: false);
if (info.height < 0)
FlipImage();
tex.SetPixels32(imageData);
tex.Apply();
return tex;
texture.SetPixels32(imageData);
texture.Apply();
return texture;
}
// flip image if height is negative
@@ -42,7 +42,7 @@ namespace Core.DataReader.Pol
nodeInfos[i] = new PolGeometryNode
{
Name = reader.ReadString(32, codepage),
Position = reader.ReadVector3(),
Position = GameBoxInterpreter.ToUnityPosition(reader.ReadVector3()),
Radius = reader.ReadSingle(),
Offset = reader.ReadInt32()
};
@@ -5,6 +5,7 @@
namespace Core.DataReader.Scn
{
using System;
using GameBox;
using Newtonsoft.Json;
using UnityEngine;
@@ -139,6 +140,34 @@ namespace Core.DataReader.Scn
public int LightMap; // 0日景灯光, 1夜景灯光, -1不知道是什么意思(比如M01)
public uint SkyBox;
public uint[] Reserved; // 6 DWORDs
/// <summary>
/// Check if two scene share the same model.
/// </summary>
/// <param name="sceneInfo">ScnSceneInfo</param>
/// <returns>True if two scene share the same model</returns>
public bool ModelEquals(ScnSceneInfo sceneInfo)
{
#if PAL3
return string.Equals(CityName, sceneInfo.CityName, StringComparison.OrdinalIgnoreCase) &&
string.Equals(Model, sceneInfo.Model, StringComparison.OrdinalIgnoreCase);
#elif PAL3A
var modelAName = Model;
if (modelAName.EndsWith("y", StringComparison.OrdinalIgnoreCase))
{
modelAName = modelAName[..^1];
}
var modelBName = sceneInfo.Model;
if (modelBName.EndsWith("y", StringComparison.OrdinalIgnoreCase))
{
modelBName = modelBName[..^1];
}
return string.Equals(CityName, sceneInfo.CityName, StringComparison.OrdinalIgnoreCase) &&
string.Equals(modelAName, modelBName, StringComparison.OrdinalIgnoreCase);
#endif
}
}
[System.Serializable]
@@ -58,8 +58,8 @@ namespace Core.GameBox
public static class GameBoxVertexType
{
public const int MaxUvSet = 4;
public const int Null = 0;
public const int MaxUvSet = 4;
public const int XYZ = (1 << 0);
public const int Normal = (1 << 1);
public const int Diffuse = (1 << 2);
@@ -74,7 +74,7 @@ namespace Core.Utils
RuntimePlatform.IPhonePlayer => iOSSupportedVideoFormats,
RuntimePlatform.Android => AndroidSupportedVideoFormats,
_ => new () {".mp4" }
_ => new HashSet<string> {".mp4" }
};
}
}
+1 -1
View File
@@ -96,7 +96,7 @@ namespace Editor
{
allDefines.Add(symbolToAdd);
}
allDefines.Sort();
PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup,
string.Join(";", allDefines.ToArray()));
}
+1
View File
@@ -61,6 +61,7 @@ namespace Pal3.Actor
protected void ChangeName(string name)
{
if (_actorName == name) return;
_actorName = name;
InitActorConfig(name);
}
+2 -2
View File
@@ -46,7 +46,7 @@ namespace Pal3.Actor
switch (actor.Info.Id)
{
case (byte)PlayerActorId.HuaYing:
actorGameObject.AddComponent<HuaYingController>().Init(actorController, actionController);
actorGameObject.AddComponent<HuaYingController>().Init(actor, actorController, actionController);
break;
case (byte)PlayerActorId.LongKui:
actorGameObject.AddComponent<LongKuiController>().Init(actor, actionController);
@@ -56,7 +56,7 @@ namespace Pal3.Actor
switch (actor.Info.Id)
{
case (byte)PlayerActorId.TaoZi:
actorGameObject.AddComponent<FlyingActorController>().Init(actionController);
actorGameObject.AddComponent<FlyingActorController>().Init(actor, actionController);
break;
}
#endif
@@ -53,7 +53,7 @@ namespace Pal3.Actor
private WaitUntilCanceled _movementWaiter;
private bool _isDuringCollision;
private Vector3 _lastKnownValidPositionDuringCollision;
private Vector3 _lastKnownValidPositionWhenCollisionEnter;
private Func<int, byte[], HashSet<Vector2Int>> _getAllActiveActorBlockingTilePositions;
@@ -160,14 +160,14 @@ namespace Pal3.Actor
Vector2Int tilePosition = _tilemap.GetTilePosition(currentPosition, _currentLayerIndex);
if (!_tilemap.IsTilePositionInsideTileMap(tilePosition, _currentLayerIndex))
{
transform.position = _lastKnownValidPositionDuringCollision;
transform.position = _lastKnownValidPositionWhenCollisionEnter;
}
else
{
NavTile currentTile = _tilemap.GetTile(tilePosition, _currentLayerIndex);
if (!currentTile.IsWalkable())
{
transform.position = _lastKnownValidPositionDuringCollision;
transform.position = _lastKnownValidPositionWhenCollisionEnter;
}
else
{
@@ -183,7 +183,24 @@ namespace Pal3.Actor
private void OnCollisionEnter(Collision _)
{
_isDuringCollision = true;
_lastKnownValidPositionDuringCollision = transform.position;
Vector3 currentActorPosition = transform.position;
Vector2Int currentTilePosition = _tilemap.GetTilePosition(currentActorPosition, _currentLayerIndex);
if (_tilemap.IsTilePositionInsideTileMap(currentTilePosition, _currentLayerIndex) &&
_tilemap.GetTile(currentActorPosition, _currentLayerIndex).IsWalkable())
{
_lastKnownValidPositionWhenCollisionEnter = currentActorPosition;
}
else
{
_lastKnownValidPositionWhenCollisionEnter =
_tilemap.TryGetAdjacentWalkableTile(currentTilePosition,
_currentLayerIndex,
out Vector2Int nearestWalkableTilePosition)
? _tilemap.GetWorldPosition(nearestWalkableTilePosition, _currentLayerIndex)
: currentActorPosition; // Highly unlikely to happen, but this is the best effort
}
}
private void OnCollisionExit(Collision _)
@@ -387,6 +404,7 @@ namespace Pal3.Actor
private void ReachingToEndOfPath()
{
_movementWaiter?.CancelWait();
switch (_currentPath.EndOfPathAction)
{
case EndOfPathActionType.DisposeSelf:
@@ -522,7 +540,7 @@ namespace Pal3.Actor
}
}
transform.position = _tilemap.GetWorldPosition(tilePosition, _currentLayerIndex);
transform.position = _tilemap.GetWorldPosition(tilePosition, _currentLayerIndex);
}
public void Execute(ActorPathToCommand command)
@@ -10,7 +10,6 @@ namespace Pal3.Actor
using Command.InternalCommands;
using Command.SceCommands;
using Core.GameBox;
using MetaData;
using Player;
using Script.Waiter;
using UnityEngine;
@@ -19,11 +18,14 @@ namespace Pal3.Actor
ICommandExecutor<FlyingActorFlyToCommand>
{
private const float FLY_SPEED = 144f / GameBoxInterpreter.GameBoxUnitToUnityUnit;
private const float FLYING_MOVEMENT_MODE_SWITCH_DISTANCE = 5f;
private Actor _actor;
private ActorActionController _actionController;
public void Init(ActorActionController actionController)
public void Init(Actor actor, ActorActionController actionController)
{
_actor = actor;
_actionController = actionController;
}
@@ -44,6 +46,7 @@ namespace Pal3.Actor
if (Vector3.Distance(transform.position, PlayerActorNpcInfo.InitPosition) < float.Epsilon)
{
transform.position = targetPosition;
_actionController.PerformAction(_actor.GetIdleAction());
return;
}
@@ -53,7 +56,10 @@ namespace Pal3.Actor
var distance = (targetPosition - transform.position).magnitude;
var duration = distance / FLY_SPEED;
_actionController.PerformAction(ActorActionType.Run);
_actionController.PerformAction(distance < FLYING_MOVEMENT_MODE_SWITCH_DISTANCE
? _actor.GetMovementAction(0)
: _actor.GetMovementAction(1));
StartCoroutine(Fly(targetPosition, duration, waiter));
}
@@ -62,9 +68,8 @@ namespace Pal3.Actor
Vector3 oldPosition = transform.position;
// Facing towards target position, ignoring y
transform.forward = (new Vector3(targetPosition.x, 0f, targetPosition.z)
- new Vector3(oldPosition.x, 0f, oldPosition.z)).normalized;
transform.LookAt(new Vector3(targetPosition.x, oldPosition.y, targetPosition.z));
var timePast = 0f;
while (timePast < duration)
{
@@ -78,6 +83,7 @@ namespace Pal3.Actor
}
transform.position = targetPosition;
_actionController.PerformAction(_actor.GetIdleAction());
waiter?.CancelWait();
}
}
+38 -8
View File
@@ -19,15 +19,19 @@ namespace Pal3.Actor
ICommandExecutor<HuaYingSwitchBehaviourModeCommand>
{
private const float FLY_SPEED = 144f / GameBoxInterpreter.GameBoxUnitToUnityUnit;
private const float ROTATION_SPEED = 10f;
private const float ROTATION_SYNCING_DISTANCE = 2f;
private const float FOLLOW_TARGET_MIN_DISTANCE = 1f;
private const float FOLLOW_TARGET_MAX_DISTANCE = 6f;
private const float FOLLOW_TARGET_X_OFFSET = -0.8f;
private const float FOLLOW_TARGET_Y_OFFSET = -0.8f;
private readonly PlayerActorId _followActorId = PlayerActorId.XueJian;
private const PlayerActorId FOLLOW_ACTOR_ID = PlayerActorId.XueJian;
private SceneManager _sceneManager;
private Actor _actor;
private ActorController _actorController;
private ActorActionController _actorActionController;
private bool _isTargetRegistered;
private GameObject _target;
@@ -35,15 +39,24 @@ namespace Pal3.Actor
private ActorActionController _targetActorActionController;
private float _targetHeight;
private bool _followTarget = true;
private int _currentMode = 1; // defaults to follow target actor
public void Init(ActorController actorController,
public void Init(Actor actor,
ActorController actorController,
ActorActionController actionController)
{
base.Init(actionController);
base.Init(actor, actionController);
_actor = actor;
_actorController = actorController;
_actorActionController = actionController;
_sceneManager = ServiceLocator.Instance.Get<SceneManager>();
}
public int GetCurrentMode()
{
return _currentMode;
}
private void OnEnable()
{
CommandExecutorRegistry<ICommand>.Instance.Register(this);
@@ -96,27 +109,42 @@ namespace Pal3.Actor
}
Vector3 myNewPosition = GetTargetStayPosition();
var distanceToNewPosition = Vector3.Distance(myNewPosition, transform.position);
if (Vector3.Distance(myNewPosition, transform.position) > FOLLOW_TARGET_MAX_DISTANCE)
if (distanceToNewPosition < float.Epsilon)
{
transform.position = myNewPosition;
_actorActionController.PerformAction(_actor.GetIdleAction());
}
else
{
if (Vector3.Distance(myNewPosition, transform.position) < FOLLOW_TARGET_MAX_DISTANCE)
{
_actorActionController.PerformAction(_actor.GetMovementAction(0));
}
else
{
transform.position = (transform.position - myNewPosition).normalized * FOLLOW_TARGET_MAX_DISTANCE +
myNewPosition;
_actorActionController.PerformAction(_actor.GetMovementAction(1));
}
transform.position = Vector3.MoveTowards(transform.position,
myNewPosition,
Time.deltaTime * FLY_SPEED);
transform.LookAt(new Vector3(myNewPosition.x, transform.position.y, myNewPosition.z));
}
if (_isTargetRegistered)
if (distanceToNewPosition < ROTATION_SYNCING_DISTANCE)
{
transform.rotation = _target.transform.rotation;
Vector3 newRotation= Vector3.RotateTowards(transform.forward,
_target.transform.forward, ROTATION_SPEED * Time.deltaTime, 0.0f);
transform.rotation = Quaternion.LookRotation(newRotation);
}
}
private void FindAndSetTarget()
{
_target = _sceneManager.GetCurrentScene().GetActorGameObject((byte) _followActorId);
_target = _sceneManager.GetCurrentScene().GetActorGameObject((byte) FOLLOW_ACTOR_ID);
_targetActorController = _target.GetComponent<ActorController>();
_targetActorActionController = _target.GetComponent<ActorActionController>();
_isTargetRegistered = true;
@@ -139,6 +167,8 @@ namespace Pal3.Actor
_followTarget = false;
break;
}
_currentMode = command.Mode;
}
}
}
@@ -18,6 +18,8 @@ namespace Pal3.Actor
private Actor _actor;
private ActorActionController _actionController;
private int _currentMode = 0;
public void Init(Actor actor, ActorActionController actionController)
{
_actor = actor;
@@ -33,12 +35,20 @@ namespace Pal3.Actor
{
CommandExecutorRegistry<ICommand>.Instance.UnRegister(this);
}
public int GetCurrentMode()
{
return _currentMode;
}
public void Execute(LongKuiSwitchModeCommand command)
{
_currentMode = command.Mode;
_actor.ChangeName(command.Mode == 0 ?
ActorConstants.LongKuiHumanModeActorName :
ActorConstants.LongKuiGhostModeActorName);
if (_actor.IsActive)
{
_actionController.PerformAction(_actor.GetIdleAction(), overwrite: true);
+169 -95
View File
@@ -7,6 +7,7 @@ namespace Pal3.Audio
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Command;
@@ -25,7 +26,7 @@ namespace Pal3.Audio
public sealed class AudioManager : MonoBehaviour,
ICommandExecutor<PlaySfxCommand>,
ICommandExecutor<PlayMusicCommand>,
ICommandExecutor<PlaySfxAtGameObjectRequest>,
ICommandExecutor<AttachSfxToGameObjectRequest>,
ICommandExecutor<StopSfxPlayingAtGameObjectRequest>,
ICommandExecutor<GameStateChangedNotification>,
ICommandExecutor<StopMusicCommand>,
@@ -33,17 +34,18 @@ namespace Pal3.Audio
ICommandExecutor<ScenePostLoadingNotification>,
ICommandExecutor<ResetGameStateCommand>
{
public float MusicVolume { get; set; } = 0.45f;
public float SoundVolume { get; set; } = 0.65f;
public float DefaultMusicVolume { get; set; } = 0.45f;
public float DefaultSoundVolume { get; set; } = 0.65f;
private Camera _mainCamera;
private AudioSource _musicPlayer;
private AudioSource _sfxPlayer;
private GameResourceProvider _resourceProvider;
private SceneManager _sceneManager;
private const string STOP_MUSIC_NAME = "NONE";
private string _currentMusicClipName = string.Empty;
private string _currentScriptMusic = string.Empty;
private readonly List<string> _playingSfxSourceNames = new ();
// TODO: Fix and remove this hack
private const string PLAYER_ACTOR_MOVEMENT_SFX_AUDIO_SOURCE_NAME = "PlayerActorMovementSfx";
@@ -51,15 +53,15 @@ namespace Pal3.Audio
private CancellationTokenSource _sceneAudioCts = new ();
public void Init(GameResourceProvider resourceProvider,
public void Init(Camera mainCamera,
GameResourceProvider resourceProvider,
SceneManager sceneManager,
AudioSource musicSource,
AudioSource sfxSource)
AudioSource musicSource)
{
_mainCamera = mainCamera != null ? mainCamera : throw new ArgumentNullException(nameof(mainCamera));
_resourceProvider = resourceProvider ?? throw new ArgumentNullException(nameof(resourceProvider));
_sceneManager = sceneManager ?? throw new ArgumentNullException(nameof(sceneManager));
_musicPlayer = musicSource != null ? musicSource : throw new ArgumentNullException(nameof(musicSource));
_sfxPlayer = sfxSource != null ? sfxSource : throw new ArgumentNullException(nameof(sfxSource));
}
private void OnEnable()
@@ -101,17 +103,20 @@ namespace Pal3.Audio
_currentMusicClipName = musicName;
var musicFileVirtualPath = GetMusicFileVirtualPath(musicName);
var musicFileCachePath = _resourceProvider.GetMp3FilePathInCacheFolder(musicFileVirtualPath);
yield return PlayMusic(musicFileVirtualPath, musicFileCachePath, -1);
yield return PlayMusic(musicName, musicFileVirtualPath, musicFileCachePath, -1);
}
public IEnumerator PlayAudioClip(AudioSource audioSource,
private IEnumerator PlayAudioClip(AudioSource audioSource,
AudioClip audioClip,
int loopCount,
float interval,
float volume,
CancellationToken cancellationToken)
{
if (loopCount <= 0 && interval == 0f)
if (audioSource == null || !audioSource.enabled) yield break;
if (loopCount == -1 && interval == 0f)
{
if (audioSource.clip != null)
{
@@ -124,7 +129,7 @@ namespace Pal3.Audio
audioSource.loop = true;
audioSource.Play();
}
else if (loopCount <= 0 && interval > 0f)
else if (loopCount == -1 && interval > 0f)
{
while (!cancellationToken.IsCancellationRequested && audioSource != null)
{
@@ -141,44 +146,42 @@ namespace Pal3.Audio
}
}
}
public IEnumerator PlaySfx(string sfxFilePath, int loopCount, CancellationToken cancellationToken)
{
AudioClip sfxAudioClip = null;
yield return _resourceProvider.LoadAudioClip(sfxFilePath, AudioType.WAV, audioClip =>
{
sfxAudioClip = audioClip;
});
if (sfxAudioClip == null || cancellationToken.IsCancellationRequested) yield break;
yield return PlayAudioClip(_sfxPlayer, sfxAudioClip, loopCount, 0f, SoundVolume, cancellationToken);
}
// Spatial Audio
public IEnumerator PlaySfx(GameObject parent,
private IEnumerator AttachSfxToGameObjectAndPlaySfx(GameObject parent,
string sfxFilePath,
string audioSourceName,
int loopCount,
float volume,
int loopCount = -1,
float interval = 0f,
CancellationToken cancellationToken = default)
{
if (parent == null || cancellationToken.IsCancellationRequested) yield break;
AudioClip sfxAudioClip = null;
yield return _resourceProvider.LoadAudioClip(sfxFilePath, AudioType.WAV, audioClip =>
{
sfxAudioClip = audioClip;
});
if (parent == null || cancellationToken.IsCancellationRequested || sfxAudioClip == null) yield break;
if (parent == null ||
cancellationToken.IsCancellationRequested ||
sfxAudioClip == null) yield break;
if (audioSourceName == PLAYER_ACTOR_MOVEMENT_SFX_AUDIO_SOURCE_NAME &&
if (parent != _mainCamera.gameObject &&
audioSourceName == PLAYER_ACTOR_MOVEMENT_SFX_AUDIO_SOURCE_NAME &&
_playerMovementSfxInProgress == false)
{
yield break;
yield break; // Means movement sfx is already stopped before it started due to the delay of the coroutine
}
if (parent == _mainCamera.gameObject &&
!_playingSfxSourceNames.Contains(audioSourceName))
{
yield break; // Means sfx is already stopped before it started due to the delay of the coroutine
}
GameObject audioSourceParent;
Transform audioSourceParentTransform = parent.transform.Find(audioSourceName);
if (audioSourceParentTransform != null)
@@ -199,6 +202,22 @@ namespace Pal3.Audio
yield return PlayAudioClip(audioSource, sfxAudioClip, loopCount, interval, volume, cancellationToken);
}
private IEnumerator StartWithDelay(
float delayInSeconds,
IEnumerator coroutine,
CancellationToken cancellationToken)
{
if (delayInSeconds > 0)
{
yield return new WaitForSeconds(delayInSeconds);
}
if (!cancellationToken.IsCancellationRequested)
{
yield return coroutine;
}
}
private string GetMusicFileVirtualPath(string musicName)
{
@@ -207,77 +226,129 @@ namespace Pal3.Audio
$"{FileConstants.MusicCpkPathInfo.relativePath}{separator}{musicName}.mp3";
}
public IEnumerator PlayMusic(string musicFileVirtualPath, string musicFileCachePath, int loopCount)
public IEnumerator PlayMusic(string musicName,
string musicFileVirtualPath,
string musicFileCachePath,
int loopCount)
{
yield return _resourceProvider.ExtractAndMoveMp3FileToCacheFolder(musicFileVirtualPath, musicFileCachePath);
AudioClip musicClip = null;
yield return _resourceProvider.LoadAudioClip(musicFileCachePath, AudioType.MPEG, audioClip =>
{
musicClip = audioClip;
});
if (musicClip == null) yield break;
StartCoroutine(PlayAudioClip(_musicPlayer, musicClip, loopCount, 0f, MusicVolume,
new CancellationToken(false))); // Should not stop music during scene switch
// We need to check if current music clip is the same as the one we are trying to play,
// since we are using coroutine to load and play music, there is a chance that the music
// clip we are trying to play is not the same as the one we supposed to play.
if (musicClip == null ||
!string.Equals(_currentMusicClipName, musicName, StringComparison.OrdinalIgnoreCase)) yield break;
yield return PlayAudioClip(_musicPlayer, musicClip, loopCount, 0f, DefaultMusicVolume,
new CancellationToken(false)); // Should not stop music during scene switch
}
private IEnumerator PlaySfxAtGameObject(string sfxFilePath,
string audioSourceName,
float volume,
float startDelayInSeconds,
int loopCount,
float interval,
GameObject parent,
CancellationToken cancellationToken)
public string GetCurrentScriptMusic()
{
if (startDelayInSeconds > 0)
{
yield return new WaitForSeconds(startDelayInSeconds);
}
return _currentScriptMusic;
}
if (!cancellationToken.IsCancellationRequested && parent != null)
private void DestroyAllSfxAudioSource()
{
// Destroy current playing sfx
foreach (Transform audioSourceParentTransform in _playingSfxSourceNames
.Select(sfxName => _mainCamera.transform.Find(sfxName))
.Where(audioSourceParentTransform => audioSourceParentTransform != null))
{
yield return PlaySfx(parent,
sfxFilePath,
audioSourceName,
volume,
loopCount,
interval,
cancellationToken);
if (audioSourceParentTransform.GetComponent<AudioSource>() is { } audioSource)
{
audioSource.Stop();
if (audioSource.clip != null)
{
Destroy(audioSource.clip);
}
}
Destroy(audioSourceParentTransform.gameObject);
}
_playingSfxSourceNames.Clear();
}
private void ChangeAllSfxAudioSourceMuteSetting(bool mute)
{
foreach (Transform audioSourceParentTransform in _playingSfxSourceNames
.Select(sfxName => _mainCamera.transform.Find(sfxName))
.Where(audioSourceParentTransform => audioSourceParentTransform != null))
{
if (audioSourceParentTransform.GetComponent<AudioSource>() is { } audioSource)
{
audioSource.mute = mute;
}
}
}
public void Execute(PlaySfxCommand command)
{
var sfxName = command.SfxName;
#if PAL3
var sfxName = command.SfxName.ToLower();
#elif PAL3A
var sfxName = command.SfxName.ToUpper();
#endif
var loopCount = command.LoopCount;
// TODO: Start/stop walk/run sfx based on actor behaviour
if (command.SfxName.Contains("we022", StringComparison.OrdinalIgnoreCase))
#if PAL3
// Fix actor movement sfx name
if (sfxName.Equals("we021", StringComparison.OrdinalIgnoreCase))
{
loopCount = 3;
sfxName = "we021a";
}
// TODO: Change walk/run sfx based on tile type
if (command.SfxName.Equals("we022", StringComparison.OrdinalIgnoreCase))
if (sfxName.Equals("we022", StringComparison.OrdinalIgnoreCase))
{
sfxName = "we022b";
sfxName = "we022a";
}
#endif
// TODO: This sfx will be triggered to loop forever after actor
// leaving the hotel. Maybe we should play it by attaching
// the sound to the hotel position?
if (command.SfxName.Equals("wc019", StringComparison.OrdinalIgnoreCase) &&
command.LoopCount == -1)
switch (loopCount)
{
return;
case 0: // start playing sfx indefinitely for the given sfxName
_playingSfxSourceNames.Add(sfxName);
StartCoroutine(AttachSfxToGameObjectAndPlaySfx(_mainCamera.gameObject,
_resourceProvider.GetSfxFilePath(sfxName),
sfxName, // use sfx name as audio source name
loopCount: -1, // loop indefinitely
DefaultSoundVolume,
interval: 0f,
_sceneAudioCts.Token));
break;
case -1: // stop playing sfx by sfxName
_playingSfxSourceNames.Remove(sfxName);
Execute(new StopSfxPlayingAtGameObjectRequest(
_mainCamera.gameObject,
sfxName,
disposeSource: true));
break;
default:
{
_playingSfxSourceNames.Add(sfxName);
var sfxFilePath = _resourceProvider.GetSfxFilePath(sfxName);
CancellationToken cancellationToken = _sceneAudioCts.Token;
StartCoroutine(AttachSfxToGameObjectAndPlaySfx(_mainCamera.gameObject,
sfxFilePath,
sfxName, // use sfx name as audio source name
loopCount,
DefaultSoundVolume,
interval: 0f,
cancellationToken));
break;
}
}
var sfxFilePath = _resourceProvider.GetSfxFilePath(sfxName);
CancellationToken cancellationToken = _sceneAudioCts.Token;
StartCoroutine(PlaySfx(sfxFilePath, loopCount, cancellationToken));
}
public void Execute(PlaySfxAtGameObjectRequest request)
public void Execute(AttachSfxToGameObjectRequest request)
{
if (request.AudioSourceName == PLAYER_ACTOR_MOVEMENT_SFX_AUDIO_SOURCE_NAME)
{
@@ -286,13 +357,14 @@ namespace Pal3.Audio
var sfxFilePath = _resourceProvider.GetSfxFilePath(request.SfxName);
CancellationToken cancellationToken = _sceneAudioCts.Token;
StartCoroutine(PlaySfxAtGameObject(sfxFilePath,
request.AudioSourceName,
request.Volume,
request.StartDelayInSeconds,
request.LoopCount,
request.Interval,
request.Parent,
StartCoroutine(StartWithDelay(request.StartDelayInSeconds,
AttachSfxToGameObjectAndPlaySfx(request.Parent,
sfxFilePath,
request.AudioSourceName,
request.LoopCount,
request.Volume,
request.Interval,
cancellationToken),
cancellationToken));
}
@@ -312,6 +384,11 @@ namespace Pal3.Audio
audioSource.Stop();
audioSource.clip = null;
if (command.DisposeSource)
{
Destroy(audioSourceParent);
}
}
public void Execute(PlayMusicCommand command)
@@ -325,7 +402,9 @@ namespace Pal3.Audio
// TODO: Disable combat music since combat system has not been implemented yet.
if (MusicConstants.CombatMusicInfo.Any(musicInfo =>
command.MusicName.Equals(musicInfo.Value, StringComparison.OrdinalIgnoreCase)))
command.MusicName.Equals(musicInfo.Value, StringComparison.OrdinalIgnoreCase)) ||
command.MusicName.Equals("PI25A", StringComparison.OrdinalIgnoreCase) ||
command.MusicName.Equals("PI25", StringComparison.OrdinalIgnoreCase))
{
return;
}
@@ -334,7 +413,8 @@ namespace Pal3.Audio
_currentMusicClipName = command.MusicName;
var musicFileVirtualPath = GetMusicFileVirtualPath(command.MusicName);
var musicFileCachePath = _resourceProvider.GetMp3FilePathInCacheFolder(musicFileVirtualPath);
StartCoroutine(PlayMusic(musicFileVirtualPath,
StartCoroutine(PlayMusic(command.MusicName,
musicFileVirtualPath,
musicFileCachePath,
command.Loop == 0 ? -1 : command.Loop));
}
@@ -355,13 +435,7 @@ namespace Pal3.Audio
public void Execute(ScenePreLoadingNotification command)
{
if (_sfxPlayer.clip != null)
{
_sfxPlayer.loop = false;
_sfxPlayer.Stop();
Destroy(_sfxPlayer.clip);
}
DestroyAllSfxAudioSource();
_sceneAudioCts.Cancel();
_sceneAudioCts = new CancellationTokenSource();
}
@@ -376,9 +450,9 @@ namespace Pal3.Audio
public void Execute(ResetGameStateCommand command)
{
DestroyAllSfxAudioSource();
_currentScriptMusic = string.Empty;
_musicPlayer.Stop();
_sfxPlayer.Stop();
}
public void Execute(GameStateChangedNotification command)
@@ -391,12 +465,12 @@ namespace Pal3.Audio
}
_musicPlayer.mute = true;
_sfxPlayer.mute = true;
ChangeAllSfxAudioSourceMuteSetting(true);
}
else
else if (command.PreviousState == GameState.VideoPlaying)
{
if (_musicPlayer.mute) _musicPlayer.mute = false;
if (_sfxPlayer.mute) _sfxPlayer.mute = false;
_musicPlayer.mute = false;
ChangeAllSfxAudioSourceMuteSetting(false);
}
}
}
+54 -5
View File
@@ -7,6 +7,8 @@ namespace Pal3.Camera
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Command;
using Command.InternalCommands;
@@ -46,7 +48,9 @@ namespace Pal3.Camera
ICommandExecutor<CameraFocusOnActorCommand>,
ICommandExecutor<CameraFocusOnSceneObjectCommand>,
ICommandExecutor<ScenePreLoadingNotification>,
ICommandExecutor<GameStateChangedNotification>
ICommandExecutor<SceneLeavingCurrentSceneNotification>,
ICommandExecutor<GameStateChangedNotification>,
ICommandExecutor<ResetGameStateCommand>
{
private const float FADE_ANIMATION_DURATION = 3f;
private const float SCENE_STORY_B_ROOM_HEIGHT = 32f;
@@ -89,6 +93,12 @@ namespace Pal3.Camera
private CancellationTokenSource _asyncCameraAnimationCts = new ();
private CancellationTokenSource _cameraFadeAnimationCts = new ();
private const int LAST_KNOWN_SCENE_STATE_LIST_MAX_LENGTH = 1;
private readonly List<(ScnSceneInfo sceneInfo,
Vector3 cameraPosition,
Quaternion cameraRotation,
Vector3 cameraOffset)> _cameraLastKnownSceneState = new ();
public void Init(PlayerInputActions inputActions,
PlayerGamePlayController gamePlayController,
SceneManager sceneManager,
@@ -369,7 +379,7 @@ namespace Pal3.Camera
return _currentAppliedDefaultTransformOption;
}
public void ApplySceneSettings(ScnSceneInfo sceneInfo)
private void ApplySceneSettings(ScnSceneInfo sceneInfo)
{
switch (sceneInfo.SceneType)
{
@@ -406,7 +416,7 @@ namespace Pal3.Camera
_shouldResetVelocity = true;
}
public void ApplyDefaultSettings(int option)
private void ApplyDefaultSettings(int option)
{
Quaternion rotation;
float distance = 688.0f / GameBoxInterpreter.GameBoxUnitToUnityUnit;
@@ -692,16 +702,49 @@ namespace Pal3.Camera
public void Execute(CameraSetYawCommand command)
{
if (!_asyncCameraAnimationCts.IsCancellationRequested) _asyncCameraAnimationCts.Cancel();
RotateToOrbitPoint(command.Yaw);
}
public void Execute(SceneLeavingCurrentSceneNotification command)
{
if (_sceneManager.GetCurrentScene() is not { } currentScene) return;
if (currentScene.GetSceneInfo().SceneType != ScnSceneType.StoryB)
{
var cameraTransform = _camera.transform;
_cameraLastKnownSceneState.Add((
currentScene.GetSceneInfo(),
cameraTransform.position,
cameraTransform.rotation,
_cameraOffset));
if (_cameraLastKnownSceneState.Count > LAST_KNOWN_SCENE_STATE_LIST_MAX_LENGTH)
{
_cameraLastKnownSceneState.RemoveAt(0);
}
}
}
public void Execute(ScenePreLoadingNotification notification)
{
_currentAppliedDefaultTransformOption = 0;
ApplySceneSettings(notification.NewSceneInfo);
}
// Apply the last known scene state if found in record.
if (notification.NewSceneInfo.SceneType != ScnSceneType.StoryB)
{
if (_cameraLastKnownSceneState.Count > 0 && _cameraLastKnownSceneState.Any(_ =>
_.sceneInfo.ModelEquals(notification.NewSceneInfo)))
{
(ScnSceneInfo _, Vector3 cameraPosition, Quaternion cameraRotation, Vector3 cameraOffset) =
_cameraLastKnownSceneState.Last(_ => _.sceneInfo.ModelEquals(notification.NewSceneInfo));
_camera.transform.SetPositionAndRotation(cameraPosition, cameraRotation);
_cameraOffset = cameraOffset;
}
}
}
public void Execute(CameraFocusOnActorCommand command)
{
if (command.ActorId == ActorConstants.PlayerActorVirtualID) return;
@@ -721,5 +764,11 @@ namespace Pal3.Camera
{
if (command.NewState == GameState.Gameplay) _free = true;
}
public void Execute(ResetGameStateCommand command)
{
_cameraLastKnownSceneState.Clear();
_free = true;
}
}
}
@@ -8,21 +8,21 @@ namespace Pal3.Command.InternalCommands
using Newtonsoft.Json;
using UnityEngine;
public class PlaySfxAtGameObjectRequest : ICommand
public class AttachSfxToGameObjectRequest : ICommand
{
public PlaySfxAtGameObjectRequest(GameObject parent,
public AttachSfxToGameObjectRequest(GameObject parent,
string sfxName,
string audioSourceName,
float volume,
int loopCount,
float volume,
float startDelayInSeconds,
float interval)
{
Parent = parent;
SfxName = sfxName;
AudioSourceName = audioSourceName;
Volume = volume;
LoopCount = loopCount;
Volume = volume;
StartDelayInSeconds = startDelayInSeconds;
Interval = interval;
}
@@ -30,10 +30,9 @@ namespace Pal3.Command.InternalCommands
[JsonIgnore] public GameObject Parent { get; }
public string SfxName { get; }
public string AudioSourceName { get; }
public float Volume { get; }
public int LoopCount { get; }
public float Volume { get; }
public float StartDelayInSeconds { get; }
public float Interval { get; }
}
}
@@ -9,11 +9,13 @@ namespace Pal3.Command.InternalCommands
public class GameStateChangedNotification : ICommand
{
public GameStateChangedNotification(GameState newState)
public GameStateChangedNotification(GameState previousState, GameState newState)
{
PreviousState = previousState;
NewState = newState;
}
public GameState PreviousState { get; }
public GameState NewState { get; }
}
}
@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: 6affef692c664172a6cc441fecd714cd
timeCreated: 1663649030
@@ -1,12 +1,12 @@
// ---------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
namespace Pal3.Command.InternalCommands
{
public class SceneBeforeLoadingNotification : ICommand
public class SceneLeavingCurrentSceneNotification : ICommand
{
public SceneBeforeLoadingNotification() { }
public SceneLeavingCurrentSceneNotification() { }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 332a46f38a2c43759aecfba77b293112
timeCreated: 1665352229
@@ -10,13 +10,15 @@ namespace Pal3.Command.InternalCommands
public class StopSfxPlayingAtGameObjectRequest : ICommand
{
public StopSfxPlayingAtGameObjectRequest(GameObject parent, string audioSourceName)
public StopSfxPlayingAtGameObjectRequest(GameObject parent, string audioSourceName, bool disposeSource)
{
Parent = parent;
AudioSourceName = audioSourceName;
DisposeSource = disposeSource;
}
[JsonIgnore] public GameObject Parent { get; }
public string AudioSourceName { get; }
public bool DisposeSource { get; }
}
}
@@ -704,7 +704,7 @@ namespace Pal3.Command
}
// <auto-generated/>
[ConsoleMethodAttribute("PlaySfx", "播放音效,参数:音效名,循环次数")]
[ConsoleMethodAttribute("PlaySfx", "播放音效,参数:音效名,循环次数(0表示开始无限循环,-1表示结束循环)")]
public static void PlaySfx(System.String sfxName, System.Int32 loopCount)
{
CommandDispatcher<ICommand>.Instance.Dispatch(
@@ -736,7 +736,7 @@ namespace Pal3.Command
}
// <auto-generated/>
[ConsoleMethodAttribute("PlaySfx", "播放音效,参数:音效名,循环次数")]
[ConsoleMethodAttribute("PlaySfx", "播放音效,参数:音效名,循环次数(0表示开始无限循环,-1表示结束循环)")]
public static void PlaySfx(System.String sfxName, System.Int32 loopCount)
{
CommandDispatcher<ICommand>.Instance.Dispatch(
@@ -6,7 +6,7 @@
namespace Pal3.Command.SceCommands
{
[SceCommand(79, "播放音效," +
"参数:音效名,循环次数")]
"参数:音效名,循环次数(0表示开始无限循环,-1表示结束循环)")]
public class PlaySfxCommand : ICommand
{
public PlaySfxCommand(string sfxName, int loopCount)
@@ -14,7 +14,7 @@ namespace Pal3.Data
/// <summary>
/// Cache/dispose Cpk archive into memory based on scenarios.
/// </summary>
public class FileSystemCacheManager :
public sealed class FileSystemCacheManager : IDisposable,
ICommandExecutor<ScenePreLoadingNotification>
{
private readonly ICpkFileSystem _fileSystem;
@@ -33,7 +33,8 @@ namespace Pal3.Data
/// Single resource provider for accessing game data.
/// Also manages the lifecycle of the resource it provides.
/// </summary>
public class GameResourceProvider : ICommandExecutor<ScenePreLoadingNotification>
public class GameResourceProvider : IDisposable,
ICommandExecutor<ScenePreLoadingNotification>
{
private const string CACHE_FOLDER_NAME = "CacheData";
private const string MV3_ACTOR_CONFIG_HEADER = ";#MV3#";
@@ -505,12 +506,13 @@ namespace Pal3.Data
{
var separator = CpkConstants.DirectorySeparator;
var emojiSpriteSheetRelativePath =
var cursorSpriteRelativePath =
$"{FileConstants.BaseDataCpkPathInfo.cpkName}{separator}" +
$"{FileConstants.UIFolderName}{separator}{FileConstants.CursorFolderName}{separator}";
ITextureResourceProvider textureProvider = GetTextureResourceProvider(emojiSpriteSheetRelativePath);
return textureProvider.GetTexture($"jt.tga");
ITextureResourceProvider textureProvider = GetTextureResourceProvider(cursorSpriteRelativePath);
Texture2D cursorTexture = textureProvider.GetTexture($"jt.tga");
return cursorTexture;
}
private string _currentSceneCityName;
+5 -3
View File
@@ -17,10 +17,11 @@ namespace Pal3.Dev
using Scene;
using Script;
using State;
using UI;
using UnityEngine;
using UnityEngine.UI;
public sealed class MazeSkipper :
public sealed class MazeSkipper : IDisposable,
ICommandExecutor<ScenePostLoadingNotification>,
ICommandExecutor<GameStateChangedNotification>
{
@@ -903,8 +904,10 @@ namespace Pal3.Dev
_mazeSkipperCanvasGroup.alpha = 0f;
_mazeSkipperCanvasGroup.interactable = false;
_mazeEntranceButton.colors = UITheme.GetButtonColors();
_mazeEntranceButton.onClick
.AddListener(EntranceButtonClicked);
_mazeExitButton.colors = UITheme.GetButtonColors();
_mazeExitButton.onClick
.AddListener(ExitButtonClicked);
@@ -962,12 +965,11 @@ namespace Pal3.Dev
public void Dispose()
{
CommandExecutorRegistry<ICommand>.Instance.UnRegister(this);
_mazeEntranceButton.onClick
.RemoveListener(EntranceButtonClicked);
_mazeExitButton.onClick
.RemoveListener(ExitButtonClicked);
CommandExecutorRegistry<ICommand>.Instance.UnRegister(this);
}
private string GetCommandHashKeyPrefix(ScnSceneInfo sceneInfo)
@@ -15,6 +15,7 @@ namespace Pal3.Dev
// Should be (1, 1) but these are (1, -1)
public static readonly HashSet<string> KnownTextureFiles = new HashSet<string>
{
"basedata.cpk\\role\\607\\607.tga",
"basedata.cpk\\role\\611\\611.tga",
"basedata.cpk\\role\\613\\613.tga",
"basedata.cpk\\role\\b03\\b03.tga",
+99 -50
View File
@@ -18,6 +18,7 @@ namespace Pal3.Dev
using Script;
using State;
using TMPro;
using UI;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
@@ -26,7 +27,10 @@ namespace Pal3.Dev
public sealed class StorySelector : MonoBehaviour,
ICommandExecutor<ToggleStorySelectorRequest>,
ICommandExecutor<GameSwitchToMainMenuCommand>
ICommandExecutor<GameSwitchToMainMenuCommand>,
ICommandExecutor<ScriptFinishedRunningNotification>,
ICommandExecutor<GameStateChangedNotification>,
ICommandExecutor<ResetGameStateCommand>
{
private InputManager _inputManager;
private EventSystem _eventSystem;
@@ -38,11 +42,14 @@ namespace Pal3.Dev
private CanvasGroup _storySelectorCanvas;
private GameObject _storySelectorButtonPrefab;
private readonly List<string> _deferredExecutionCommands = new();
private readonly List<GameObject> _selectionButtons = new();
private readonly Dictionary<string, string> _storySelections = new()
{
{"关闭", ""},
{"退出游戏", ""},
{"继续游戏", ""},
{"保存当前游戏进度", ""},
{"新的游戏", ""},
@@ -1135,25 +1142,6 @@ namespace Pal3.Dev
BigMapEnableRegion 5 2
BigMapEnableRegion 6 1
CameraFadeIn"},
{"胜州-纳林河源", @"
ScriptVarSetValue -32768 50800
SceneLoad q05 q05
ActorActivate -1 1
ActorEnablePlayerControl -1
PlayerEnableInput 1
ActorSetNavLayer -1 0
ActorSetTilePosition -1 150 85
TeamAddOrRemoveActor 2 1
TeamAddOrRemoveActor 1 1
TeamAddOrRemoveActor 4 1
BigMapEnableRegion 0 2
BigMapEnableRegion 1 2
BigMapEnableRegion 2 2
BigMapEnableRegion 4 2
BigMapEnableRegion 5 2
BigMapEnableRegion 6 1
BigMapEnableRegion 7 2
CameraFadeIn"},
{"胜州祭坛欢庆盛典", @"
ScriptVarSetValue -32768 51100
SceneLoad q05 q05
@@ -1902,6 +1890,7 @@ namespace Pal3.Dev
_playerInputActions.Gameplay.ToggleStorySelector.performed += ToggleStorySelectorOnPerformed;
_playerInputActions.Cutscene.ToggleStorySelector.performed += ToggleStorySelectorOnPerformed;
_playerInputActions.Cutscene.ExitCurrentShowingMenu.performed += HideStorySelectorOnPerformed;
}
private void OnEnable()
@@ -1914,13 +1903,25 @@ namespace Pal3.Dev
CommandExecutorRegistry<ICommand>.Instance.UnRegister(this);
_playerInputActions.Gameplay.ToggleStorySelector.performed -= ToggleStorySelectorOnPerformed;
_playerInputActions.Cutscene.ToggleStorySelector.performed -= ToggleStorySelectorOnPerformed;
_playerInputActions.Cutscene.ExitCurrentShowingMenu.performed -= HideStorySelectorOnPerformed;
}
private void ToggleStorySelectorOnPerformed(InputAction.CallbackContext obj)
private void ToggleStorySelectorOnPerformed(InputAction.CallbackContext _)
{
ToggleStorySelector();
}
private void HideStorySelectorOnPerformed(InputAction.CallbackContext _)
{
if (_sceneManager.GetCurrentScene() == null) return;
if (_storySelectorCanvas.interactable)
{
Hide();
_gameStateManager.GoToState(GameState.Gameplay);
}
}
private void ToggleStorySelector()
{
if (_sceneManager.GetCurrentScene() == null) return;
@@ -1945,52 +1946,44 @@ namespace Pal3.Dev
foreach (var story in _storySelections)
{
if (hideCloseButton && story.Key is "关闭" or "保存当前游戏进度") continue;
#if !UNITY_STANDALONE || UNITY_EDITOR
if (story.Key == "退出游戏") continue;
#endif
GameObject selectionButton = Instantiate(_storySelectorButtonPrefab, _storySelectorCanvas.transform);
var buttonTextUI = selectionButton.GetComponentInChildren<TextMeshProUGUI>();
buttonTextUI.text = story.Key;
if (story.Key is "关闭" or "保存当前游戏进度" or "退出游戏" or "新的游戏" or "继续游戏")
{
buttonTextUI.fontStyle = FontStyles.Underline;
}
var button = selectionButton.GetComponent<Button>();
Navigation buttonNavigation = button.navigation;
buttonNavigation.mode = Navigation.Mode.Horizontal | Navigation.Mode.Vertical;
button.navigation = buttonNavigation;
button.colors = UITheme.GetButtonColors();
button.onClick.AddListener(delegate { StorySelectionButtonClicked(story.Key);});
_selectionButtons.Add(selectionButton);
}
// Setup button navigation
for (var i = 0; i < _selectionButtons.Count; i++)
{
var button = _selectionButtons[i].GetComponent<Button>();
Navigation buttonNavigation = button.navigation;
buttonNavigation.mode = Navigation.Mode.Explicit;
if (i == 0)
{
buttonNavigation.selectOnLeft = _selectionButtons[^1].GetComponent<Button>();
buttonNavigation.selectOnRight = _selectionButtons[i + 1].GetComponent<Button>();
}
else if (i == _selectionButtons.Count - 1)
{
buttonNavigation.selectOnLeft = _selectionButtons[i - 1].GetComponent<Button>();
buttonNavigation.selectOnRight = _selectionButtons[0].GetComponent<Button>();
}
else
{
buttonNavigation.selectOnLeft = _selectionButtons[i - 1].GetComponent<Button>();
buttonNavigation.selectOnRight = _selectionButtons[i + 1].GetComponent<Button>();
}
button.navigation = buttonNavigation;
}
var firstButton = _selectionButtons.First().GetComponent<Button>();
_eventSystem.firstSelectedGameObject = firstButton.gameObject;
InputDevice lastActiveInputDevice = _inputManager.GetLastActiveInputDevice();
if (lastActiveInputDevice == Keyboard.current ||
lastActiveInputDevice == Gamepad.current ||
lastActiveInputDevice == DualShockGamepad.current)
{
_eventSystem.firstSelectedGameObject = firstButton.gameObject;
firstButton.Select();
}
else
{
_eventSystem.firstSelectedGameObject = null;
}
_storySelectorCanvas.alpha = 1f;
_storySelectorCanvas.interactable = true;
@@ -2004,6 +1997,9 @@ namespace Pal3.Dev
if (_sceneManager.GetCurrentScene() == null) return;
_gameStateManager.GoToState(GameState.Gameplay);
break;
case "退出游戏":
Application.Quit();
break;
case "新的游戏":
CommandDispatcher<ICommand>.Instance.Dispatch(new ResetGameStateCommand());
StartNewGame();
@@ -2024,7 +2020,7 @@ namespace Pal3.Dev
}
else
{
ExecuteCommands(commands);
ExecuteCommandsFromSaveFile(commands);
}
}
break;
@@ -2064,6 +2060,32 @@ namespace Pal3.Dev
}
}
}
private void ExecuteCommandsFromSaveFile(string commands)
{
foreach (var command in commands.Split('\n'))
{
if (string.IsNullOrEmpty(command)) continue;
var arguments = new List<string>();
DebugLogConsole.FetchArgumentsFromCommand(command, arguments);
if (arguments[0] == nameof(ActorActivateCommand).Replace("Command", string.Empty) &&
!Enum.GetValues(typeof(PlayerActorId)).Cast<int>().Contains(int.Parse(arguments[1])))
{
_deferredExecutionCommands.Add(command);
}
else if (arguments[0] == nameof(SceneActivateObjectCommand).Replace("Command", string.Empty))
{
_deferredExecutionCommands.Add(command);
}
else
{
DebugLogConsole.ExecuteCommand(command);
}
}
}
public void Hide()
{
@@ -2087,5 +2109,32 @@ namespace Pal3.Dev
{
if (!_storySelectorCanvas.interactable) Show();
}
public void Execute(ScriptFinishedRunningNotification command)
{
if (command.ScriptType == PalScriptType.Scene &&
_deferredExecutionCommands.Count > 0)
{
ExecuteCommands(string.Join('\n', _deferredExecutionCommands));
_deferredExecutionCommands.Clear();
}
}
public void Execute(GameStateChangedNotification command)
{
// Not every scene has init scene script to run,
// so we need to check if there are pending deferred commands to run.
if (command.NewState == GameState.Gameplay &&
_deferredExecutionCommands.Count > 0)
{
ExecuteCommands(string.Join('\n', _deferredExecutionCommands));
_deferredExecutionCommands.Clear();
}
}
public void Execute(ResetGameStateCommand command)
{
_deferredExecutionCommands.Clear();
}
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ namespace Pal3.Feature
using Command.SceCommands;
using MetaData;
public sealed class FavorManager :
public sealed class FavorManager : IDisposable,
ICommandExecutor<FavorAddCommand>,
ICommandExecutor<ResetGameStateCommand>
{
+1 -2
View File
@@ -11,7 +11,7 @@ namespace Pal3.Input
using State;
using UnityEngine.InputSystem;
public sealed class InputManager
public sealed class InputManager : IDisposable
{
private readonly PlayerInputActions _playerInputActions;
private InputDevice _lastActiveInputDevice;
@@ -26,7 +26,6 @@ namespace Pal3.Input
public void Dispose()
{
InputSystem.onActionChange -= OnInputActionChange;
_playerInputActions.Dispose();
}
public PlayerInputActions GetPlayerInputActions()
@@ -472,6 +472,17 @@ namespace Pal3.Input
""isComposite"": false,
""isPartOfComposite"": false
},
{
""name"": """",
""id"": ""4460ae52-4a0c-496b-9d61-4675024a3498"",
""path"": ""<Keyboard>/escape"",
""interactions"": """",
""processors"": """",
""groups"": """",
""action"": ""ToggleStorySelector"",
""isComposite"": false,
""isPartOfComposite"": false
},
{
""name"": """",
""id"": ""954e0003-1b73-4c17-a01a-4dccbafa8ca9"",
@@ -526,6 +537,15 @@ namespace Pal3.Input
""processors"": """",
""interactions"": """",
""initialStateCheck"": false
},
{
""name"": ""ExitCurrentShowingMenu"",
""type"": ""Button"",
""id"": ""f4c71292-8ed0-4ea2-9f78-bf137d63f607"",
""expectedControlType"": ""Button"",
""processors"": """",
""interactions"": """",
""initialStateCheck"": false
}
],
""bindings"": [
@@ -595,6 +615,17 @@ namespace Pal3.Input
""isComposite"": false,
""isPartOfComposite"": false
},
{
""name"": """",
""id"": ""30885317-9959-46c4-a930-1a29c0e33b47"",
""path"": ""<Keyboard>/escape"",
""interactions"": """",
""processors"": """",
""groups"": """",
""action"": ""ToggleStorySelector"",
""isComposite"": false,
""isPartOfComposite"": false
},
{
""name"": """",
""id"": ""6404737e-bf57-43a9-83a5-3fa155e78c1b"",
@@ -616,6 +647,28 @@ namespace Pal3.Input
""action"": ""ToggleBigMap"",
""isComposite"": false,
""isPartOfComposite"": false
},
{
""name"": """",
""id"": ""9a0e1e31-3aac-4131-8cc6-f1a87d113db6"",
""path"": ""<Keyboard>/escape"",
""interactions"": """",
""processors"": """",
""groups"": """",
""action"": ""ExitCurrentShowingMenu"",
""isComposite"": false,
""isPartOfComposite"": false
},
{
""name"": """",
""id"": ""046969fe-1445-429a-b8ca-1a687dbdd20d"",
""path"": ""<Gamepad>/buttonEast"",
""interactions"": """",
""processors"": """",
""groups"": """",
""action"": ""ExitCurrentShowingMenu"",
""isComposite"": false,
""isPartOfComposite"": false
}
]
},
@@ -1167,6 +1220,7 @@ namespace Pal3.Input
m_Cutscene_Continue = m_Cutscene.FindAction("Continue", throwIfNotFound: true);
m_Cutscene_ToggleBigMap = m_Cutscene.FindAction("ToggleBigMap", throwIfNotFound: true);
m_Cutscene_ToggleStorySelector = m_Cutscene.FindAction("ToggleStorySelector", throwIfNotFound: true);
m_Cutscene_ExitCurrentShowingMenu = m_Cutscene.FindAction("ExitCurrentShowingMenu", throwIfNotFound: true);
// VideoPlaying
m_VideoPlaying = asset.FindActionMap("VideoPlaying", throwIfNotFound: true);
m_VideoPlaying_SkipVideo = m_VideoPlaying.FindAction("SkipVideo", throwIfNotFound: true);
@@ -1397,6 +1451,7 @@ namespace Pal3.Input
private readonly InputAction m_Cutscene_Continue;
private readonly InputAction m_Cutscene_ToggleBigMap;
private readonly InputAction m_Cutscene_ToggleStorySelector;
private readonly InputAction m_Cutscene_ExitCurrentShowingMenu;
public struct CutsceneActions
{
private @PlayerInputActions m_Wrapper;
@@ -1404,6 +1459,7 @@ namespace Pal3.Input
public InputAction @Continue => m_Wrapper.m_Cutscene_Continue;
public InputAction @ToggleBigMap => m_Wrapper.m_Cutscene_ToggleBigMap;
public InputAction @ToggleStorySelector => m_Wrapper.m_Cutscene_ToggleStorySelector;
public InputAction @ExitCurrentShowingMenu => m_Wrapper.m_Cutscene_ExitCurrentShowingMenu;
public InputActionMap Get() { return m_Wrapper.m_Cutscene; }
public void Enable() { Get().Enable(); }
public void Disable() { Get().Disable(); }
@@ -1422,6 +1478,9 @@ namespace Pal3.Input
@ToggleStorySelector.started -= m_Wrapper.m_CutsceneActionsCallbackInterface.OnToggleStorySelector;
@ToggleStorySelector.performed -= m_Wrapper.m_CutsceneActionsCallbackInterface.OnToggleStorySelector;
@ToggleStorySelector.canceled -= m_Wrapper.m_CutsceneActionsCallbackInterface.OnToggleStorySelector;
@ExitCurrentShowingMenu.started -= m_Wrapper.m_CutsceneActionsCallbackInterface.OnExitCurrentShowingMenu;
@ExitCurrentShowingMenu.performed -= m_Wrapper.m_CutsceneActionsCallbackInterface.OnExitCurrentShowingMenu;
@ExitCurrentShowingMenu.canceled -= m_Wrapper.m_CutsceneActionsCallbackInterface.OnExitCurrentShowingMenu;
}
m_Wrapper.m_CutsceneActionsCallbackInterface = instance;
if (instance != null)
@@ -1435,6 +1494,9 @@ namespace Pal3.Input
@ToggleStorySelector.started += instance.OnToggleStorySelector;
@ToggleStorySelector.performed += instance.OnToggleStorySelector;
@ToggleStorySelector.canceled += instance.OnToggleStorySelector;
@ExitCurrentShowingMenu.started += instance.OnExitCurrentShowingMenu;
@ExitCurrentShowingMenu.performed += instance.OnExitCurrentShowingMenu;
@ExitCurrentShowingMenu.canceled += instance.OnExitCurrentShowingMenu;
}
}
}
@@ -1601,6 +1663,7 @@ namespace Pal3.Input
void OnContinue(InputAction.CallbackContext context);
void OnToggleBigMap(InputAction.CallbackContext context);
void OnToggleStorySelector(InputAction.CallbackContext context);
void OnExitCurrentShowingMenu(InputAction.CallbackContext context);
}
public interface IVideoPlayingActions
{
@@ -448,6 +448,17 @@
"isComposite": false,
"isPartOfComposite": false
},
{
"name": "",
"id": "4460ae52-4a0c-496b-9d61-4675024a3498",
"path": "<Keyboard>/escape",
"interactions": "",
"processors": "",
"groups": "",
"action": "ToggleStorySelector",
"isComposite": false,
"isPartOfComposite": false
},
{
"name": "",
"id": "954e0003-1b73-4c17-a01a-4dccbafa8ca9",
@@ -502,6 +513,15 @@
"processors": "",
"interactions": "",
"initialStateCheck": false
},
{
"name": "ExitCurrentShowingMenu",
"type": "Button",
"id": "f4c71292-8ed0-4ea2-9f78-bf137d63f607",
"expectedControlType": "Button",
"processors": "",
"interactions": "",
"initialStateCheck": false
}
],
"bindings": [
@@ -571,6 +591,17 @@
"isComposite": false,
"isPartOfComposite": false
},
{
"name": "",
"id": "30885317-9959-46c4-a930-1a29c0e33b47",
"path": "<Keyboard>/escape",
"interactions": "",
"processors": "",
"groups": "",
"action": "ToggleStorySelector",
"isComposite": false,
"isPartOfComposite": false
},
{
"name": "",
"id": "6404737e-bf57-43a9-83a5-3fa155e78c1b",
@@ -592,6 +623,28 @@
"action": "ToggleBigMap",
"isComposite": false,
"isPartOfComposite": false
},
{
"name": "",
"id": "9a0e1e31-3aac-4131-8cc6-f1a87d113db6",
"path": "<Keyboard>/escape",
"interactions": "",
"processors": "",
"groups": "",
"action": "ExitCurrentShowingMenu",
"isComposite": false,
"isPartOfComposite": false
},
{
"name": "",
"id": "046969fe-1445-429a-b8ca-1a687dbdd20d",
"path": "<Gamepad>/buttonEast",
"interactions": "",
"processors": "",
"groups": "",
"action": "ExitCurrentShowingMenu",
"isComposite": false,
"isPartOfComposite": false
}
]
},
@@ -7,10 +7,12 @@
namespace Pal3.MiniGame
{
using System;
using Command;
using Command.SceCommands;
public sealed class AppraisalsMiniGame : ICommandExecutor<MiniGameStartAppraisalsCommand>
public sealed class AppraisalsMiniGame : IDisposable,
ICommandExecutor<MiniGameStartAppraisalsCommand>
{
public AppraisalsMiniGame()
{
@@ -7,10 +7,12 @@
namespace Pal3.MiniGame
{
using System;
using Command;
using Command.SceCommands;
public sealed class CaveExperienceMiniGame : ICommandExecutor<MiniGameStartCaveExperienceCommand>
public sealed class CaveExperienceMiniGame : IDisposable,
ICommandExecutor<MiniGameStartCaveExperienceCommand>
{
public CaveExperienceMiniGame()
{
@@ -7,10 +7,12 @@
namespace Pal3.MiniGame
{
using System;
using Command;
using Command.SceCommands;
public sealed class EncampMiniGame : ICommandExecutor<MiniGameStartEncampCommand>
public sealed class EncampMiniGame : IDisposable,
ICommandExecutor<MiniGameStartEncampCommand>
{
public EncampMiniGame()
{
@@ -7,13 +7,15 @@
namespace Pal3.MiniGame
{
using System;
using Command;
using Command.SceCommands;
using Core.Services;
using MetaData;
using Script;
public sealed class HideFightMiniGame : ICommandExecutor<MiniGameStartHideFightCommand>
public sealed class HideFightMiniGame : IDisposable,
ICommandExecutor<MiniGameStartHideFightCommand>
{
public HideFightMiniGame()
{
@@ -7,11 +7,13 @@
namespace Pal3.MiniGame
{
using System;
using Command;
using Command.SceCommands;
using MetaData;
public sealed class SailingMiniGame : ICommandExecutor<MiniGameStartSailingCommand>
public sealed class SailingMiniGame : IDisposable,
ICommandExecutor<MiniGameStartSailingCommand>
{
public SailingMiniGame()
{
+2 -1
View File
@@ -12,7 +12,8 @@ namespace Pal3.MiniGame
using Command.SceCommands;
using Script;
public sealed class SkiMiniGame : ICommandExecutor<MiniGameStartSkiCommand>
public sealed class SkiMiniGame : IDisposable,
ICommandExecutor<MiniGameStartSkiCommand>
{
private readonly ScriptManager _scriptManager;
@@ -7,10 +7,12 @@
namespace Pal3.MiniGame
{
using System;
using Command;
using Command.SceCommands;
public sealed class SwatAFlyMiniGame : ICommandExecutor<MiniGameStartSwatAFlyCommand>
public sealed class SwatAFlyMiniGame : IDisposable,
ICommandExecutor<MiniGameStartSwatAFlyCommand>
{
public SwatAFlyMiniGame()
{
+22 -4
View File
@@ -56,7 +56,6 @@ namespace Pal3
// Audio
[SerializeField] private AudioSource musicSource;
[SerializeField] private AudioSource sfxSource;
// Video
[SerializeField] private Canvas videoPlayerCanvas;
@@ -228,10 +227,10 @@ namespace Pal3
ServiceLocator.Instance.Register(_cameraManager);
_audioManager = gameObject.AddComponent<AudioManager>();
_audioManager.Init(_gameResourceProvider,
_audioManager.Init(mainCamera,
_gameResourceProvider,
_sceneManager,
musicSource,
sfxSource);
musicSource);
ServiceLocator.Instance.Register(_audioManager);
_informationManager = gameObject.AddComponent<InformationManager>();
@@ -290,6 +289,7 @@ namespace Pal3
_scriptManager,
_favorManager,
_cameraManager,
_audioManager,
_postProcessManager);
ServiceLocator.Instance.Register(_saveManager);
@@ -319,6 +319,8 @@ namespace Pal3
DebugLogConsole.AddCommand("save", "Save game state into executable commands.", ConvertCurrentGameStateToCommandStr);
DebugLogConsole.AddCommand("info", "Get current game info.", GetCurrentGameInfo);
DisableInGameDebugConsoleButtonNavigation();
_settingsManager = new SettingsManager();
_settingsManager.ApplyDefaultRenderingSettings();
_settingsManager.ApplyPlatformSpecificSettings();
@@ -331,6 +333,7 @@ namespace Pal3
_gameResourceProvider.Dispose();
_fileSystemCacheManager.Dispose();
_inputManager.Dispose();
_inputActions.Dispose();
_gameStateManager.Dispose();
_scriptManager.Dispose();
_playerManager.Dispose();
@@ -380,6 +383,21 @@ namespace Pal3
private void OnDebugWindowHidden()
{
_gameStateManager.LeaveDebugState();
// We need to do this since InGameDebugConsole will reset
// it's button navigation when it's hidden (not sure why tho).
DisableInGameDebugConsoleButtonNavigation();
}
// Disable button navigation for InGameDebugConsole
private void DisableInGameDebugConsoleButtonNavigation()
{
foreach (Button button in DebugLogManager.Instance.gameObject.GetComponentsInChildren<Button>())
{
button.navigation = new Navigation()
{
mode = Navigation.Mode.None
};
}
}
private void Update()
@@ -35,7 +35,7 @@ namespace Pal3.Player
#if PAL3
ICommandExecutor<LongKuiSwitchModeCommand>,
#endif
ICommandExecutor<SceneBeforeLoadingNotification>,
ICommandExecutor<SceneLeavingCurrentSceneNotification>,
ICommandExecutor<ScenePostLoadingNotification>,
ICommandExecutor<ResetGameStateCommand>
{
@@ -58,18 +58,17 @@ namespace Pal3.Player
#if PAL3
private int _longKuiLastKnownMode = 0;
#endif
private bool _isDuringSceneTransition = true;
private GameObject _playerActor;
private ActorController _playerActorController;
private ActorActionController _playerActorActionController;
private ActorMovementController _playerActorMovementController;
private const int POSITION_INFO_LIST_MAX_LENGTH = 2;
private readonly List<(string scene,
private const int LAST_KNOWN_SCENE_STATE_LIST_MAX_LENGTH = 2;
private readonly List<(ScnSceneInfo sceneInfo,
int actorNavIndex,
Vector2Int actorTilePosition,
Vector3 actorFacing)> _playerActorLastKnownPositionInfo = new ();
Vector3 actorFacing)> _playerActorLastKnownSceneState = new ();
public void Init(GameStateManager gameStateManager,
PlayerManager playerManager,
@@ -109,7 +108,6 @@ namespace Pal3.Player
private void Update()
{
if (_isDuringSceneTransition) return;
if (_playerActor == null) return;
var isPlayerInControl = false;
@@ -208,20 +206,22 @@ namespace Pal3.Player
if (string.IsNullOrEmpty(_currentMovementSfxAudioName))
{
CommandDispatcher<ICommand>.Instance.Dispatch(
new StopSfxPlayingAtGameObjectRequest(_playerActor, PLAYER_ACTOR_MOVEMENT_SFX_AUDIO_SOURCE_NAME));
new StopSfxPlayingAtGameObjectRequest(_playerActor,
PLAYER_ACTOR_MOVEMENT_SFX_AUDIO_SOURCE_NAME,
disposeSource: false));
}
else
{
CommandDispatcher<ICommand>.Instance.Dispatch(
new PlaySfxAtGameObjectRequest(_playerActor,
new AttachSfxToGameObjectRequest(_playerActor,
newMovementSfxAudioFileName,
PLAYER_ACTOR_MOVEMENT_SFX_AUDIO_SOURCE_NAME,
actionType == ActorActionType.Walk ?
PLAYER_ACTOR_MOVEMENT_SFX_WALK_VOLUME :
PLAYER_ACTOR_MOVEMENT_SFX_RUN_VOLUME,
-1,
0f,
0f));
loopCount: -1,
actionType == ActorActionType.Walk
? PLAYER_ACTOR_MOVEMENT_SFX_WALK_VOLUME
: PLAYER_ACTOR_MOVEMENT_SFX_RUN_VOLUME,
startDelayInSeconds: 0f,
interval: 0f));
}
}
@@ -285,12 +285,12 @@ namespace Pal3.Player
return result;
}
private void MovementCanceled(InputAction.CallbackContext ctx)
private void MovementCanceled(InputAction.CallbackContext _)
{
_playerActorActionController.PerformAction(ActorActionType.Stand);
}
private void OnTapPerformed(InputAction.CallbackContext ctx)
private void OnTapPerformed(InputAction.CallbackContext _)
{
if (!_playerManager.IsPlayerActorControlEnabled() ||
!_playerManager.IsPlayerInputEnabled())
@@ -301,7 +301,7 @@ namespace Pal3.Player
MoveToTapPosition(false);
}
private void OnDoubleTapPerformed(InputAction.CallbackContext ctx)
private void OnDoubleTapPerformed(InputAction.CallbackContext _)
{
if (!_playerManager.IsPlayerActorControlEnabled() ||
!_playerManager.IsPlayerInputEnabled())
@@ -312,7 +312,7 @@ namespace Pal3.Player
MoveToTapPosition(true);
}
private void PortalToPerformed(InputAction.CallbackContext ctx)
private void PortalToPerformed(InputAction.CallbackContext _)
{
if (!_playerManager.IsPlayerActorControlEnabled() ||
!_playerManager.IsPlayerInputEnabled())
@@ -352,7 +352,7 @@ namespace Pal3.Player
var nearestInteractableDistance = float.MaxValue;
Action interactionAction = null;
foreach (var actorInfo in _sceneManager.GetCurrentScene().GetAllActors())
foreach (var actorInfo in _sceneManager.GetCurrentScene().GetAllActorGameObjects())
{
var actorController = actorInfo.Value.GetComponent<ActorController>();
var actorMovementController = actorInfo.Value.GetComponent<ActorMovementController>();
@@ -665,7 +665,16 @@ namespace Pal3.Player
// Stop current player actor movement sfx
_currentMovementSfxAudioName = string.Empty;
CommandDispatcher<ICommand>.Instance.Dispatch(
new StopSfxPlayingAtGameObjectRequest(_playerActor, PLAYER_ACTOR_MOVEMENT_SFX_AUDIO_SOURCE_NAME));
new StopSfxPlayingAtGameObjectRequest(_playerActor,
PLAYER_ACTOR_MOVEMENT_SFX_AUDIO_SOURCE_NAME,
disposeSource: false));
// Just to make sure actor is activated
if (_playerManager.IsPlayerInputEnabled() &&
!_playerActorController.IsActive)
{
_playerActorController.IsActive = true;
}
}
public void Execute(PlayerEnableInputCommand command)
@@ -701,30 +710,19 @@ namespace Pal3.Player
if (command.ActorId == ActorConstants.PlayerActorVirtualID)
{
Scene currentScene = _sceneManager.GetCurrentScene();
var currentLayerIndex = currentScene
.GetActorGameObject((byte) _playerManager.GetPlayerActor())
.GetComponent<ActorMovementController>()
.GetCurrentLayerIndex();
_lastKnownPosition = currentScene.GetTilemap().GetWorldPosition(
new Vector2Int(command.TileXPosition,command.TileZPosition), currentLayerIndex);
}
}
private string GetSceneNameHashKey(ScnSceneInfo sceneInfo)
public void Execute(SceneLeavingCurrentSceneNotification command)
{
#if PAL3
return $"{sceneInfo.CityName}_{sceneInfo.Model}";
#elif PAL3A
return sceneInfo.Model.EndsWith("y", StringComparison.OrdinalIgnoreCase) ?
$"{sceneInfo.CityName}_{sceneInfo.Model[..^1]}" :
$"{sceneInfo.CityName}_{sceneInfo.Model}";
#endif
}
public void Execute(SceneBeforeLoadingNotification command)
{
_isDuringSceneTransition = true;
if (_sceneManager.GetCurrentScene() is not { } currentScene) return;
// Stop current player actor movement sfx
@@ -732,18 +730,20 @@ namespace Pal3.Player
{
_currentMovementSfxAudioName = string.Empty;
CommandDispatcher<ICommand>.Instance.Dispatch(
new StopSfxPlayingAtGameObjectRequest(_playerActor, PLAYER_ACTOR_MOVEMENT_SFX_AUDIO_SOURCE_NAME));
new StopSfxPlayingAtGameObjectRequest(_playerActor,
PLAYER_ACTOR_MOVEMENT_SFX_AUDIO_SOURCE_NAME,
disposeSource: true));
}
_playerActorLastKnownPositionInfo.Add((
GetSceneNameHashKey(currentScene.GetSceneInfo()),
_playerActorLastKnownSceneState.Add((
currentScene.GetSceneInfo(),
_playerActorMovementController.GetCurrentLayerIndex(),
_playerActorMovementController.GetTilePosition(),
_playerActor.transform.forward));
if (_playerActorLastKnownPositionInfo.Count > POSITION_INFO_LIST_MAX_LENGTH)
if (_playerActorLastKnownSceneState.Count > LAST_KNOWN_SCENE_STATE_LIST_MAX_LENGTH)
{
_playerActorLastKnownPositionInfo.RemoveAt(0);
_playerActorLastKnownSceneState.RemoveAt(0);
}
}
@@ -753,23 +753,19 @@ namespace Pal3.Player
CommandDispatcher<ICommand>.Instance.Dispatch(new ActorActivateCommand(playerActorId, 1));
if (_playerActorLastKnownPositionInfo.Count > 0 && _playerActorLastKnownPositionInfo.Any(_ => string.Equals(
_.scene,
GetSceneNameHashKey(notification.NewSceneInfo),
StringComparison.OrdinalIgnoreCase)))
if (_playerActorLastKnownSceneState.Count > 0 && _playerActorLastKnownSceneState.Any(_ =>
_.sceneInfo.ModelEquals(notification.NewSceneInfo)))
{
(string scene, int actorNavIndex, Vector2Int actorTilePosition, Vector3 actorFacing) positionInfo = _playerActorLastKnownPositionInfo.Last(_ => string.Equals(
_.scene,
GetSceneNameHashKey(notification.NewSceneInfo),
StringComparison.OrdinalIgnoreCase));
(ScnSceneInfo _, int actorNavIndex, Vector2Int actorTilePosition, Vector3 actorFacing) =
_playerActorLastKnownSceneState.Last(_ => _.sceneInfo.ModelEquals(notification.NewSceneInfo));
CommandDispatcher<ICommand>.Instance.Dispatch(
new ActorSetNavLayerCommand(playerActorId, positionInfo.actorNavIndex));
new ActorSetNavLayerCommand(playerActorId, actorNavIndex));
CommandDispatcher<ICommand>.Instance.Dispatch(
new ActorSetTilePositionCommand(playerActorId, positionInfo.actorTilePosition.x, positionInfo.actorTilePosition.y));
new ActorSetTilePositionCommand(playerActorId, actorTilePosition.x, actorTilePosition.y));
_sceneManager.GetCurrentScene()
.GetActorGameObject((byte)playerActorId).transform.forward = positionInfo.actorFacing;
.GetActorGameObject((byte)playerActorId).transform.forward = actorFacing;
}
if (_playerManager.IsPlayerActorControlEnabled())
@@ -785,13 +781,28 @@ namespace Pal3.Player
#if PAL3
CommandDispatcher<ICommand>.Instance.Dispatch(new LongKuiSwitchModeCommand(_longKuiLastKnownMode));
#endif
_isDuringSceneTransition = false;
}
public void Execute(ResetGameStateCommand command)
{
_playerActorLastKnownPositionInfo.Clear();
_playerActorLastKnownSceneState.Clear();
_currentMovementSfxAudioName = string.Empty;
_lastInputTapPosition = default;
_lastKnownPosition = default;
_lastKnownTilePosition = default;
_lastKnownLayerIndex = 0;
_lastKnownPlayerActorAction = string.Empty;
#if PAL3
_longKuiLastKnownMode = 0;
#endif
_playerActor = null;
_playerActorController = null;
_playerActorActionController = null;
_playerActorMovementController = null;
}
#if PAL3
+12 -3
View File
@@ -5,12 +5,13 @@
namespace Pal3.Player
{
using System;
using Command;
using Command.InternalCommands;
using Command.SceCommands;
using MetaData;
public sealed class PlayerManager :
public sealed class PlayerManager : IDisposable,
ICommandExecutor<DialogueRenderActorAvatarCommand>,
ICommandExecutor<ActorActivateCommand>,
ICommandExecutor<ActorAddSkillCommand>,
@@ -47,10 +48,11 @@ namespace Pal3.Player
#endif
ICommandExecutor<PlayerEnableInputCommand>,
ICommandExecutor<CameraFocusOnActorCommand>,
ICommandExecutor<EffectAttachToActorCommand>
ICommandExecutor<EffectAttachToActorCommand>,
ICommandExecutor<ResetGameStateCommand>
{
private PlayerActorId _playerActor = 0;
private bool _playerActorControlEnabled;
private bool _playerActorControlEnabled = true;
private bool _playerInputEnabled;
public PlayerManager()
@@ -368,5 +370,12 @@ namespace Pal3.Player
new EffectAttachToActorCommand((int)_playerActor));
}
}
public void Execute(ResetGameStateCommand command)
{
_playerActor = 0;
_playerActorControlEnabled = true;
_playerInputEnabled = false;
}
}
}
+2 -2
View File
@@ -17,7 +17,7 @@ namespace Pal3.Player
using Scene;
using UnityEngine;
public sealed class TeamManager :
public sealed class TeamManager : IDisposable,
ICommandExecutor<TeamOpenCommand>,
ICommandExecutor<TeamCloseCommand>,
ICommandExecutor<TeamAddOrRemoveActorCommand>,
@@ -128,7 +128,7 @@ namespace Pal3.Player
var playerActorIds = Enum.GetValues(typeof(PlayerActorId)).Cast<int>();
var activePlayerActors = _sceneManager.GetCurrentScene()
.GetAllActors()
.GetAllActorGameObjects()
.Where(actor => playerActorIds.Contains(actor.Key) &&
actor.Value.GetComponent<ActorController>().IsActive);
@@ -25,6 +25,8 @@ namespace Pal3.Renderer
{
public event EventHandler<int> AnimationLoopPointReached;
private const int TRANSPARENT_RENDER_QUEUE_INDEX = 3000;
private const string MV3_ANIMATION_HOLD_EVENT_NAME = "hold";
private const string MV3_MODEL_DEFAULT_TEXTURE_EXTENSION = ".tga";
private const float TIME_TO_TICK_SCALE = 5000f;
@@ -32,6 +34,7 @@ namespace Pal3.Renderer
private readonly int _mainTexturePropertyId = Shader.PropertyToID("_MainTex");
private readonly int _cutoffPropertyId = Shader.PropertyToID("_Cutoff");
private readonly int _tintColorPropertyId = Shader.PropertyToID("_TintColor");
private readonly int _isOpaquePropertyId = Shader.PropertyToID("_IsOpaque");
private Shader _standardNoShadowShader;
private ITextureResourceProvider _textureProvider;
@@ -153,10 +156,12 @@ namespace Pal3.Renderer
_materials[index] = new Material(_standardNoShadowShader);
_materials[index].SetTexture(_mainTexturePropertyId, _textures[index]);
var cutoff = _textureHasAlphaChannel[index] ? 0.3f : 0f;
var cutoff = _textureHasAlphaChannel[index] ? 0.01f : 0f;
if (cutoff > Mathf.Epsilon)
{
_materials[index].SetFloat(_cutoffPropertyId, cutoff);
_materials[index].renderQueue = TRANSPARENT_RENDER_QUEUE_INDEX - 100; // TODO: Find a better way to set render queue
_materials[index].SetFloat(_isOpaquePropertyId, .0f);
}
_materials[index].SetColor(_tintColorPropertyId, _tintColor);
@@ -39,18 +39,16 @@ namespace Pal3.Renderer
private readonly int _shadowTexturePropertyId = Shader.PropertyToID("_ShadowTex");
private readonly int _cutoffPropertyId = Shader.PropertyToID("_Cutoff");
private readonly int _tintColorPropertyId = Shader.PropertyToID("_TintColor");
private readonly int _transparencyPropertyId = Shader.PropertyToID("_Transparency");
private readonly int _isOpaquePropertyId = Shader.PropertyToID("_IsOpaque");
private Shader _standardShader;
private Shader _standardNoShadowShader;
private readonly Dictionary<string, Material> _materials = new ();
private bool _disableTransparency;
public void Render(PolFile polFile, ITextureResourceProvider textureProvider, Color tintColor, bool disableTransparency = false)
public void Render(PolFile polFile, ITextureResourceProvider textureProvider, Color tintColor)
{
_textureProvider = textureProvider;
_tintColor = tintColor;
_textureCache = BuildTextureCache(polFile, textureProvider);
_disableTransparency = disableTransparency;
_standardShader = Shader.Find("Pal3/Standard");
_standardNoShadowShader = Shader.Find("Pal3/StandardNoShadow");
@@ -58,7 +56,7 @@ namespace Pal3.Renderer
for (var i = 0; i < polFile.Meshes.Length; i++)
{
RenderMeshInternal(
polFile.NodeDescriptions[i].Name,
polFile.NodeDescriptions[i],
polFile.Meshes[i]);
}
}
@@ -95,7 +93,7 @@ namespace Pal3.Renderer
return textureCache;
}
private void RenderMeshInternal(string meshName, PolMesh mesh)
private void RenderMeshInternal(PolGeometryNode meshNode, PolMesh mesh)
{
for (var i = 0; i < mesh.Textures.Length; i++)
{
@@ -112,11 +110,11 @@ namespace Pal3.Renderer
if (textures.Count == 0)
{
Debug.LogWarning($"0 texture found for {meshName}");
Debug.LogWarning($"0 texture found for {meshNode.Name}");
return;
}
var meshObject = new GameObject(meshName);
var meshObject = new GameObject(meshNode.Name);
// Attach BlendFlag and GameBoxMaterial to the GameObject for better debuggability
#if UNITY_EDITOR
@@ -126,17 +124,13 @@ namespace Pal3.Renderer
#endif
var meshRenderer = meshObject.AddComponent<StaticMeshRenderer>();
GameBoxMaterial gbMaterial = mesh.Textures[i].Material;
var blendFlag = mesh.Textures[i].BlendFlag;
if (textures.Count == 1)
{
var materialHashKey = _standardNoShadowShader.name +
textures[0].name +
blendFlag +
gbMaterial.Emissive.r +
gbMaterial.Emissive.g +
gbMaterial.Emissive.b;
blendFlag;
var isWaterSurface = textures[0].name
.StartsWith(ANIMATED_WATER_TEXTURE_DEFAULT_NAME, StringComparison.OrdinalIgnoreCase);
@@ -157,18 +151,10 @@ namespace Pal3.Renderer
material.SetFloat(_cutoffPropertyId, cutoff);
}
if (!_disableTransparency &&
(gbMaterial.Emissive.r is > 0 and < 255 ||
gbMaterial.Emissive.g is > 0 and < 255 ||
gbMaterial.Emissive.b is > 0 and < 255 ||
isWaterSurface))
if (blendFlag is 1 or 2)
{
var transparency = blendFlag is 1 or 2 ? 0.5f : 0f;
if (transparency > Mathf.Epsilon)
{
material.renderQueue = TRANSPARENT_RENDER_QUEUE_INDEX;
material.SetFloat(_transparencyPropertyId, transparency);
}
material.renderQueue = TRANSPARENT_RENDER_QUEUE_INDEX;
material.SetFloat(_isOpaquePropertyId, .0f);
}
material.SetColor(_tintColorPropertyId, _tintColor);
_materials[materialHashKey] = material;
@@ -191,10 +177,7 @@ namespace Pal3.Renderer
var materialHashKey = _standardShader.name +
textures[0].name +
textures[1].name +
blendFlag +
gbMaterial.Emissive.r +
gbMaterial.Emissive.g +
gbMaterial.Emissive.b;
blendFlag;
var isWaterSurface = textures[1].name
.StartsWith(ANIMATED_WATER_TEXTURE_DEFAULT_NAME, StringComparison.OrdinalIgnoreCase);
@@ -216,18 +199,10 @@ namespace Pal3.Renderer
material.SetFloat(_cutoffPropertyId, cutoff);
}
if (!_disableTransparency &&
(gbMaterial.Emissive.r is > 0 and < 255 ||
gbMaterial.Emissive.g is > 0 and < 255 ||
gbMaterial.Emissive.b is > 0 and < 255 ||
isWaterSurface))
if (blendFlag is 1 or 2)
{
var transparency = blendFlag is 1 or 2 ? 0.5f : 0f;
if (transparency > Mathf.Epsilon)
{
material.renderQueue = TRANSPARENT_RENDER_QUEUE_INDEX;
material.SetFloat(_transparencyPropertyId, transparency);
}
material.renderQueue = TRANSPARENT_RENDER_QUEUE_INDEX;
material.SetFloat(_isOpaquePropertyId, .0f);
}
material.SetColor(_tintColorPropertyId, _tintColor);
_materials[materialHashKey] = material;
+12 -2
View File
@@ -161,18 +161,28 @@ namespace Pal3.Scene
{
return _activatedSceneObjects;
}
public Dictionary<byte, SceneObject> GetAllSceneObjects()
{
return SceneObjects;
}
public Actor GetActor(byte id)
{
return Actors.ContainsKey(id) ? Actors[id] : null;
}
public Dictionary<byte, Actor> GetAllActors()
{
return Actors;
}
public GameObject GetActorGameObject(byte id)
{
return _actorObjects.ContainsKey(id) ? _actorObjects[id] : null;
}
public Dictionary<byte, GameObject> GetAllActors()
public Dictionary<byte, GameObject> GetAllActorGameObjects()
{
return _actorObjects;
}
@@ -325,7 +335,7 @@ namespace Pal3.Scene
/// </summary>
private HashSet<Vector2Int> GetAllActiveActorBlockingTilePositions(int layerIndex, byte[] excludeActorIds)
{
var allActors = GetAllActors();
var allActors = GetAllActorGameObjects();
var actorTiles = new HashSet<Vector2Int>();
foreach ((var id, GameObject actor) in allActors)
+2 -3
View File
@@ -19,7 +19,7 @@ namespace Pal3.Scene
using Debug = UnityEngine.Debug;
using Object = UnityEngine.Object;
public sealed class SceneManager :
public sealed class SceneManager : IDisposable,
ICommandExecutor<SceneLoadCommand>,
ICommandExecutor<ResetGameStateCommand>
{
@@ -51,8 +51,6 @@ namespace Pal3.Scene
public void LoadScene(string sceneFileName, string sceneName)
{
CommandDispatcher<ICommand>.Instance.Dispatch(new SceneBeforeLoadingNotification());
var timer = new Stopwatch();
timer.Start();
DisposeCurrentScene();
@@ -83,6 +81,7 @@ namespace Pal3.Scene
{
if (_currentScene != null)
{
CommandDispatcher<ICommand>.Instance.Dispatch(new SceneLeavingCurrentSceneNotification());
Object.Destroy(_currentScene);
Object.Destroy(_currentSceneRoot);
_currentScene = null;
@@ -105,7 +105,7 @@ namespace Pal3.Scene.SceneObjects
// scene when holding the stick while transferring between scenes.
// We simply disable the auto trigger for a short time window after
// a fresh scene load.
var disableTime = _autoTrigger.Info.Type == ScnSceneObjectType.Door ? 1f : 0.4f;
var disableTime = _autoTrigger.Info.Type == ScnSceneObjectType.Door ? 1f : 0.45f;
if (Time.realtimeSinceStartupAsDouble - _awakeTime < disableTime) return;
if (!_wasTriggered)
@@ -94,7 +94,7 @@ namespace Pal3.Scene.SceneObjects
{
(PolFile PolFile, ITextureResourceProvider TextureProvider) poly = resourceProvider.GetPol(_modelFilePath);
var sceneObjectRenderer = sceneGameObject.AddComponent<PolyModelRenderer>();
sceneObjectRenderer.Render(poly.PolFile, poly.TextureProvider, tintColor, disableTransparency: true);
sceneObjectRenderer.Render(poly.PolFile, poly.TextureProvider, tintColor);
}
else if (_modelFilePath.ToLower().EndsWith(".cvd"))
{
@@ -41,11 +41,11 @@ namespace Pal3.Scene.SceneObjects
}
CommandDispatcher<ICommand>.Instance.Dispatch(
new PlaySfxAtGameObjectRequest(sceneGameObject,
new AttachSfxToGameObjectRequest(sceneGameObject,
SfxName,
SCENE_SFX_AUDIO_SOURCE_NAME,
loopCount: -1,
SCENE_SFX_VOLUME,
0,
startDelay,
interval));
+20 -8
View File
@@ -25,7 +25,7 @@ namespace Pal3.Script
using Waiter;
using Random = UnityEngine.Random;
public class PalScriptRunner:
public class PalScriptRunner : IDisposable,
ICommandExecutor<ScriptChangeExecutionModeCommand>,
ICommandExecutor<ScriptSetOperatorCommand>,
ICommandExecutor<ScriptVarGreaterThanCommand>,
@@ -74,7 +74,7 @@ namespace Pal3.Script
private readonly Stack<IWaitUntil> _waiters = new ();
private bool _isExecuting;
private bool _idDisposed;
private bool _isDisposed;
private PalScriptRunner() {}
@@ -117,10 +117,21 @@ namespace Pal3.Script
public void Dispose()
{
if (_idDisposed) return;
CommandExecutorRegistry<ICommand>.Instance.UnRegister(this);
_scriptDataReader.Dispose();
_idDisposed = true;
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
CommandExecutorRegistry<ICommand>.Instance.UnRegister(this);
_scriptDataReader.Dispose();
}
_isDisposed = true;
}
}
public bool Update(float deltaTime)
@@ -153,7 +164,7 @@ namespace Pal3.Script
private bool Execute()
{
if (_idDisposed) return false;
if (_isDisposed) return false;
if (_scriptDataReader.BaseStream.Position == _scriptDataReader.BaseStream.Length)
{
@@ -162,7 +173,8 @@ namespace Pal3.Script
_isExecuting = true;
while (!_idDisposed && _scriptDataReader.BaseStream.Position < _scriptDataReader.BaseStream.Length)
while (!_isDisposed &&
_scriptDataReader.BaseStream.Position < _scriptDataReader.BaseStream.Length)
{
ExecuteNextCommand();
if (_executionMode == PalScriptExecutionMode.Break) break;
+3 -1
View File
@@ -18,7 +18,7 @@ namespace Pal3.Script
using Newtonsoft.Json;
using UnityEngine;
public sealed class ScriptManager :
public sealed class ScriptManager : IDisposable,
ICommandExecutor<ScriptRunCommand>,
ICommandExecutor<ScriptVarSetValueCommand>,
ICommandExecutor<ScriptVarAddValueCommand>,
@@ -47,6 +47,8 @@ namespace Pal3.Script
{
CommandExecutorRegistry<ICommand>.Instance.UnRegister(this);
_pendingScripts.Clear();
foreach (PalScriptRunner scriptRunner in _runningScripts)
{
scriptRunner.OnCommandExecutionRequested -= OnCommandExecutionRequested;
@@ -21,19 +21,22 @@ namespace Pal3.Settings
public void ApplyDefaultRenderingSettings()
{
//var vSyncCount = Utility.IsDesktopDevice() ? 0 : 1;
//QualitySettings.vSyncCount = vSyncCount;
var vSyncCount = Utility.IsDesktopDevice() ? 0 : 1;
QualitySettings.vSyncCount = vSyncCount;
var monitorRefreshRate = Screen.currentResolution.refreshRate;
Application.targetFrameRate = Application.platform switch
{
RuntimePlatform.WindowsEditor => 120,
RuntimePlatform.WindowsPlayer => 120,
RuntimePlatform.OSXEditor => 120,
RuntimePlatform.OSXPlayer => 120,
RuntimePlatform.LinuxEditor => 120,
RuntimePlatform.LinuxPlayer => 120,
RuntimePlatform.WindowsEditor => monitorRefreshRate,
RuntimePlatform.WindowsPlayer => monitorRefreshRate,
RuntimePlatform.OSXEditor => monitorRefreshRate,
RuntimePlatform.OSXPlayer => monitorRefreshRate,
RuntimePlatform.LinuxEditor => monitorRefreshRate,
RuntimePlatform.LinuxPlayer => monitorRefreshRate,
RuntimePlatform.IPhonePlayer => 120,
RuntimePlatform.Android => 120,
RuntimePlatform.Switch => 60,
_ => -1,
};
+13 -12
View File
@@ -15,7 +15,7 @@ namespace Pal3.State
using UI;
using UnityEngine;
public sealed class GameStateManager :
public sealed class GameStateManager : IDisposable,
ICommandExecutor<PlayVideoCommand>,
ICommandExecutor<VideoEndedNotification>,
ICommandExecutor<PlayerEnableInputCommand>,
@@ -26,7 +26,7 @@ namespace Pal3.State
ICommandExecutor<GameSwitchToMainMenuCommand>
{
private GameState _previousState;
private GameState _state;
private GameState _currentState;
private readonly InputManager _inputManager;
private readonly ScriptManager _scriptManager;
private bool _isDebugging;
@@ -38,7 +38,7 @@ namespace Pal3.State
_inputManager = inputManager ?? throw new ArgumentNullException(nameof(inputManager));
_scriptManager = scriptManager ?? throw new ArgumentNullException(nameof(scriptManager));
_previousState = GameState.UI;
_state = GameState.UI;
_currentState = GameState.UI;
CommandExecutorRegistry<ICommand>.Instance.Register(this);
}
@@ -49,21 +49,22 @@ namespace Pal3.State
public GameState GetCurrentState()
{
return _state;
return _currentState;
}
public void GoToState(GameState state)
public void GoToState(GameState newState)
{
if (_state == state) return;
if (_currentState == newState) return;
Debug.Log($"Goto State: {state.ToString()}");
Debug.Log($"Goto State: {newState.ToString()}");
_previousState = _state;
_state = state;
_previousState = _currentState;
_currentState = newState;
UpdateInputManagerState();
CommandDispatcher<ICommand>.Instance.Dispatch(new GameStateChangedNotification(state));
CommandDispatcher<ICommand>.Instance.Dispatch(
new GameStateChangedNotification(_previousState, _currentState));
}
public void GoToPreviousState()
@@ -75,7 +76,7 @@ namespace Pal3.State
{
if (!_isDebugging)
{
_inputManager.SwitchCurrentActionMap(_state);
_inputManager.SwitchCurrentActionMap(_currentState);
}
}
@@ -88,7 +89,7 @@ namespace Pal3.State
public void LeaveDebugState()
{
_isDebugging = false;
_inputManager.SwitchCurrentActionMap(_state);
_inputManager.SwitchCurrentActionMap(_currentState);
}
public void Execute(PlayVideoCommand command)
+88 -8
View File
@@ -10,6 +10,7 @@ namespace Pal3.State
using System.IO;
using System.Linq;
using Actor;
using Audio;
using Camera;
using Command;
using Command.InternalCommands;
@@ -40,6 +41,7 @@ namespace Pal3.State
private readonly ScriptManager _scriptManager;
private readonly FavorManager _favorManager;
private readonly CameraManager _cameraManager;
private readonly AudioManager _audioManager;
private readonly PostProcessManager _postProcessManager;
private const string SAVE_FILE_NAME = "save.txt";
@@ -51,6 +53,7 @@ namespace Pal3.State
ScriptManager scriptManager,
FavorManager favorManager,
CameraManager cameraManager,
AudioManager audioManager,
PostProcessManager postProcessManager)
{
_sceneManager = sceneManager ?? throw new ArgumentNullException(nameof(sceneManager));
@@ -60,6 +63,7 @@ namespace Pal3.State
_scriptManager = scriptManager ?? throw new ArgumentNullException(nameof(scriptManager));
_favorManager = favorManager ?? throw new ArgumentNullException(nameof(favorManager));
_cameraManager = cameraManager != null ? cameraManager : throw new ArgumentNullException(nameof(cameraManager));
_audioManager = audioManager != null ? audioManager : throw new ArgumentNullException(nameof(audioManager));
_postProcessManager = postProcessManager != null ? postProcessManager : throw new ArgumentNullException(nameof(postProcessManager));
}
@@ -117,50 +121,126 @@ namespace Pal3.State
var commands = new List<ICommand>
{
new ResetGameStateCommand(),
new ResetGameStateCommand(), // Reset game state at first
};
// Save global variable(s)
commands.AddRange(varsToSave.Select(var =>
new ScriptVarSetValueCommand(var.Key, var.Value)));
var currentPlayerActorId = (int)_playerManager.GetPlayerActor();
// Save current playing script music (if any)
var currentScriptMusic = _audioManager.GetCurrentScriptMusic();
if (!string.IsNullOrEmpty(currentScriptMusic))
{
commands.Add(new PlayMusicCommand(currentScriptMusic, 0));
}
// Save current scene info and player actor state
commands.AddRange(new List<ICommand>()
{
new SceneLoadCommand(currentSceneInfo.CityName, currentSceneInfo.Name),
new ActorActivateCommand(ActorConstants.PlayerActorVirtualID, 1),
new ActorEnablePlayerControlCommand(ActorConstants.PlayerActorVirtualID),
new ActorActivateCommand(currentPlayerActorId, 1),
new ActorEnablePlayerControlCommand(currentPlayerActorId),
new PlayerEnableInputCommand(1),
new ActorSetNavLayerCommand(ActorConstants.PlayerActorVirtualID,
new ActorSetNavLayerCommand(currentPlayerActorId,
playerActorMovementController.GetCurrentLayerIndex()),
new ActorSetTilePositionCommand(ActorConstants.PlayerActorVirtualID,
playerActorTilePosition.x, playerActorTilePosition.y)
new ActorSetTilePositionCommand(currentPlayerActorId,
playerActorTilePosition.x, playerActorTilePosition.y),
new ActorRotateFacingCommand(currentPlayerActorId,
-(int)playerActorMovementController.gameObject.transform.rotation.eulerAngles.y)
});
// Save team state
commands.AddRange(_teamManager.GetActorsInTeam()
.Select(actorId => new TeamAddOrRemoveActorCommand((int) actorId, 1)));
if (saveLevel == SaveLevel.Full)
{
// Save favor info
commands.AddRange(_favorManager.GetAllActorFavorInfo()
.Select(favorInfo => new FavorAddCommand(favorInfo.Key, favorInfo.Value)));
.Select(favorInfo => new FavorAddCommand(favorInfo.Key, favorInfo.Value)));
// Save scene object activation state changed by the script
var allSceneObjects = currentScene.GetAllSceneObjects();
var allActivatedSceneObjects = currentScene.GetAllActivatedSceneObjects();
commands.AddRange(allActivatedSceneObjects
.Where(_ => allSceneObjects[_.Key].Info.Active == 0)
.Select(_ => new SceneActivateObjectCommand(_.Key, 1)));
commands.AddRange(allSceneObjects
.Where(_ => allSceneObjects[_.Key].Info.Active == 1)
.Where(_ => !allActivatedSceneObjects.Keys.Contains(_.Key))
.Select(_ => new SceneActivateObjectCommand(_.Key, 0)));
// Save actor activation state changed by the script
var playerActorIds = Enum.GetValues(typeof(PlayerActorId)).Cast<int>().ToList();
var allActors = currentScene.GetAllActors().Where(_ => !playerActorIds.Contains(_.Key)).ToArray();
var allActorGameObjects = currentScene.GetAllActorGameObjects();
commands.AddRange(allActors
.Where(_ => _.Value.Info.InitActive == 0)
.Where(_ => allActorGameObjects.ContainsKey(_.Key) &&
allActorGameObjects[_.Key].GetComponent<ActorController>().IsActive)
.Select(_ => new ActorActivateCommand(_.Key, 1)));
commands.AddRange(allActors
.Where(_ => _.Value.Info.InitActive == 1)
.Where(_ => allActorGameObjects.ContainsKey(_.Key) &&
!allActorGameObjects[_.Key].GetComponent<ActorController>().IsActive)
.Select(_ => new ActorActivateCommand(_.Key, 0)));
}
#if PAL3
// Save LongKui state
var longKuiCurrentMode = currentScene.GetActorGameObject((byte) PlayerActorId.LongKui)
.GetComponent<LongKuiController>()
.GetCurrentMode();
if (longKuiCurrentMode != 0)
{
commands.Add(new LongKuiSwitchModeCommand(longKuiCurrentMode));
}
// Save HuaYing state
var huaYingGameObject = currentScene.GetActorGameObject((byte) PlayerActorId.HuaYing);
var huaYingCurrentMode = huaYingGameObject.GetComponent<HuaYingController>().GetCurrentMode();
if (huaYingCurrentMode != 1)
{
commands.Add(new HuaYingSwitchBehaviourModeCommand(huaYingCurrentMode));
}
if (huaYingCurrentMode == 2 && huaYingGameObject.GetComponent<ActorController>().IsActive)
{
commands.Add(new ActorActivateCommand((int) PlayerActorId.HuaYing, 1));
var huaYingMovementController = huaYingGameObject.GetComponent<ActorMovementController>();
commands.Add(new ActorSetNavLayerCommand((int)PlayerActorId.HuaYing,
huaYingMovementController.GetCurrentLayerIndex()));
Vector2Int tilePosition = huaYingMovementController.GetTilePosition();
commands.Add(new ActorSetTilePositionCommand((int)PlayerActorId.HuaYing,
tilePosition.x,
tilePosition.y));
var rotationInDegrees = (int)huaYingGameObject.transform.rotation.eulerAngles.y;
commands.Add(new ActorRotateFacingCommand((int)PlayerActorId.HuaYing, -rotationInDegrees));
}
#endif
// Save big map region activation state
commands.AddRange(_bigMapManager.GetRegionEnablementInfo()
.Select(regionEnablement => new BigMapEnableRegionCommand(regionEnablement.Key, regionEnablement.Value)));
// Save current applied screen effect state
var currentEffectMode = _postProcessManager.GetCurrentAppliedEffectMode();
if (currentEffectMode != -1)
{
commands.Add(new EffectSetScreenEffectCommand(currentEffectMode));
}
// Save current applied camera settings
var defaultCameraTransformOption = _cameraManager.GetCurrentAppliedDefaultTransformOption();
if (defaultCameraTransformOption != 0)
{
commands.Add(new CameraSetDefaultTransformCommand(defaultCameraTransformOption));
}
// Good to have
commands.Add(new CameraFadeInCommand());
return commands;
}
}
+34 -35
View File
@@ -21,6 +21,7 @@ namespace Pal3.UI
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.DualShock;
using UnityEngine.UI;
public sealed class BigMapManager : MonoBehaviour,
@@ -66,6 +67,7 @@ namespace Pal3.UI
_playerInputActions.Gameplay.ToggleBigMap.performed += ToggleBigMapOnPerformed;
_playerInputActions.Cutscene.ToggleBigMap.performed += ToggleBigMapOnPerformed;
_playerInputActions.Cutscene.ExitCurrentShowingMenu.performed += HideBigMapOnPerformed;
}
private void OnEnable()
@@ -75,16 +77,24 @@ namespace Pal3.UI
private void OnDisable()
{
CommandExecutorRegistry<ICommand>.Instance.UnRegister(this);
_playerInputActions.Gameplay.ToggleBigMap.performed -= ToggleBigMapOnPerformed;
_playerInputActions.Cutscene.ToggleBigMap.performed -= ToggleBigMapOnPerformed;
CommandExecutorRegistry<ICommand>.Instance.UnRegister(this);
_playerInputActions.Cutscene.ExitCurrentShowingMenu.performed -= HideBigMapOnPerformed;
}
private void ToggleBigMapOnPerformed(InputAction.CallbackContext obj)
private void ToggleBigMapOnPerformed(InputAction.CallbackContext _)
{
ToggleBigMap();
}
private void HideBigMapOnPerformed(InputAction.CallbackContext _)
{
if (_isVisible)
{
Hide();
}
}
public bool IsVisible()
{
return _isVisible;
@@ -126,11 +136,17 @@ namespace Pal3.UI
_gameStateManager.GoToState(GameState.Cutscene);
GameObject exitButton = Instantiate(_bigMapRegionButtonPrefab, _bigMapCanvas.transform);
exitButton.GetComponentInChildren<TextMeshProUGUI>().text = "关闭";
exitButton.GetComponent<Button>().onClick
.AddListener(delegate { BigMapButtonClicked(-1);});
_selectionButtons.Add(exitButton);
GameObject exitButtonObj = Instantiate(_bigMapRegionButtonPrefab, _bigMapCanvas.transform);
var exitButtonTextUI = exitButtonObj.GetComponentInChildren<TextMeshProUGUI>();
exitButtonTextUI.text = "关闭";
exitButtonTextUI.fontStyle = FontStyles.Underline;
var exitButton = exitButtonObj.GetComponent<Button>();
Navigation exitButtonNavigation = exitButton.navigation;
exitButtonNavigation.mode = Navigation.Mode.Horizontal | Navigation.Mode.Vertical;
exitButton.navigation = exitButtonNavigation;
exitButton.colors = UITheme.GetButtonColors();
exitButton.onClick.AddListener(delegate { BigMapButtonClicked(-1);});
_selectionButtons.Add(exitButtonObj);
for (var i = 0; i < BigMapConstants.BigMapRegions.Length; i++)
{
@@ -140,45 +156,28 @@ namespace Pal3.UI
buttonTextUI.text = BigMapConstants.BigMapRegions[i];
var buttonIndex = i;
var button = selectionButton.GetComponent<Button>();
Navigation buttonNavigation = button.navigation;
buttonNavigation.mode = Navigation.Mode.Horizontal | Navigation.Mode.Vertical;
button.navigation = buttonNavigation;
button.colors = UITheme.GetButtonColors();
button.onClick.AddListener(delegate { BigMapButtonClicked(buttonIndex);});
_selectionButtons.Add(selectionButton);
}
// Setup button navigation
for (var i = 0; i < _selectionButtons.Count; i++)
{
var button = _selectionButtons[i].GetComponent<Button>();
Navigation buttonNavigation = button.navigation;
buttonNavigation.mode = Navigation.Mode.Explicit;
if (i == 0)
{
buttonNavigation.selectOnLeft = _selectionButtons[^1].GetComponent<Button>();
buttonNavigation.selectOnRight = _selectionButtons[i + 1].GetComponent<Button>();
}
else if (i == _selectionButtons.Count - 1)
{
buttonNavigation.selectOnLeft = _selectionButtons[i - 1].GetComponent<Button>();
buttonNavigation.selectOnRight = _selectionButtons[0].GetComponent<Button>();
}
else
{
buttonNavigation.selectOnLeft = _selectionButtons[i - 1].GetComponent<Button>();
buttonNavigation.selectOnRight = _selectionButtons[i + 1].GetComponent<Button>();
}
button.navigation = buttonNavigation;
}
var firstButton = _selectionButtons.First().GetComponent<Button>();
_eventSystem.firstSelectedGameObject = firstButton.gameObject;
InputDevice lastActiveInputDevice = _inputManager.GetLastActiveInputDevice();
if (lastActiveInputDevice == Keyboard.current ||
lastActiveInputDevice == Gamepad.current)
lastActiveInputDevice == Gamepad.current ||
lastActiveInputDevice == DualShockGamepad.current)
{
_eventSystem.firstSelectedGameObject = firstButton.gameObject;
firstButton.Select();
}
else
{
_eventSystem.firstSelectedGameObject = null;
}
if (_selectionButtons.Count > 0)
{
+2 -3
View File
@@ -17,13 +17,12 @@ namespace Pal3.UI
ICommandExecutor<ActiveInputDeviceChangedNotification>
{
private Texture2D _cursorTextureNormal;
private readonly CursorMode _cursorMode = CursorMode.Auto;
public void Init(GameResourceProvider gameResourceProvider)
{
gameResourceProvider = gameResourceProvider ?? throw new ArgumentNullException(nameof(gameResourceProvider));
_cursorTextureNormal = gameResourceProvider.GetCursorTexture();
Cursor.SetCursor(_cursorTextureNormal, Vector2.zero, _cursorMode);
Cursor.SetCursor(_cursorTextureNormal, Vector2.zero, CursorMode.Auto);
}
private void OnEnable()
+52 -28
View File
@@ -30,7 +30,8 @@ namespace Pal3.UI
ICommandExecutor<DialogueRenderActorAvatarCommand>,
ICommandExecutor<DialogueRenderTextCommand>,
ICommandExecutor<DialogueAddSelectionsCommand>,
ICommandExecutor<DialogueRenderTextWithTimeLimitCommand>
ICommandExecutor<DialogueRenderTextWithTimeLimitCommand>,
ICommandExecutor<ResetGameStateCommand>
{
private const float LIMIT_TIME_DIALOGUE_PLAYER_MAX_REACTION_TIME = 4f;
private const string INFORMATION_TEXT_COLOR_HEX = "#ffff05";
@@ -40,7 +41,6 @@ namespace Pal3.UI
private SceneManager _sceneManager;
private InputManager _inputManager;
private PlayerInputActions _inputActions;
private WaitUntilCanceled _skipDialogueWaiter;
private EventSystem _eventSystem;
private Canvas _dialogueCanvas;
@@ -63,7 +63,7 @@ namespace Pal3.UI
private readonly List<GameObject> _selectionButtons = new();
private double _totalTimeUsedBeforeSkippingTheLastDialogue;
private readonly Queue<DialogueRenderActorAvatarCommand> _avatarCommandQueue = new();
private DialogueRenderActorAvatarCommand _lastAvatarCommand;
private readonly Queue<IEnumerator> _dialogueRenderQueue = new();
public void Init(GameResourceProvider resourceProvider,
@@ -229,6 +229,7 @@ namespace Pal3.UI
public IEnumerator RenderDialogueAndWait(string text,
bool trackReactionTime,
WaitUntilCanceled waitUntilCanceled,
DialogueRenderActorAvatarCommand avatarCommand = null)
{
CommandDispatcher<ICommand>.Instance.Dispatch(new DialogueRenderingStartedNotification());
@@ -292,7 +293,7 @@ namespace Pal3.UI
}
ResetUI();
_skipDialogueWaiter?.CancelWait();
waitUntilCanceled.CancelWait();
_isDialoguePresenting = false;
}
@@ -382,7 +383,7 @@ namespace Pal3.UI
return newStr;
}
private void SkipDialoguePerformed(InputAction.CallbackContext obj)
private void SkipDialoguePerformed(InputAction.CallbackContext _)
{
if (_dialogueSelectionButtonsCanvas.enabled) return;
_isSkipDialogueRequested = true;
@@ -390,28 +391,27 @@ namespace Pal3.UI
public void Execute(DialogueRenderTextCommand command)
{
_skipDialogueWaiter?.CancelWait();
_skipDialogueWaiter = new WaitUntilCanceled(this);
CommandDispatcher<ICommand>.Instance.Dispatch(new ScriptRunnerWaitRequest(_skipDialogueWaiter));
DialogueRenderActorAvatarCommand avatarCommand =
_avatarCommandQueue.Count > 0 ? _avatarCommandQueue.Dequeue() : null;
_dialogueRenderQueue.Enqueue(RenderDialogueAndWait(GetDisplayText(command.DialogueText), false, avatarCommand));
var skipDialogueWaiter = new WaitUntilCanceled(this);
CommandDispatcher<ICommand>.Instance.Dispatch(new ScriptRunnerWaitRequest(skipDialogueWaiter));
DialogueRenderActorAvatarCommand avatarCommand = _lastAvatarCommand;
_dialogueRenderQueue.Enqueue(
RenderDialogueAndWait(GetDisplayText(command.DialogueText), false, skipDialogueWaiter, avatarCommand));
_lastAvatarCommand = null;
}
public void Execute(DialogueRenderTextWithTimeLimitCommand command)
{
_skipDialogueWaiter?.CancelWait();
_skipDialogueWaiter = new WaitUntilCanceled(this);
CommandDispatcher<ICommand>.Instance.Dispatch(new ScriptRunnerWaitRequest(_skipDialogueWaiter));
DialogueRenderActorAvatarCommand avatarCommand =
_avatarCommandQueue.Count > 0 ? _avatarCommandQueue.Dequeue() : null;
_dialogueRenderQueue.Enqueue(RenderDialogueAndWait(GetDisplayText(command.DialogueText), true, avatarCommand));
var skipDialogueWaiter = new WaitUntilCanceled(this);
CommandDispatcher<ICommand>.Instance.Dispatch(new ScriptRunnerWaitRequest(skipDialogueWaiter));
DialogueRenderActorAvatarCommand avatarCommand = _lastAvatarCommand;
_dialogueRenderQueue.Enqueue(RenderDialogueAndWait(GetDisplayText(command.DialogueText), true, skipDialogueWaiter, avatarCommand));
_lastAvatarCommand = null;
}
public void Execute(DialogueRenderActorAvatarCommand command)
{
if (command.ActorId == ActorConstants.PlayerActorVirtualID) return;
_avatarCommandQueue.Enqueue(command);
_lastAvatarCommand = command;
}
private string GetSelectionDisplayText(object selection)
@@ -428,6 +428,15 @@ namespace Pal3.UI
return selectionString[(selectionString.IndexOf('.') + 1)..];
}
}
if (selectionString.Contains('、'))
{
var numberStr = selectionString[..selectionString.IndexOf('、')];
if (int.TryParse(numberStr, out _))
{
return selectionString[(selectionString.IndexOf('、') + 1)..];
}
}
// I don't think there will be more than 20 options, so let's start with 20
for (var i = 20; i >= 0; i--)
@@ -445,7 +454,10 @@ namespace Pal3.UI
public void Execute(DialogueAddSelectionsCommand command)
{
_gameStateManager.GoToState(GameState.UI);
var waiter = new WaitUntilCanceled(this);
CommandDispatcher<ICommand>.Instance.Dispatch(new ScriptRunnerWaitRequest(waiter));
Transform canvasTransform = _dialogueSelectionButtonsCanvas.transform;
for (var i = 0; i < command.Selections.Count; i++)
{
@@ -453,8 +465,15 @@ namespace Pal3.UI
var buttonTextUI = selectionButton.GetComponentInChildren<TextMeshProUGUI>();
buttonTextUI.text = GetSelectionDisplayText(command.Selections[i]);
var buttonIndex = i;
selectionButton.GetComponentInChildren<Button>().onClick
.AddListener(delegate { SelectionButtonClicked(buttonIndex);});
var button = selectionButton.GetComponentInChildren<Button>();
button.colors = UITheme.GetButtonColors();
button.onClick
.AddListener(delegate
{
SelectionButtonClicked(buttonIndex);
waiter.CancelWait();
_gameStateManager.GoToPreviousState();
});
_selectionButtons.Add(selectionButton);
}
@@ -485,30 +504,35 @@ namespace Pal3.UI
}
var firstButton = _selectionButtons.First().GetComponentInChildren<Button>();
_eventSystem.firstSelectedGameObject = firstButton.gameObject;
InputDevice lastActiveInputDevice = _inputManager.GetLastActiveInputDevice();
if (lastActiveInputDevice == Keyboard.current ||
lastActiveInputDevice == Gamepad.current ||
lastActiveInputDevice == DualShockGamepad.current)
{
_eventSystem.firstSelectedGameObject = firstButton.gameObject;
firstButton.Select();
}
else
{
_eventSystem.firstSelectedGameObject = null;
}
_dialogueCanvas.enabled = true;
_dialogueSelectionButtonsCanvas.enabled = true;
_skipDialogueWaiter?.CancelWait();
_skipDialogueWaiter = new WaitUntilCanceled(this);
CommandDispatcher<ICommand>.Instance.Dispatch(new ScriptRunnerWaitRequest(_skipDialogueWaiter));
}
private void SelectionButtonClicked(int index)
{
_lastSelectedButtonIndex = index;
_skipDialogueWaiter?.CancelWait();
ResetUI();
_gameStateManager.GoToPreviousState();
}
public void Execute(ResetGameStateCommand command)
{
_lastAvatarCommand = null;
_dialogueRenderQueue.Clear();
ResetUI();
}
}
}
@@ -14,7 +14,7 @@ namespace Pal3.UI
using UnityEngine.InputSystem;
using UnityEngine.UI;
public sealed class TouchControlUIManager :
public sealed class TouchControlUIManager : IDisposable,
ICommandExecutor<GameStateChangedNotification>,
ICommandExecutor<ActiveInputDeviceChangedNotification>
{
@@ -68,13 +68,14 @@ namespace Pal3.UI
public void Dispose()
{
CommandExecutorRegistry<ICommand>.Instance.UnRegister(this);
if (_isTouchSupported)
{
_interactionButton.onClick.RemoveAllListeners();
_bigMapButton.onClick.RemoveAllListeners();
_storySelectionButton.onClick.RemoveAllListeners();
}
CommandExecutorRegistry<ICommand>.Instance.UnRegister(this);
}
public void Execute(GameStateChangedNotification command)
+36
View File
@@ -0,0 +1,36 @@
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
namespace Pal3.UI
{
using UnityEngine;
using UnityEngine.UI;
public static class UITheme
{
public static ColorBlock GetButtonColors()
{
#if PAL3
return new ColorBlock()
{
colorMultiplier = 1f,
normalColor = new Color(40f / 255f, 40f / 255f, 40f / 255f, 200f / 255f),
highlightedColor = new Color(30f / 255f, 75f / 255f, 140f / 255f, 200f / 255f),
pressedColor = new Color(20f / 255f, 50f / 255f, 100f / 255f, 200f / 255f),
selectedColor = new Color(30f / 255f, 75f / 255f, 140f / 255f, 200f / 255f),
};
#elif PAL3A
return new ColorBlock()
{
colorMultiplier = 1f,
normalColor = new Color(40f / 255f, 40f / 255f, 40f / 255f, 200f / 255f),
highlightedColor = new Color(160f / 255f, 40f / 255f, 110f / 255f, 200f / 255f),
pressedColor = new Color(110f / 255f, 25f / 255f, 75f / 255f, 200f / 255f),
selectedColor = new Color(160f / 255f, 40f / 255f, 110f / 255f, 200f / 255f),
};
#endif
}
}
}
+3
View File
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 4e5d025051a64b28b7df04efe6a5bdd1
timeCreated: 1664963601
+8 -2
View File
@@ -49,12 +49,18 @@ namespace Pal3.Video
private void OnDisable()
{
CommandExecutorRegistry<ICommand>.Instance.UnRegister(this);
_inputActions.VideoPlaying.SkipVideo.performed -= SkipVideoPerformed;
_videoPlayer.loopPointReached -= StopVideoInternal;
StopVideoInternal(_videoPlayer); // In case video is still playing
// In case video is still playing
_videoPlayer.Stop();
_videoPlayer.targetTexture.Release();
_videoPlayingWaiter?.CancelWait();
_videoPlayerUI.enabled = false;
}
private void SkipVideoPerformed(InputAction.CallbackContext obj)
private void SkipVideoPerformed(InputAction.CallbackContext _)
{
StopVideoInternal(_videoPlayer);
}
@@ -50,11 +50,11 @@ namespace ResourceViewer
private ICpkFileSystem _fileSystem;
private GameResourceProvider _resourceProvider;
private static IList<string> _polFiles = new List<string>();
private static IList<string> _cvdFiles = new List<string>();
private static IList<string> _mv3Files = new List<string>();
private static IList<string> _mp3Files = new List<string>();
private static IList<string> _sceFiles = new List<string>();
private IList<string> _polFiles = new List<string>();
private IList<string> _cvdFiles = new List<string>();
private IList<string> _mv3Files = new List<string>();
private IList<string> _mp3Files = new List<string>();
private IList<string> _sceFiles = new List<string>();
private static readonly Random Random = new ();
private const int GBK_CODE_PAGE = 936; // GBK Encoding's code page,
@@ -69,21 +69,9 @@ namespace ResourceViewer
_renderingRoot = new GameObject("Model");
_renderingRoot.transform.SetParent(null);
Application.targetFrameRate = Application.platform switch
{
RuntimePlatform.WindowsEditor => 120,
RuntimePlatform.WindowsPlayer => 120,
RuntimePlatform.OSXEditor => 120,
RuntimePlatform.OSXPlayer => 120,
RuntimePlatform.LinuxEditor => 120,
RuntimePlatform.LinuxPlayer => 120,
RuntimePlatform.IPhonePlayer => 60,
RuntimePlatform.Android => 60,
_ => -1,
};
Application.targetFrameRate = Screen.currentResolution.refreshRate;
if (Application.platform == RuntimePlatform.IPhonePlayer ||
Application.platform == RuntimePlatform.Android)
if (Application.platform is RuntimePlatform.IPhonePlayer or RuntimePlatform.Android)
{
DebugLogManager.Instance.PopupEnabled = true;
}
+16 -6
View File
@@ -11,7 +11,7 @@ Shader "Pal3/Standard"
_ShadowTex ("Shadow map (RGB)", 2D) = "white" {}
_Cutoff ("Alpha cutoff", Range(0,1)) = 0.0
_Exposure("Exposure Amount", Range(0.1,1.0)) = 0.4
_Transparency("Transparency Amount", Range(0.1,1.0)) = 1.0
_IsOpaque("Is Material Opaque", Range(0,1)) = 1.0
}
SubShader
{
@@ -54,7 +54,7 @@ Shader "Pal3/Standard"
float4 _ShadowTex_ST;
fixed _Cutoff;
float _Exposure;
float _Transparency;
float _IsOpaque;
v2f vert(appdata_t v)
{
@@ -71,15 +71,25 @@ Shader "Pal3/Standard"
half4 frag(v2f i) : SV_Target
{
half4 color = tex2D(_MainTex, i.texcoord);
const half alpha = color.a;
// Cutout
clip(color.a - _Cutoff);
// Shadow
color *= tex2D(_ShadowTex, i.shadowcoord) / (1 - _Exposure);
// Transparency
color.a = _Transparency;
// Preserve alpha or not
if (_IsOpaque == 1.0)
{
color.a = 1.0;
}
else
{
color.a = alpha;
}
UNITY_APPLY_FOG(i.fogCoord, color);
//UNITY_APPLY_FOG(i.fogCoord, color);
return color;
}
ENDCG
+16 -6
View File
@@ -10,7 +10,7 @@ Shader "Pal3/StandardNoShadow"
_MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
_Cutoff ("Alpha cutoff", Range(0,1)) = 0.0
_TintColor ("Tint color", Color) = (1.0, 1.0, 1.0, 1.0)
_Transparency("Transparency Amount", Range(0.1,1.0)) = 1.0
_IsOpaque("Is Material Opaque", Range(0,1)) = 1.0
}
SubShader
{
@@ -49,7 +49,7 @@ Shader "Pal3/StandardNoShadow"
float4 _MainTex_ST;
fixed _Cutoff;
half4 _TintColor;
float _Transparency;
float _IsOpaque;
v2f vert(appdata_t v)
{
@@ -65,15 +65,25 @@ Shader "Pal3/StandardNoShadow"
half4 frag(v2f i) : SV_Target
{
half4 color = tex2D(_MainTex, i.texcoord);
const half alpha = color.a;
// Cutout
clip(color.a - _Cutoff);
// Tint color
color *= _TintColor;
// Transparency
color.a = _Transparency;
// Preserve alpha or not
if (_IsOpaque == 1.0)
{
color.a = 1.0;
}
else
{
color.a = alpha;
}
UNITY_APPLY_FOG(i.fogCoord, color);
//UNITY_APPLY_FOG(i.fogCoord, color);
return color;
}
ENDCG
+11 -11
View File
@@ -42,8 +42,8 @@ PlayerSettings:
m_SplashScreenLogos: []
m_VirtualRealitySplashScreen: {fileID: 0}
m_HolographicTrackingLossScreen: {fileID: 0}
defaultScreenWidth: 1920
defaultScreenHeight: 1200
defaultScreenWidth: 1280
defaultScreenHeight: 800
defaultScreenWidthWeb: 960
defaultScreenHeightWeb: 600
m_StereoRenderingPath: 0
@@ -99,7 +99,7 @@ PlayerSettings:
xboxEnableFitness: 0
visibleInBackground: 1
allowFullscreenSwitch: 1
fullscreenMode: 3
fullscreenMode: 1
xboxSpeechDB: 0
xboxEnableHeadOrientation: 0
xboxEnableGuest: 0
@@ -134,7 +134,7 @@ PlayerSettings:
16:10: 1
16:9: 1
Others: 1
bundleVersion: 0.25
bundleVersion: 0.28
preloadedAssets: []
metroInputSource: 0
wsaTransparentSwapchain: 0
@@ -590,13 +590,13 @@ PlayerSettings:
m_Automatic: 1
- m_BuildTarget: MacStandaloneSupport
m_APIs: 10000000
m_Automatic: 1
m_Automatic: 0
- m_BuildTarget: LinuxStandaloneSupport
m_APIs: 1100000015000000
m_Automatic: 1
m_APIs: 1500000011000000
m_Automatic: 0
- m_BuildTarget: WindowsStandaloneSupport
m_APIs: 02000000
m_Automatic: 1
m_APIs: 0200000015000000
m_Automatic: 0
m_BuildTargetVRSettings:
- m_BuildTarget: Standalone
m_Enabled: 0
@@ -877,7 +877,7 @@ PlayerSettings:
webGLThreadsSupport: 0
webGLDecompressionFallback: 0
scriptingDefineSymbols:
Android: UNITY_POST_PROCESSING_STACK_V2;PAL3
Android: PAL3;UNITY_POST_PROCESSING_STACK_V2
CloudRendering: UNITY_POST_PROCESSING_STACK_V2
EmbeddedLinux: UNITY_POST_PROCESSING_STACK_V2
GameCoreXboxOne: UNITY_POST_PROCESSING_STACK_V2
@@ -886,7 +886,7 @@ PlayerSettings:
PS4: UNITY_POST_PROCESSING_STACK_V2
PS5: UNITY_POST_PROCESSING_STACK_V2
Stadia: UNITY_POST_PROCESSING_STACK_V2
Standalone: UNITY_POST_PROCESSING_STACK_V2;PAL3
Standalone: PAL3;UNITY_POST_PROCESSING_STACK_V2
WebGL: UNITY_POST_PROCESSING_STACK_V2
Windows Store Apps: UNITY_POST_PROCESSING_STACK_V2
XboxOne: UNITY_POST_PROCESSING_STACK_V2
+4 -3
View File
@@ -35,6 +35,8 @@
因为项目本身不含有仙剑奇侠传三或仙剑奇侠传三外传的游戏数据,所以你需要持有一份仙剑三或外传的游戏原始文件(Steam或者方块游戏获得皆可,注意:暂时仅支持简体版游戏)。
- 第一次打开Unity项目之后,先双击选择Scenes\Game作为当前场景,然后点播放键即可。如果选择Scenes\ResourceViewer,则会打开游戏资源查看器。
- 第一次打开的时候会自动弹出文件夹选择窗口,请选择当前电脑上仙剑奇侠传三(或者外传)的安装文件夹即可。
- 因为原始游戏的过场动画为Bink格式,Unity并不原生支持,所以请自行转码视频为Unity所支持的格式放在游戏根目录下的movie文件夹即可(大部分设备和系统支持.mp4等主流格式视频,Linux下仅支持.webm格式视频)。
* Linux用户可以使用FFmpeg转码视频为.webm格式封装(vp8 + vorbis):ffmpeg -i input.mp4 -c:v libvpx -b:v 3M -c:a libvorbis output.webm
## 如何在手持设备上运行
- 在打包后的运行时,所有平台都默认使用Application.persistentDataPath目录读取仙剑三文件,具体这个目录在哪里,根据平台决定,请阅读Unity文档:[Application.persistentDataPath](https://docs.unity3d.com/ScriptReference/Application-persistentDataPath.html)
@@ -62,9 +64,8 @@ https://www.bilibili.com/video/BV1Fu411R7jM
## 如何贡献?
因为项目还处于早期实现过程中,很多系统还没有实现,暂时不接受比较大的Pull request,特别是feature类型,如果您有好的想法,意见或者发现了Bug请欢迎提交issue或者加入交流群与我讨论。
另外您还可以参考这个项目解析视频:https://www.bilibili.com/video/BV1Pr4y167sF
## 技术交流以及测试
## 社区
仙剑三(及外传)复刻版讨论群:252315306
仙剑三(及外传)复刻版开发群:330680869