Compare commits
215 Commits
252853f4d4
...
0.5.2
Author | SHA1 | Date | |
---|---|---|---|
9f73c8ffad | |||
c1c354959d | |||
94428d9e18 | |||
5198ecec1f | |||
6779b88055 | |||
c5dab3a232 | |||
a7608bcd7e | |||
be64bc76b5 | |||
39bc34fd42 | |||
4185303bd2 | |||
3280693e8f | |||
29432feabc | |||
86559c681e | |||
79f11b9c33 | |||
5b9149cb34 | |||
9d6bdd968f | |||
bc4fec33ef | |||
09e917dbe8 | |||
1003a0e199 | |||
e3a805b855 | |||
4222176979 | |||
43c87fba70 | |||
d0a23aaf30 | |||
a09a5686d7 | |||
609bb317d0 | |||
898fb7d557 | |||
c39f258a19 | |||
4fdd4e1935 | |||
7662011d60 | |||
c24372b308 | |||
5e4c53113a | |||
4f93995bbd | |||
5b14466059 | |||
1d3aa85446 | |||
6efe70d751 | |||
555c88855c | |||
105aacc133 | |||
ea9000f2b0 | |||
4e851d9b73 | |||
0a1e512f41 | |||
a7baef2c9d | |||
723ec937ad | |||
7c77ba83f8 | |||
6da4b96b24 | |||
e8f8593555 | |||
2b5bc5dd08 | |||
cf6186aa16 | |||
4d7773a2ac | |||
e8f74399f2 | |||
ca72f7adb5 | |||
5e19a8b886 | |||
a416f772d4 | |||
989a6b5554 | |||
732af15d9b | |||
8cdab36cd6 | |||
44180c7e0f | |||
e589e37640 | |||
94107de97d | |||
13c55dc23e | |||
617eddc030 | |||
7475b19547 | |||
0049ace91a | |||
356f4df9a9 | |||
ff5928b556 | |||
1f0ac2a2e9 | |||
95628f07d1 | |||
3bead4f1b3 | |||
ec9b23f797 | |||
8175ca7e82 | |||
451ebbe91a | |||
da2313ab57 | |||
c5571e7d17 | |||
959157255f | |||
06d8012675 | |||
571320630b | |||
207dee9932 | |||
d7b0ca77e9 | |||
e55642cdeb | |||
595fd74662 | |||
3f7becf580 | |||
5d17555744 | |||
e6d94f248c | |||
b0c70bc62e | |||
8eb0b11027 | |||
7f2cfe94c1 | |||
e4524bda0b | |||
226fb15eb1 | |||
645c4af2f2 | |||
6e0f41c7fd | |||
b9001ed9b2 | |||
04abf59521 | |||
251f92532d | |||
f5df56687b | |||
b582da90e5 | |||
815f48fe06 | |||
1470fa87dd | |||
4b4356aaab | |||
a8658856ca | |||
1477e907e6 | |||
f559cea826 | |||
d363042036 | |||
69e4ecd0a9 | |||
35d2e06625 | |||
358e654f51 | |||
d16548e570 | |||
c7201dd62c | |||
e43a0e62b7 | |||
4bcf76819c | |||
31155c909c | |||
ab2670358a | |||
3da70bdccc | |||
e370e1937c | |||
d9f6dd33d4 | |||
e5d6e549bd | |||
145c0ce6c8 | |||
a0174b94c6 | |||
109b489104 | |||
784c3fc338 | |||
77d6ac2caf | |||
321af22775 | |||
39ef9815e8 | |||
bb3afba11f | |||
e4fa160a90 | |||
34df9e2257 | |||
cfdb5f021e | |||
d08eea5c1e | |||
ce30b5427b | |||
e38fed89e9 | |||
d4b12bf3f7 | |||
40d75a91c6 | |||
388a41cb55 | |||
3b23f78960 | |||
4fce8369f0 | |||
373554912a | |||
46039f6a12 | |||
9b872654d5 | |||
2c4ac3191c | |||
20632d9b54 | |||
28cad97bbb | |||
75652ecff1 | |||
1734cf9b72 | |||
5eb9786a7c | |||
16be67dc75 | |||
a7dfaa4558 | |||
3b65dbea5b | |||
3ed7e566dd | |||
f3549353f3 | |||
78bb820f9e | |||
b954dda676 | |||
1be5cc77ca | |||
bf942cbe45 | |||
79bfd6764c | |||
dcc92bb024 | |||
15e9217f93 | |||
79240fdfe8 | |||
678e145271 | |||
5cdf10874e | |||
777b7d9c34 | |||
34b17f3111 | |||
fd9e2ce409 | |||
cd8aa0e65c | |||
5240408f00 | |||
a7e6522a57 | |||
d89e5a2e68 | |||
05124ac406 | |||
a4fdb97424 | |||
735a85b914 | |||
be0c71702b | |||
535959a6ed | |||
ae37b27dc0 | |||
80cc5fdbda | |||
87e406e903 | |||
f04d0ec299 | |||
a19057f869 | |||
d0d981b790 | |||
c95ae92ba8 | |||
31e9f1352b | |||
9974b25377 | |||
852c93c6d0 | |||
15e66d29c4 | |||
3d5ea4f056 | |||
1772c90c2f | |||
53ada70dda | |||
a8ab73ac65 | |||
35ac57bfba | |||
945f9ca7d1 | |||
d2b2834a60 | |||
f82e0ce9ef | |||
5444ea7186 | |||
3a54d2023f | |||
cb3e3e5f28 | |||
174f616e5c | |||
0f8bb5f1f6 | |||
2d35e3177b | |||
7b1f639412 | |||
fcc9935325 | |||
8b29cd2893 | |||
f44d9546e1 | |||
1d1d2646c4 | |||
6444de41a2 | |||
ea856f3339 | |||
74b1a5485b | |||
975b48e61e | |||
9e0bf024d7 | |||
d2ff168e25 | |||
05664a2994 | |||
ba6166068b | |||
d5d6465806 | |||
1f57c299a2 | |||
49431e888c | |||
c31c16792c | |||
7ce73186ae | |||
318a6705be | |||
7fca09ff49 | |||
eff8dd2c35 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -61,6 +61,7 @@ crashlytics-build.properties
|
||||
#
|
||||
/Docs
|
||||
/Issues
|
||||
/Local
|
||||
/Obsolete
|
||||
/Snapshots
|
||||
/UI
|
||||
|
@@ -1,8 +0,0 @@
|
||||
using System.Reflection;
|
||||
|
||||
[assembly: AssemblyCompany("Cryville")]
|
||||
[assembly: AssemblyCopyright("Copyright © Cryville 2020-2022")]
|
||||
[assembly: AssemblyDefaultAlias("Cosmo Resona")]
|
||||
[assembly: AssemblyProduct("Cosmo Resona")]
|
||||
[assembly: AssemblyTitle("Cosmo Resona")]
|
||||
[assembly: AssemblyVersion("0.5.0")]
|
Binary file not shown.
120
Assets/Cryville/Common/Buffers/TargetString.cs
Normal file
120
Assets/Cryville/Common/Buffers/TargetString.cs
Normal file
@@ -0,0 +1,120 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Cryville.Common.Buffers {
|
||||
/// <summary>
|
||||
/// An auto-resized <see cref="char" /> array as a variable-length string used as a target that is modified frequently.
|
||||
/// </summary>
|
||||
public class TargetString : IEnumerable<char> {
|
||||
public event Action OnUpdate;
|
||||
char[] _arr;
|
||||
bool _invalidated;
|
||||
/// <summary>
|
||||
/// Creates an instance of the <see cref="TargetString" /> class with a capacity of 16.
|
||||
/// </summary>
|
||||
public TargetString() : this(16) { }
|
||||
/// <summary>
|
||||
/// Creates an instance of the <see cref="TargetString" /> class.
|
||||
/// </summary>
|
||||
/// <param name="capacity">The initial capacity of the string.</param>
|
||||
public TargetString(int capacity) {
|
||||
_arr = new char[capacity];
|
||||
}
|
||||
/// <summary>
|
||||
/// Gets or sets one of the characters in the string.
|
||||
/// </summary>
|
||||
/// <param name="index">The zero-based index of the character.</param>
|
||||
/// <returns>The character at the given index.</returns>
|
||||
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index" /> is less than 0 or not less than <see cref="Length" />.</exception>
|
||||
/// <remarks>
|
||||
/// <para>Set <see cref="Length" /> to a desired value before updating the characters.</para>
|
||||
/// <para>Call <see cref=" Validate" /> after all the characters are updated.</para>
|
||||
/// </remarks>
|
||||
public char this[int index] {
|
||||
get {
|
||||
if (index < 0 || index >= m_length)
|
||||
throw new ArgumentOutOfRangeException("index");
|
||||
return _arr[index];
|
||||
}
|
||||
set {
|
||||
if (index < 0 || index >= m_length)
|
||||
throw new ArgumentOutOfRangeException("index");
|
||||
if (_arr[index] == value) return;
|
||||
_arr[index] = value;
|
||||
_invalidated = true;
|
||||
}
|
||||
}
|
||||
int m_length;
|
||||
/// <summary>
|
||||
/// The length of the string.
|
||||
/// </summary>
|
||||
public int Length {
|
||||
get {
|
||||
return m_length;
|
||||
}
|
||||
set {
|
||||
if (m_length == value) return;
|
||||
if (_arr.Length < value) {
|
||||
var len = m_length;
|
||||
while (len < value) len *= 2;
|
||||
var arr2 = new char[len];
|
||||
Array.Copy(_arr, arr2, m_length);
|
||||
_arr = arr2;
|
||||
}
|
||||
m_length = value;
|
||||
_invalidated = true;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Validates the string.
|
||||
/// </summary>
|
||||
public void Validate() {
|
||||
if (!_invalidated) return;
|
||||
_invalidated = false;
|
||||
var ev = OnUpdate;
|
||||
if (ev != null) ev.Invoke();
|
||||
}
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator() {
|
||||
return GetEnumerator();
|
||||
}
|
||||
public IEnumerator<char> GetEnumerator() {
|
||||
return new Enumerator(this);
|
||||
}
|
||||
|
||||
class Enumerator : IEnumerator<char> {
|
||||
readonly TargetString _self;
|
||||
int _index = -1;
|
||||
public Enumerator(TargetString self) { _self = self; }
|
||||
|
||||
public char Current {
|
||||
get {
|
||||
if (_index < 0)
|
||||
throw new InvalidOperationException(_index == -1 ? "Enum not started" : "Enum ended");
|
||||
return _self[_index];
|
||||
}
|
||||
}
|
||||
|
||||
object IEnumerator.Current { get { return Current; } }
|
||||
|
||||
public void Dispose() {
|
||||
_index = -2;
|
||||
}
|
||||
|
||||
public bool MoveNext() {
|
||||
if (_index == -2) return false;
|
||||
_index++;
|
||||
if (_index >= _self.Length) {
|
||||
_index = -2;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Reset() {
|
||||
_index = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,5 +1,5 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d6a3a023271b82a4985d1bbcc86e6fa8
|
||||
guid: f0fc34ac257793d4883a9cfcdb6941b9
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
@@ -10,10 +10,10 @@ namespace Cryville.Common {
|
||||
/// </summary>
|
||||
public static IdentifierManager SharedInstance = new IdentifierManager();
|
||||
|
||||
Dictionary<object, int> _idents = new Dictionary<object, int>();
|
||||
List<object> _ids = new List<object>();
|
||||
readonly Dictionary<object, int> _idents = new Dictionary<object, int>();
|
||||
readonly List<object> _ids = new List<object>();
|
||||
|
||||
object _syncRoot = new object();
|
||||
readonly object _syncRoot = new object();
|
||||
|
||||
/// <summary>
|
||||
/// Creates an instance of the <see cref="IdentifierManager" /> class.
|
||||
|
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
|
||||
namespace Cryville.Common {
|
||||
@@ -17,7 +18,7 @@ namespace Cryville.Common {
|
||||
public static void SetLogPath(string path) {
|
||||
logPath = path;
|
||||
var dir = new DirectoryInfo(path);
|
||||
if (!dir.Exists) Directory.CreateDirectory(dir.FullName);
|
||||
if (!dir.Exists) dir.Create();
|
||||
}
|
||||
/// <summary>
|
||||
/// Logs to the specified logger.
|
||||
@@ -40,7 +41,7 @@ namespace Cryville.Common {
|
||||
public static void Create(string key, Logger logger) {
|
||||
Instances[key] = logger;
|
||||
if (logPath != null) {
|
||||
Files[key] = new StreamWriter(logPath + "/" + ((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "-" + key + ".log") {
|
||||
Files[key] = new StreamWriter(logPath + "/" + ((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds).ToString(CultureInfo.InvariantCulture) + "-" + key + ".log") {
|
||||
AutoFlush = true
|
||||
};
|
||||
}
|
||||
|
78
Assets/Cryville/Common/Math/FractionUtils.cs
Normal file
78
Assets/Cryville/Common/Math/FractionUtils.cs
Normal file
@@ -0,0 +1,78 @@
|
||||
using System;
|
||||
|
||||
namespace Cryville.Common.Math {
|
||||
/// <summary>
|
||||
/// Provides a set of <see langword="static" /> methods related to fractions.
|
||||
/// </summary>
|
||||
public static class FractionUtils {
|
||||
/// <summary>
|
||||
/// Converts a <see cref="double" /> decimal to a fraction.
|
||||
/// </summary>
|
||||
/// <param name="value">The decimal.</param>
|
||||
/// <param name="error">The error.</param>
|
||||
/// <param name="n">The numerator.</param>
|
||||
/// <param name="d">The denominator.</param>
|
||||
/// <exception cref="ArgumentOutOfRangeException"><paramref name="value" /> is less than 0 or <paramref name="error" /> is not greater than 0 or not less than 1.</exception>
|
||||
public static void ToFraction(double value, double error, out int n, out int d) {
|
||||
if (value < 0.0)
|
||||
throw new ArgumentOutOfRangeException("value", "Must be >= 0.");
|
||||
if (error <= 0.0 || error >= 1.0)
|
||||
throw new ArgumentOutOfRangeException("accuracy", "Must be > 0 and < 1.");
|
||||
|
||||
int num = (int)System.Math.Floor(value);
|
||||
value -= num;
|
||||
|
||||
if (value < error) { n = num; d = 1; return; }
|
||||
if (1 - error < value) { n = num + 1; d = 1; return; }
|
||||
|
||||
int lower_n = 0;
|
||||
int lower_d = 1;
|
||||
int upper_n = 1;
|
||||
int upper_d = 1;
|
||||
while (true) {
|
||||
int middle_n = lower_n + upper_n;
|
||||
int middle_d = lower_d + upper_d;
|
||||
|
||||
if (middle_d * (value + error) < middle_n) {
|
||||
upper_n = middle_n;
|
||||
upper_d = middle_d;
|
||||
}
|
||||
else if (middle_n < (value - error) * middle_d) {
|
||||
lower_n = middle_n;
|
||||
lower_d = middle_d;
|
||||
}
|
||||
else {
|
||||
n = num * middle_d + middle_n;
|
||||
d = middle_d;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the greatest common divisor (GCD) of two integers.
|
||||
/// </summary>
|
||||
/// <param name="n">The first integer.</param>
|
||||
/// <param name="d">The second integer.</param>
|
||||
/// <returns>The greatest common divisor (GCD) of the two integers.</returns>
|
||||
public static int GreatestCommonDivisor(int n, int d) {
|
||||
while (d != 0) {
|
||||
int t = d;
|
||||
d = n % d;
|
||||
n = t;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Simplifies a fraction.
|
||||
/// </summary>
|
||||
/// <param name="n">The numerator.</param>
|
||||
/// <param name="d">The denominator.</param>
|
||||
public static void Simplify(ref int n, ref int d) {
|
||||
var gcd = GreatestCommonDivisor(n, d);
|
||||
n /= gcd;
|
||||
d /= gcd;
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,5 +1,5 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a69a6c726b01961419c4835bba37a218
|
||||
guid: 6829ada596979a545a935785eeea2972
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
@@ -1,9 +1,13 @@
|
||||
namespace Cryville.Common.Math {
|
||||
using System;
|
||||
|
||||
namespace Cryville.Common.Math {
|
||||
/// <summary>
|
||||
/// Represents a square matrix.
|
||||
/// </summary>
|
||||
public class SquareMatrix {
|
||||
readonly float[,] content;
|
||||
readonly float[,] buffer;
|
||||
readonly int[] refl;
|
||||
/// <summary>
|
||||
/// The size of the matrix.
|
||||
/// </summary>
|
||||
@@ -17,6 +21,8 @@
|
||||
/// <param name="size">The size of the matrix.</param>
|
||||
public SquareMatrix(int size) {
|
||||
content = new float[size, size];
|
||||
buffer = new float[size, size];
|
||||
refl = new int[size];
|
||||
Size = size;
|
||||
}
|
||||
/// <summary>
|
||||
@@ -38,38 +44,36 @@
|
||||
/// <returns>The column vector eliminated.</returns>
|
||||
public ColumnVector<T> Eliminate<T>(ColumnVector<T> v, IVectorOperator<T> o) {
|
||||
int s = Size;
|
||||
float[,] d = (float[,])content.Clone();
|
||||
int[] refl = new int[s];
|
||||
for (int i = 0; i < s; i++)
|
||||
refl[i] = i;
|
||||
Array.Copy(content, buffer, Size * Size);
|
||||
for (int i = 0; i < s; i++) refl[i] = i;
|
||||
for (int r = 0; r < s; r++) {
|
||||
for (int r0 = r; r0 < s; r0++)
|
||||
if (d[refl[r0], r] != 0) {
|
||||
if (buffer[refl[r0], r] != 0) {
|
||||
refl[r] = r0;
|
||||
refl[r0] = r;
|
||||
break;
|
||||
}
|
||||
int or = refl[r];
|
||||
float sf0 = d[or, r];
|
||||
float sf0 = buffer[or, r];
|
||||
for (int c0 = r; c0 < s; c0++)
|
||||
d[or, c0] /= sf0;
|
||||
buffer[or, c0] /= sf0;
|
||||
v[or] = o.ScalarMultiply(1 / sf0, v[or]);
|
||||
for (int r1 = r + 1; r1 < s; r1++) {
|
||||
int or1 = refl[r1];
|
||||
float sf1 = d[or1, r];
|
||||
float sf1 = buffer[or1, r];
|
||||
for (int c1 = r; c1 < s; c1++)
|
||||
d[or1, c1] -= d[or, c1] * sf1;
|
||||
buffer[or1, c1] -= buffer[or, c1] * sf1;
|
||||
v[or1] = o.Add(v[or1], o.ScalarMultiply(-sf1, v[or]));
|
||||
}
|
||||
}
|
||||
T[] res = new T[s];
|
||||
ColumnVector<T> res = new ColumnVector<T>(s);
|
||||
for (int r2 = s - 1; r2 >= 0; r2--) {
|
||||
var v2 = v[refl[r2]];
|
||||
for (int c2 = r2 + 1; c2 < s; c2++)
|
||||
v2 = o.Add(v2, o.ScalarMultiply(-d[refl[r2], c2], res[refl[c2]]));
|
||||
v2 = o.Add(v2, o.ScalarMultiply(-buffer[refl[r2], c2], res[refl[c2]]));
|
||||
res[refl[r2]] = v2;
|
||||
}
|
||||
return new ColumnVector<T>(res);
|
||||
return res;
|
||||
}
|
||||
/// <summary>
|
||||
/// Creates a square matrix and fills it with polynomial coefficients.
|
||||
|
@@ -77,7 +77,7 @@ namespace Cryville.Common.Network {
|
||||
encoding = Encoding.UTF8;
|
||||
payload = encoding.GetBytes(body);
|
||||
headers.Add("Content-Encoding", encoding.EncodingName);
|
||||
headers.Add("Content-Length", payload.Length.ToString());
|
||||
headers.Add("Content-Length", payload.Length.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
string request_line = string.Format(
|
||||
"{0} {1} {2}\r\n", method, uri, Version
|
||||
|
@@ -19,9 +19,7 @@ namespace Cryville.Common.Network {
|
||||
set { throw new NotSupportedException(); }
|
||||
}
|
||||
|
||||
public override void Flush() {
|
||||
// Do nothing
|
||||
}
|
||||
public override void Flush() { }
|
||||
|
||||
public abstract byte[] ReadToEnd();
|
||||
|
||||
|
@@ -28,7 +28,7 @@ namespace Cryville.Common.Network {
|
||||
}
|
||||
|
||||
private class InternalTlsClient : DefaultTlsClient {
|
||||
string _host;
|
||||
readonly string _host;
|
||||
|
||||
public InternalTlsClient(string host, TlsCrypto crypto) : base(crypto) {
|
||||
_host = host;
|
||||
@@ -92,9 +92,7 @@ namespace Cryville.Common.Network {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void NotifyServerCertificate(TlsServerCertificate serverCertificate) {
|
||||
// Do nothing
|
||||
}
|
||||
public void NotifyServerCertificate(TlsServerCertificate serverCertificate) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace Cryville.Common.Pdt {
|
||||
/// <summary>
|
||||
@@ -34,6 +35,16 @@ namespace Cryville.Common.Pdt {
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Patches an expression with a lefthand variable and a compound operator.
|
||||
/// </summary>
|
||||
/// <param name="target">The name of the lefthand variable.</param>
|
||||
/// <param name="op">The name of the compound operator.</param>
|
||||
/// <param name="exp">The expression.</param>
|
||||
public void PatchCompound(int target, int op, PdtExpression exp) {
|
||||
exp.Instructions.AddFirst(new PdtInstruction.PushVariable(target));
|
||||
exp.Instructions.AddLast(new PdtInstruction.Operate(op, 2));
|
||||
}
|
||||
/// <summary>
|
||||
/// Optimizes an expression by merging its instructions.
|
||||
/// </summary>
|
||||
/// <param name="exp">The expression to optimize.</param>
|
||||
@@ -94,7 +105,7 @@ namespace Cryville.Common.Pdt {
|
||||
else if (i is PdtInstruction.PushVariable) {
|
||||
i.Execute(this);
|
||||
var frame = _stack[_framecount - 1];
|
||||
if (frame.Type != PdtInternalType.Undefined) {
|
||||
if (frame.Type != PdtInternalType.Undefined && frame.Type != PdtInternalType.Error) {
|
||||
_rip = il.AddAfter(_rip, new PdtInstruction.PushConstant(frame.Type, _mem, frame.Offset, frame.Length));
|
||||
il.Remove(_rip.Previous);
|
||||
}
|
||||
@@ -137,10 +148,10 @@ namespace Cryville.Common.Pdt {
|
||||
_goffset += value.Length;
|
||||
}
|
||||
}
|
||||
internal unsafe void PushVariable(int name) {
|
||||
internal unsafe void PushVariable(int name, bool forced) {
|
||||
fixed (StackFrame* frame = &_stack[_framecount++]) {
|
||||
byte[] value;
|
||||
GetVariable(name, out frame->Type, out value);
|
||||
GetVariable(name, forced, out frame->Type, out value);
|
||||
frame->Offset = _goffset;
|
||||
frame->Length = value.Length;
|
||||
Array.Copy(value, 0, _mem, _goffset, value.Length);
|
||||
@@ -151,16 +162,17 @@ namespace Cryville.Common.Pdt {
|
||||
/// Gets a variable of the specified name.
|
||||
/// </summary>
|
||||
/// <param name="name">The name of the variable.</param>
|
||||
/// <param name="forced">Whether to produce an error stack instead of an identifier stack if the variable is not found.</param>
|
||||
/// <param name="type">The type of the variable.</param>
|
||||
/// <param name="value">The value of the variable.</param>
|
||||
protected abstract void GetVariable(int name, out int type, out byte[] value);
|
||||
protected abstract void GetVariable(int name, bool forced, out int type, out byte[] value);
|
||||
internal void Operate(PdtOperatorSignature sig) {
|
||||
PdtOperator op;
|
||||
try { op = GetOperator(sig); }
|
||||
catch (Exception) {
|
||||
catch (Exception ex) {
|
||||
for (int i = 0; i < sig.ParamCount; i++)
|
||||
DiscardStack();
|
||||
throw;
|
||||
throw new EvaluationFailureException(string.Format("Failed to get operator {0}", sig), ex);
|
||||
}
|
||||
Operate(op, sig.ParamCount);
|
||||
}
|
||||
@@ -212,4 +224,18 @@ namespace Cryville.Common.Pdt {
|
||||
_goffset -= _stack[--_framecount].Length;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The exception that is thrown when the evalution of a <see cref="PdtExpression" /> fails.
|
||||
/// </summary>
|
||||
public class EvaluationFailureException : Exception {
|
||||
/// <inheritdoc />
|
||||
public EvaluationFailureException() : base("Evaluation failed") { }
|
||||
/// <inheritdoc />
|
||||
public EvaluationFailureException(string message) : base(message) { }
|
||||
/// <inheritdoc />
|
||||
public EvaluationFailureException(string message, Exception innerException) : base(message, innerException) { }
|
||||
/// <inheritdoc />
|
||||
protected EvaluationFailureException(SerializationInfo info, StreamingContext context) : base(info, context) { }
|
||||
}
|
||||
}
|
||||
|
@@ -51,18 +51,21 @@ namespace Cryville.Common.Pdt {
|
||||
}
|
||||
public class PushVariable : PdtInstruction {
|
||||
public int Name { get; private set; }
|
||||
public PushVariable(string name) {
|
||||
Name = IdentifierManager.SharedInstance.Request(name);
|
||||
}
|
||||
public bool Forced { get; private set; }
|
||||
public PushVariable(int name, bool forced = false) { Name = name; Forced = forced; }
|
||||
public PushVariable(string name, bool forced = false) : this(IdentifierManager.SharedInstance.Request(name)) { Forced = forced; }
|
||||
internal override void Execute(PdtEvaluatorBase etor) {
|
||||
etor.PushVariable(Name);
|
||||
etor.PushVariable(Name, Forced);
|
||||
}
|
||||
public override string ToString() {
|
||||
return string.Format("pushv {0}", IdentifierManager.SharedInstance.Retrieve(Name));
|
||||
return string.Format(Forced ? "pushv ?{0}" : "pushv {0}", IdentifierManager.SharedInstance.Retrieve(Name));
|
||||
}
|
||||
}
|
||||
public class Operate : PdtInstruction {
|
||||
public PdtOperatorSignature Signature { get; private set; }
|
||||
public Operate(int name, int paramCount) {
|
||||
Signature = new PdtOperatorSignature(name, paramCount);
|
||||
}
|
||||
public Operate(string name, int paramCount) {
|
||||
Signature = new PdtOperatorSignature(name, paramCount);
|
||||
}
|
||||
@@ -237,7 +240,11 @@ namespace Cryville.Common.Pdt {
|
||||
if (defs.TryGetValue(buf.Value.Value, out def)) {
|
||||
foreach (var i in def.Instructions) ins.AddLast(i);
|
||||
}
|
||||
else ins.AddLast(new PdtInstruction.PushVariable(buf.Value.Value));
|
||||
else {
|
||||
var name = buf.Value.Value;
|
||||
if (name[0] == '?') ins.AddLast(new PdtInstruction.PushVariable(name.Substring(1), true));
|
||||
else ins.AddLast(new PdtInstruction.PushVariable(name));
|
||||
}
|
||||
buf = null;
|
||||
TryPushAdjMul(ins, ref flag);
|
||||
}
|
||||
|
@@ -32,7 +32,7 @@ namespace Cryville.Common.Pdt {
|
||||
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0001, 0x0000, 0x0000, 0x0001, 0x0000, 0x0000,
|
||||
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
|
||||
0x0001, 0x0080, 0x0100, 0x0000, 0x0030, 0x0080, 0x0080, 0x0000, 0x0200, 0x0400, 0x0080, 0x0080, 0x0080, 0x0080, 0x0040, 0x0080,
|
||||
0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x1000, 0x1800, 0x0080, 0x0080, 0x0080, 0x0000,
|
||||
0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x1000, 0x1800, 0x0080, 0x0080, 0x0080, 0x0030,
|
||||
0x0080, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030,
|
||||
0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0000, 0x0000, 0x0000, 0x0000, 0x0030,
|
||||
0x0000, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030,
|
||||
|
@@ -19,7 +19,8 @@ namespace Cryville.Common.Pdt {
|
||||
/// <returns>The operand at the specified index.</returns>
|
||||
/// <exception cref="IndexOutOfRangeException"><paramref name="index" /> is not less than <see cref="LoadedOperandCount" /> or less than 0.</exception>
|
||||
protected PdtVariableMemory GetOperand(int index) {
|
||||
if (index >= LoadedOperandCount || index < 0) throw new IndexOutOfRangeException();
|
||||
if (index >= LoadedOperandCount || index < 0)
|
||||
throw new ArgumentOutOfRangeException("index");
|
||||
int i = index + _loadindex;
|
||||
return _operands[i];
|
||||
}
|
||||
@@ -33,11 +34,9 @@ namespace Cryville.Common.Pdt {
|
||||
_operands = new PdtVariableMemory[pc];
|
||||
}
|
||||
PdtEvaluatorBase _etor;
|
||||
bool _failure = false;
|
||||
bool _rfreq = true;
|
||||
internal void Begin(PdtEvaluatorBase etor) {
|
||||
_etor = etor;
|
||||
_failure = false;
|
||||
_loadindex = ParamCount;
|
||||
}
|
||||
internal void LoadOperand(PdtVariableMemory mem) {
|
||||
@@ -49,13 +48,9 @@ namespace Cryville.Common.Pdt {
|
||||
_rfreq = false;
|
||||
try { Execute(); } catch (Exception ex) {
|
||||
if (_rfreq) _etor.DiscardStack();
|
||||
throw new InvalidOperationException("Evaluation failed", ex);
|
||||
throw new EvaluationFailureException("Evaluation failed", ex);
|
||||
}
|
||||
if (_failure) {
|
||||
if (_rfreq) _etor.DiscardStack();
|
||||
throw new InvalidOperationException("Evaluation failed");
|
||||
}
|
||||
if (!_rfreq && !noset) throw new InvalidOperationException("Return frame not set");
|
||||
if (!_rfreq && !noset) throw new EvaluationFailureException("Return frame not set");
|
||||
}
|
||||
/// <summary>
|
||||
/// Executes the operator.
|
||||
@@ -69,10 +64,7 @@ namespace Cryville.Common.Pdt {
|
||||
/// <returns>The return frame.</returns>
|
||||
/// <exception cref="InvalidOperationException">The return frame has already been requested.</exception>
|
||||
protected PdtVariableMemory GetReturnFrame(int type, int len) {
|
||||
if (_rfreq) {
|
||||
_failure = true;
|
||||
throw new InvalidOperationException("Return frame already requested");
|
||||
}
|
||||
if (_rfreq) throw new InvalidOperationException("Return frame requested twice");
|
||||
_rfreq = true;
|
||||
return _etor.StackAlloc(type, _prmem, len);
|
||||
}
|
||||
|
@@ -4,7 +4,7 @@ namespace Cryville.Common.Pdt {
|
||||
/// <summary>
|
||||
/// Span on the memory of a <see cref="PdtEvaluatorBase" />.
|
||||
/// </summary>
|
||||
public unsafe struct PdtVariableMemory {
|
||||
public unsafe struct PdtVariableMemory : IEquatable<PdtVariableMemory> {
|
||||
readonly byte* _ptr;
|
||||
/// <summary>
|
||||
/// The length of the span.
|
||||
@@ -46,6 +46,14 @@ namespace Cryville.Common.Pdt {
|
||||
for (int i = 0; i < length; i++)
|
||||
dest[destOffset + i] = _ptr[i];
|
||||
}
|
||||
/// <inheritdoc />
|
||||
public bool Equals(PdtVariableMemory obj) {
|
||||
if (Type != obj.Type || Length != obj.Length) return false;
|
||||
for (int i = 0; i < Length; i++) {
|
||||
if (*(_ptr + i) != *(obj._ptr + i)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/// <summary>
|
||||
/// Gets the memory of the span as a number.
|
||||
/// </summary>
|
||||
|
@@ -1,49 +0,0 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
|
||||
namespace Cryville.Common.Plist {
|
||||
public class PlistConvert {
|
||||
public static T Deserialize<T>(string file) {
|
||||
return (T)Deserialize(typeof(T), PlistCS.Plist.readPlist(file));
|
||||
}
|
||||
|
||||
public static object Deserialize(Type type, object obj, Binder binder = null) {
|
||||
if (binder == null)
|
||||
binder = BinderAttribute.CreateBinderOfType(type);
|
||||
if (obj is IList) {
|
||||
var lobj = (List<object>)obj;
|
||||
foreach (var i in lobj) {
|
||||
throw new NotImplementedException(); // TODO
|
||||
}
|
||||
}
|
||||
else if (obj is IDictionary) {
|
||||
var dobj = (Dictionary<string, object>)obj;
|
||||
if (typeof(IDictionary).IsAssignableFrom(type)) {
|
||||
var result = (IDictionary)ReflectionHelper.InvokeEmptyConstructor(type);
|
||||
var it = type.GetGenericArguments()[1];
|
||||
foreach (var i in dobj) {
|
||||
var value = Deserialize(it, i.Value, binder);
|
||||
result.Add(i.Key, value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
else {
|
||||
var result = ReflectionHelper.InvokeEmptyConstructor(type);
|
||||
foreach (var i in dobj) {
|
||||
var imis = type.GetMember(i.Key);
|
||||
if (imis.Length == 0) continue;
|
||||
var imi = imis[0];
|
||||
var it = ReflectionHelper.GetMemberType(imi);
|
||||
var value = Deserialize(it, i.Value, binder);
|
||||
ReflectionHelper.SetValue(imi, result, value, binder);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
else return obj;
|
||||
throw new Exception(); // TODO
|
||||
}
|
||||
}
|
||||
}
|
@@ -145,7 +145,7 @@ namespace Cryville.Common {
|
||||
/// <returns>An array containing all the subclasses of the type in the current app domain.</returns>
|
||||
public static Type[] GetSubclassesOf<T>() where T : class {
|
||||
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
|
||||
IEnumerable<Type> r = new List<Type>();
|
||||
IEnumerable<Type> r = Enumerable.Empty<Type>();
|
||||
foreach (var a in assemblies)
|
||||
r = r.Concat(a.GetTypes().Where(
|
||||
t => t.IsClass
|
||||
@@ -168,5 +168,19 @@ namespace Cryville.Common {
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the namespace qualified name of a type.
|
||||
/// </summary>
|
||||
/// <param name="type">The type.</param>
|
||||
/// <returns>The namespace qualified name of the class.</returns>
|
||||
public static string GetNamespaceQualifiedName(Type type) {
|
||||
string result = type.Namespace + "." + type.Name;
|
||||
var typeargs = type.GetGenericArguments();
|
||||
if (typeargs.Length > 0) {
|
||||
result = string.Format("{0}[{1}]", result, string.Join(",", from a in typeargs select GetNamespaceQualifiedName(a)));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -40,7 +40,25 @@ namespace Cryville.Common {
|
||||
/// <param name="name">The file name excluding the extension.</param>
|
||||
/// <returns>The escaped file name.</returns>
|
||||
public static string EscapeFileName(string name) {
|
||||
return Regex.Replace(name, @"[\/\\\<\>\:\x22\|\?\*\p{Cc}\.\s]", "_");
|
||||
var result = Regex.Replace(name, @"[\/\\\<\>\:\x22\|\?\*\p{Cc}]", "_").TrimEnd(' ', '.');
|
||||
if (result.Length == 0) return "_";
|
||||
return result;
|
||||
}
|
||||
/// <summary>
|
||||
/// Gets the process path from a command.
|
||||
/// </summary>
|
||||
/// <param name="command">The command.</param>
|
||||
/// <returns>The process path.</returns>
|
||||
public static string GetProcessPathFromCommand(string command) {
|
||||
command = command.Trim();
|
||||
if (command[0] == '"') {
|
||||
return command.Substring(1, command.IndexOf('"', 1) - 1);
|
||||
}
|
||||
else {
|
||||
int e = command.IndexOf(' ');
|
||||
if (e == -1) return command;
|
||||
else return command.Substring(0, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -9,14 +9,6 @@ namespace Cryville.Common.Unity {
|
||||
return (num2 & num) == num;
|
||||
}
|
||||
|
||||
public static void ShowException(Exception ex) {
|
||||
ShowMessageBox(ex.ToString());
|
||||
}
|
||||
|
||||
public static void ShowMessageBox(string message) {
|
||||
GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("Common/Popup")).GetComponent<Popup>().Message = message;
|
||||
}
|
||||
|
||||
public static void Purge(Transform obj) {
|
||||
foreach (Transform i in obj)
|
||||
GameObject.Destroy(i.gameObject);
|
||||
|
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
@@ -11,13 +12,13 @@ namespace Cryville.Common.Unity {
|
||||
Transform dirs;
|
||||
Transform files;
|
||||
|
||||
public Action Callback { private get; set; }
|
||||
public event Action OnClose;
|
||||
|
||||
#if UNITY_ANDROID && !UNITY_EDITOR_WIN
|
||||
string androidStorage = "";
|
||||
#endif
|
||||
|
||||
string fileName = "";
|
||||
string fileName = null;
|
||||
public string FileName {
|
||||
get { return fileName; }
|
||||
}
|
||||
@@ -27,8 +28,16 @@ namespace Cryville.Common.Unity {
|
||||
set { m_filter = value; }
|
||||
}
|
||||
|
||||
#pragma warning disable IDE0051
|
||||
public Dictionary<string, string> m_presetPaths = new Dictionary<string, string>();
|
||||
public Dictionary<string, string> PresetPaths {
|
||||
get { return m_presetPaths; }
|
||||
set { m_presetPaths = value; }
|
||||
}
|
||||
|
||||
GameObject prefabButton;
|
||||
|
||||
void Start() {
|
||||
prefabButton = Resources.Load<GameObject>("Common/Button");
|
||||
panel = gameObject.transform.Find("Panel");
|
||||
title = panel.Find("Title/Text");
|
||||
drives = panel.Find("Drives/DrivesInner");
|
||||
@@ -38,8 +47,8 @@ namespace Cryville.Common.Unity {
|
||||
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
|
||||
CurrentDirectory = new DirectoryInfo(Directory.GetCurrentDirectory());
|
||||
#elif UNITY_ANDROID
|
||||
using (AndroidJavaClass ajc=new AndroidJavaClass("android.os.Environment"))
|
||||
using (AndroidJavaObject file=ajc.CallStatic<AndroidJavaObject>("getExternalStorageDirectory")) {
|
||||
using (AndroidJavaClass ajc = new AndroidJavaClass("android.os.Environment"))
|
||||
using (AndroidJavaObject file = ajc.CallStatic<AndroidJavaObject>("getExternalStorageDirectory")) {
|
||||
androidStorage = file.Call<string>("getAbsolutePath");
|
||||
CurrentDirectory = new DirectoryInfo(androidStorage);
|
||||
}
|
||||
@@ -47,9 +56,8 @@ namespace Cryville.Common.Unity {
|
||||
#error No default directory
|
||||
#endif
|
||||
}
|
||||
UpdateGUI();
|
||||
UpdateGUI(0);
|
||||
}
|
||||
#pragma warning restore IDE0051
|
||||
|
||||
public void Show() {
|
||||
fileName = null;
|
||||
@@ -57,85 +65,82 @@ namespace Cryville.Common.Unity {
|
||||
}
|
||||
|
||||
public void Close() {
|
||||
if (Callback != null) Callback.Invoke();
|
||||
var ev = OnClose;
|
||||
if (ev != null) ev.Invoke();
|
||||
gameObject.SetActive(false);
|
||||
}
|
||||
|
||||
public DirectoryInfo CurrentDirectory;
|
||||
|
||||
void OnDriveChanged(string s) {
|
||||
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
|
||||
CurrentDirectory = new DirectoryInfo(s);
|
||||
#elif UNITY_ANDROID
|
||||
switch (s) {
|
||||
case "?storage":
|
||||
CurrentDirectory = new DirectoryInfo(androidStorage);
|
||||
break;
|
||||
}
|
||||
#else
|
||||
#error No change drive logic
|
||||
#endif
|
||||
UpdateGUI();
|
||||
void ChangeDirectory(DirectoryInfo s) {
|
||||
CurrentDirectory = s;
|
||||
UpdateGUI(1);
|
||||
}
|
||||
|
||||
void OnDirectoryChanged(string s) {
|
||||
CurrentDirectory = new DirectoryInfo(CurrentDirectory.FullName + "/" + s);
|
||||
UpdateGUI();
|
||||
}
|
||||
|
||||
void OnFileChanged(string s) {
|
||||
void SelectFile(string s) {
|
||||
fileName = s;
|
||||
Close();
|
||||
}
|
||||
|
||||
void UpdateGUI() {
|
||||
void UpdateGUI(int depth) {
|
||||
title.GetComponent<Text>().text = CurrentDirectory.FullName;
|
||||
|
||||
CallHelper.Purge(drives);
|
||||
if (depth <= 0) {
|
||||
CallHelper.Purge(drives);
|
||||
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
|
||||
var dl = Directory.GetLogicalDrives();
|
||||
foreach (string d in dl) {
|
||||
GameObject btn = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("Common/Button"));
|
||||
btn.GetComponentInChildren<Text>().text = d;
|
||||
var ts = d;
|
||||
btn.GetComponentInChildren<Button>().onClick.AddListener(() => OnDriveChanged(ts));
|
||||
btn.transform.SetParent(drives, false);
|
||||
}
|
||||
var dl = Directory.GetLogicalDrives();
|
||||
foreach (string d in dl) {
|
||||
GameObject btn = Instantiate(prefabButton);
|
||||
btn.GetComponentInChildren<Text>().text = d;
|
||||
btn.GetComponentInChildren<Button>().onClick.AddListener(() => ChangeDirectory(new DirectoryInfo(d)));
|
||||
btn.transform.SetParent(drives, false);
|
||||
}
|
||||
#elif UNITY_ANDROID
|
||||
GameObject sbtn = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("Common/Button"));
|
||||
sbtn.GetComponentInChildren<Text>().text = "Storage";
|
||||
sbtn.GetComponentInChildren<Button>().onClick.AddListener(() => OnDriveChanged("?storage"));
|
||||
sbtn.transform.SetParent(drives, false);
|
||||
GameObject sbtn = GameObject.Instantiate<GameObject>(prefabButton);
|
||||
sbtn.GetComponentInChildren<Text>().text = "Storage";
|
||||
sbtn.GetComponentInChildren<Button>().onClick.AddListener(() => ChangeDirectory(new DirectoryInfo(androidStorage)));
|
||||
sbtn.transform.SetParent(drives, false);
|
||||
#else
|
||||
#error No update GUI logic
|
||||
#endif
|
||||
foreach (var p in m_presetPaths) {
|
||||
var d = new DirectoryInfo(p.Value);
|
||||
if (d.Exists) {
|
||||
GameObject btn = Instantiate(prefabButton);
|
||||
btn.GetComponentInChildren<Text>().text = p.Key;
|
||||
btn.GetComponentInChildren<Button>().onClick.AddListener(() => ChangeDirectory(d));
|
||||
btn.transform.SetParent(drives, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CallHelper.Purge(dirs);
|
||||
DirectoryInfo[] subdirs = CurrentDirectory.GetDirectories();
|
||||
GameObject pbtn = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("Common/Button"));
|
||||
GameObject pbtn = Instantiate(prefabButton);
|
||||
pbtn.GetComponentInChildren<Text>().text = "..";
|
||||
pbtn.GetComponentInChildren<Button>().onClick.AddListener(() => OnDirectoryChanged(".."));
|
||||
pbtn.GetComponentInChildren<Button>().onClick.AddListener(() => ChangeDirectory(new DirectoryInfo(Path.Combine(CurrentDirectory.FullName, ".."))));
|
||||
pbtn.transform.SetParent(dirs, false);
|
||||
foreach (DirectoryInfo d in subdirs) {
|
||||
GameObject btn = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("Common/Button"));
|
||||
GameObject btn = Instantiate(prefabButton);
|
||||
btn.GetComponentInChildren<Text>().text = d.Name;
|
||||
var ts = d.Name;
|
||||
btn.GetComponentInChildren<Button>().onClick.AddListener(() => OnDirectoryChanged(ts));
|
||||
var ts = d;
|
||||
btn.GetComponentInChildren<Button>().onClick.AddListener(() => ChangeDirectory(ts));
|
||||
btn.transform.SetParent(dirs, false);
|
||||
}
|
||||
|
||||
CallHelper.Purge(files);
|
||||
FileInfo[] fl = CurrentDirectory.GetFiles();
|
||||
foreach (FileInfo d in fl) {
|
||||
foreach (string ext in m_filter)
|
||||
if (d.Extension == ext) goto ext_matched;
|
||||
continue;
|
||||
ext_matched:
|
||||
GameObject btn = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("Common/Button"));
|
||||
btn.GetComponentInChildren<Text>().text = d.Name + " / " + (d.Length / 1024.0).ToString("0.0 KiB");
|
||||
var ts = d.FullName;
|
||||
btn.GetComponentInChildren<Button>().onClick.AddListener(() => OnFileChanged(ts));
|
||||
btn.transform.SetParent(files, false);
|
||||
foreach (string ext in m_filter) {
|
||||
if (d.Extension == ext) {
|
||||
GameObject btn = Instantiate(prefabButton);
|
||||
btn.GetComponentInChildren<Text>().text = d.Name + " / " + (d.Length / 1024.0).ToString("0.0 KiB");
|
||||
var ts = d.FullName;
|
||||
btn.GetComponentInChildren<Button>().onClick.AddListener(() => SelectFile(ts));
|
||||
btn.transform.SetParent(files, false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -4,7 +4,19 @@ using UnityEngine;
|
||||
namespace Cryville.Common.Unity.Input {
|
||||
public delegate void InputEventDelegate(InputIdentifier id, InputVector vec);
|
||||
public abstract class InputHandler : IDisposable {
|
||||
public event InputEventDelegate OnInput;
|
||||
InputEventDelegate m_onInput;
|
||||
public event InputEventDelegate OnInput {
|
||||
add {
|
||||
if (m_onInput == null) Activate();
|
||||
m_onInput -= value;
|
||||
m_onInput += value;
|
||||
}
|
||||
remove {
|
||||
if (m_onInput == null) return;
|
||||
m_onInput -= value;
|
||||
if (m_onInput == null) Deactivate();
|
||||
}
|
||||
}
|
||||
|
||||
~InputHandler() {
|
||||
Dispose(false);
|
||||
@@ -14,26 +26,15 @@ namespace Cryville.Common.Unity.Input {
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
public bool Activated { get; private set; }
|
||||
public void Activate() {
|
||||
if (Activated) return;
|
||||
Activated = true;
|
||||
ActivateImpl();
|
||||
}
|
||||
protected abstract void ActivateImpl();
|
||||
public void Deactivate() {
|
||||
if (!Activated) return;
|
||||
Activated = false;
|
||||
DeactivateImpl();
|
||||
}
|
||||
protected abstract void DeactivateImpl();
|
||||
protected abstract void Activate();
|
||||
protected abstract void Deactivate();
|
||||
public abstract void Dispose(bool disposing);
|
||||
public abstract bool IsNullable(int type);
|
||||
public abstract byte GetDimension(int type);
|
||||
public abstract string GetTypeName(int type);
|
||||
public abstract double GetCurrentTimestamp();
|
||||
protected void Feed(int type, int id, InputVector vec) {
|
||||
var del = OnInput;
|
||||
var del = m_onInput;
|
||||
if (del != null) del(new InputIdentifier { Source = new InputSource { Handler = this, Type = type }, Id = id }, vec);
|
||||
}
|
||||
}
|
||||
|
@@ -4,27 +4,22 @@ using System.Reflection;
|
||||
|
||||
namespace Cryville.Common.Unity.Input {
|
||||
public class InputManager {
|
||||
static readonly List<Type> HandlerRegistries = new List<Type> {
|
||||
static readonly HashSet<Type> HandlerRegistries = new HashSet<Type> {
|
||||
typeof(WindowsPointerHandler),
|
||||
typeof(UnityKeyHandler<UnityKeyboardReceiver>),
|
||||
typeof(UnityKeyHandler<UnityMouseButtonReceiver>),
|
||||
typeof(UnityMouseHandler),
|
||||
typeof(UnityTouchHandler),
|
||||
};
|
||||
// TODO set private
|
||||
public readonly List<InputHandler> _handlers = new List<InputHandler>();
|
||||
readonly Dictionary<InputHandler, double> _timeOrigins = new Dictionary<InputHandler, double>();
|
||||
readonly object _lock = new object();
|
||||
readonly Dictionary<InputIdentifier, InputVector> _vectors = new Dictionary<InputIdentifier, InputVector>();
|
||||
readonly List<InputEvent> _events = new List<InputEvent>();
|
||||
readonly HashSet<InputHandler> _handlers = new HashSet<InputHandler>();
|
||||
readonly Dictionary<Type, InputHandler> _typemap = new Dictionary<Type, InputHandler>();
|
||||
public InputManager() {
|
||||
foreach (var t in HandlerRegistries) {
|
||||
try {
|
||||
if (!typeof(InputHandler).IsAssignableFrom(t)) continue;
|
||||
var h = (InputHandler)ReflectionHelper.InvokeEmptyConstructor(t);
|
||||
h.OnInput += OnInput;
|
||||
_typemap.Add(t, h);
|
||||
_handlers.Add(h);
|
||||
_timeOrigins.Add(h, 0);
|
||||
Logger.Log("main", 1, "Input", "Initialized {0}", ReflectionHelper.GetSimpleName(t));
|
||||
}
|
||||
catch (TargetInvocationException ex) {
|
||||
@@ -32,49 +27,11 @@ namespace Cryville.Common.Unity.Input {
|
||||
}
|
||||
}
|
||||
}
|
||||
public void Activate() {
|
||||
lock (_lock) {
|
||||
_events.Clear();
|
||||
}
|
||||
foreach (var h in _handlers) h.Activate();
|
||||
public InputHandler GetHandler(string name) {
|
||||
return _typemap[Type.GetType(name)];
|
||||
}
|
||||
public void SyncTime(double time) {
|
||||
foreach (var h in _handlers) {
|
||||
_timeOrigins[h] = time - h.GetCurrentTimestamp();
|
||||
}
|
||||
}
|
||||
public void Deactivate() {
|
||||
foreach (var h in _handlers) h.Deactivate();
|
||||
}
|
||||
void OnInput(InputIdentifier id, InputVector vec) {
|
||||
lock (_lock) {
|
||||
double timeOrigin = _timeOrigins[id.Source.Handler];
|
||||
vec.Time += timeOrigin;
|
||||
InputVector vec0;
|
||||
if (_vectors.TryGetValue(id, out vec0)) {
|
||||
_events.Add(new InputEvent {
|
||||
Id = id,
|
||||
From = vec0,
|
||||
To = vec,
|
||||
});
|
||||
if (vec.IsNull) _vectors.Remove(id);
|
||||
else _vectors[id] = vec;
|
||||
}
|
||||
else {
|
||||
_events.Add(new InputEvent {
|
||||
Id = id,
|
||||
From = new InputVector(vec.Time),
|
||||
To = vec,
|
||||
});
|
||||
_vectors.Add(id, vec);
|
||||
}
|
||||
}
|
||||
}
|
||||
public void EnumerateEvents(Action<InputEvent> cb) {
|
||||
lock (_lock) {
|
||||
foreach (var ev in _events) cb(ev);
|
||||
_events.Clear();
|
||||
}
|
||||
public void EnumerateHandlers(Action<InputHandler> cb) {
|
||||
foreach (var h in _handlers) cb(h);
|
||||
}
|
||||
}
|
||||
|
||||
|
49
Assets/Cryville/Common/Unity/Input/SimpleInputConsumer.cs
Normal file
49
Assets/Cryville/Common/Unity/Input/SimpleInputConsumer.cs
Normal file
@@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Cryville.Common.Unity.Input {
|
||||
public class SimpleInputConsumer {
|
||||
readonly InputManager _manager;
|
||||
readonly object _lock = new object();
|
||||
readonly Dictionary<InputIdentifier, InputVector> _vectors = new Dictionary<InputIdentifier, InputVector>();
|
||||
readonly List<InputEvent> _events = new List<InputEvent>();
|
||||
public SimpleInputConsumer(InputManager manager) { _manager = manager; }
|
||||
public void Activate() {
|
||||
lock (_lock) {
|
||||
_events.Clear();
|
||||
}
|
||||
_manager.EnumerateHandlers(h => h.OnInput += OnInput);
|
||||
}
|
||||
public void Deactivate() {
|
||||
_manager.EnumerateHandlers(h => h.OnInput -= OnInput);
|
||||
}
|
||||
protected void OnInput(InputIdentifier id, InputVector vec) {
|
||||
lock (_lock) {
|
||||
InputVector vec0;
|
||||
if (_vectors.TryGetValue(id, out vec0)) {
|
||||
_events.Add(new InputEvent {
|
||||
Id = id,
|
||||
From = vec0,
|
||||
To = vec,
|
||||
});
|
||||
if (vec.IsNull) _vectors.Remove(id);
|
||||
else _vectors[id] = vec;
|
||||
}
|
||||
else {
|
||||
_events.Add(new InputEvent {
|
||||
Id = id,
|
||||
From = new InputVector(vec.Time),
|
||||
To = vec,
|
||||
});
|
||||
_vectors.Add(id, vec);
|
||||
}
|
||||
}
|
||||
}
|
||||
public void EnumerateEvents(Action<InputEvent> cb) {
|
||||
lock (_lock) {
|
||||
foreach (var ev in _events) cb(ev);
|
||||
_events.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,8 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 62489f8e495a805478e5b45c0f53ca4e
|
||||
timeCreated: 1623583546
|
||||
licenseType: Pro
|
||||
guid: 8fd2d5f1c7ba0c74c9ce8775075750db
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
@@ -9,19 +9,19 @@ namespace Cryville.Common.Unity.Input {
|
||||
|
||||
public UnityKeyHandler() { }
|
||||
|
||||
protected override void ActivateImpl() {
|
||||
protected override void Activate() {
|
||||
receiver = new GameObject("__keyrecv__");
|
||||
recvcomp = receiver.AddComponent<T>();
|
||||
recvcomp.SetCallback(Feed);
|
||||
}
|
||||
|
||||
protected override void DeactivateImpl() {
|
||||
protected override void Deactivate() {
|
||||
if (receiver) GameObject.Destroy(receiver);
|
||||
}
|
||||
|
||||
public override void Dispose(bool disposing) {
|
||||
if (disposing) {
|
||||
DeactivateImpl();
|
||||
Deactivate();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,13 +44,16 @@ namespace Cryville.Common.Unity.Input {
|
||||
|
||||
public abstract class UnityKeyReceiver<T> : MonoBehaviour where T : UnityKeyReceiver<T> {
|
||||
protected Action<int, int, InputVector> Callback;
|
||||
protected readonly List<int> Keys = new List<int>();
|
||||
protected readonly HashSet<int> Keys = new HashSet<int>();
|
||||
public void SetCallback(Action<int, int, InputVector> h) {
|
||||
Callback = h;
|
||||
}
|
||||
public abstract string GetKeyName(int type);
|
||||
void Awake() {
|
||||
useGUILayout = false;
|
||||
}
|
||||
void Update() {
|
||||
double time = Time.timeAsDouble;
|
||||
double time = Time.realtimeSinceStartupAsDouble;
|
||||
foreach (var k in Keys) {
|
||||
Callback(k, 0, new InputVector(time, Vector3.zero));
|
||||
}
|
||||
@@ -64,7 +67,7 @@ namespace Cryville.Common.Unity.Input {
|
||||
void OnGUI() {
|
||||
var e = Event.current;
|
||||
if (e.keyCode == KeyCode.None) return;
|
||||
double time = Time.timeAsDouble;
|
||||
double time = Time.realtimeSinceStartupAsDouble;
|
||||
var key = (int)e.keyCode;
|
||||
switch (e.type) {
|
||||
case EventType.KeyDown:
|
||||
@@ -92,7 +95,7 @@ namespace Cryville.Common.Unity.Input {
|
||||
}
|
||||
void OnGUI() {
|
||||
var e = Event.current;
|
||||
double time = Time.timeAsDouble;
|
||||
double time = Time.realtimeSinceStartupAsDouble;
|
||||
var key = e.button;
|
||||
switch (e.type) {
|
||||
case EventType.MouseDown:
|
||||
|
@@ -12,35 +12,35 @@ namespace Cryville.Common.Unity.Input {
|
||||
}
|
||||
}
|
||||
|
||||
protected override void ActivateImpl() {
|
||||
protected override void Activate() {
|
||||
receiver = new GameObject("__mouserecv__");
|
||||
receiver.AddComponent<UnityMouseReceiver>().SetHandler(this);
|
||||
}
|
||||
|
||||
protected override void DeactivateImpl() {
|
||||
protected override void Deactivate() {
|
||||
if (receiver) GameObject.Destroy(receiver);
|
||||
}
|
||||
|
||||
public override void Dispose(bool disposing) {
|
||||
if (disposing) {
|
||||
DeactivateImpl();
|
||||
Deactivate();
|
||||
}
|
||||
}
|
||||
|
||||
public override bool IsNullable(int type) {
|
||||
if (type != 0) throw new ArgumentOutOfRangeException(nameof(type));
|
||||
if (type != 0) throw new ArgumentOutOfRangeException("type");
|
||||
return false;
|
||||
}
|
||||
|
||||
public override byte GetDimension(int type) {
|
||||
if (type != 0) throw new ArgumentOutOfRangeException(nameof(type));
|
||||
if (type != 0) throw new ArgumentOutOfRangeException("type");
|
||||
return 2;
|
||||
}
|
||||
|
||||
public override string GetTypeName(int type) {
|
||||
switch (type) {
|
||||
case 0: return "Mouse Position";
|
||||
default: throw new ArgumentOutOfRangeException(nameof(type));
|
||||
default: throw new ArgumentOutOfRangeException("type");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ namespace Cryville.Common.Unity.Input {
|
||||
handler = h;
|
||||
}
|
||||
void Update() {
|
||||
double time = Time.timeAsDouble;
|
||||
double time = Time.realtimeSinceStartupAsDouble;
|
||||
Vector3 pos = UnityCameraUtils.ScreenToWorldPoint(unity::Input.mousePosition);
|
||||
handler.Feed(0, 0, new InputVector(time, pos));
|
||||
}
|
||||
|
@@ -12,35 +12,35 @@ namespace Cryville.Common.Unity.Input {
|
||||
}
|
||||
}
|
||||
|
||||
protected override void ActivateImpl() {
|
||||
protected override void Activate() {
|
||||
receiver = new GameObject("__touchrecv__");
|
||||
receiver.AddComponent<UnityPointerReceiver>().SetHandler(this);
|
||||
}
|
||||
|
||||
protected override void DeactivateImpl() {
|
||||
protected override void Deactivate() {
|
||||
if (receiver) GameObject.Destroy(receiver);
|
||||
}
|
||||
|
||||
public override void Dispose(bool disposing) {
|
||||
if (disposing) {
|
||||
DeactivateImpl();
|
||||
Deactivate();
|
||||
}
|
||||
}
|
||||
|
||||
public override bool IsNullable(int type) {
|
||||
if (type != 0) throw new ArgumentOutOfRangeException(nameof(type));
|
||||
if (type != 0) throw new ArgumentOutOfRangeException("type");
|
||||
return true;
|
||||
}
|
||||
|
||||
public override byte GetDimension(int type) {
|
||||
if (type != 0) throw new ArgumentOutOfRangeException(nameof(type));
|
||||
if (type != 0) throw new ArgumentOutOfRangeException("type");
|
||||
return 2;
|
||||
}
|
||||
|
||||
public override string GetTypeName(int type) {
|
||||
switch (type) {
|
||||
case 0: return "Touch";
|
||||
default: throw new ArgumentOutOfRangeException(nameof(type));
|
||||
default: throw new ArgumentOutOfRangeException("type");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ namespace Cryville.Common.Unity.Input {
|
||||
handler = h;
|
||||
}
|
||||
void Update() {
|
||||
double time = Time.timeAsDouble;
|
||||
double time = Time.realtimeSinceStartupAsDouble;
|
||||
for (int i = 0; i < unity::Input.touchCount; i++) {
|
||||
var t = unity::Input.GetTouch(i);
|
||||
Vector2 pos = UnityCameraUtils.ScreenToWorldPoint(t.position);
|
||||
|
@@ -61,7 +61,7 @@ namespace Cryville.Common.Unity.Input {
|
||||
public const int TABLET_DISABLE_PENBARRELFEEDBACK = 0x00000010;
|
||||
public const int TABLET_DISABLE_FLICKS = 0x00010000;
|
||||
|
||||
protected override void ActivateImpl() {
|
||||
protected override void Activate() {
|
||||
newWndProc = WndProc;
|
||||
newWndProcPtr = Marshal.GetFunctionPointerForDelegate(newWndProc);
|
||||
oldWndProcPtr = SetWindowLongPtr(hMainWindow, -4, newWndProcPtr);
|
||||
@@ -77,7 +77,7 @@ namespace Cryville.Common.Unity.Input {
|
||||
);
|
||||
}
|
||||
|
||||
protected override void DeactivateImpl() {
|
||||
protected override void Deactivate() {
|
||||
if (pressAndHoldAtomID != 0) {
|
||||
NativeMethods.RemoveProp(hMainWindow, PRESS_AND_HOLD_ATOM);
|
||||
NativeMethods.GlobalDeleteAtom(pressAndHoldAtomID);
|
||||
@@ -142,7 +142,7 @@ namespace Cryville.Common.Unity.Input {
|
||||
}
|
||||
|
||||
public override void Dispose(bool disposing) {
|
||||
DeactivateImpl();
|
||||
Deactivate();
|
||||
if (usePointerMessage)
|
||||
NativeMethods.EnableMouseInPointer(false);
|
||||
Instance = null;
|
||||
|
@@ -1,29 +0,0 @@
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
||||
namespace Cryville.Common.Unity {
|
||||
public class Popup : MonoBehaviour {
|
||||
|
||||
public string Message = "";
|
||||
|
||||
LayoutElement layout;
|
||||
|
||||
float timer = 0;
|
||||
|
||||
#pragma warning disable IDE0051
|
||||
void Start() {
|
||||
layout = GetComponent<LayoutElement>();
|
||||
GetComponentInChildren<Text>().text = Message;
|
||||
transform.SetParent(GameObject.Find("PopupList").transform);
|
||||
layout.minHeight = 0;
|
||||
}
|
||||
|
||||
void Update() {
|
||||
if (timer <= 0.8f) layout.minHeight = timer * 50;
|
||||
else if (timer >= 5f) GameObject.Destroy(gameObject);
|
||||
else if (timer >= 4.2f) layout.minHeight = (300 - timer) * 50;
|
||||
timer += Time.deltaTime;
|
||||
}
|
||||
#pragma warning restore IDE0051
|
||||
}
|
||||
}
|
@@ -118,7 +118,7 @@ namespace Cryville.Common.Unity {
|
||||
fdialog = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("Common/FileDialog")).GetComponent<FileDialog>();
|
||||
fdialog.Filter = filter;
|
||||
fdialog.CurrentDirectory = ContextPath;
|
||||
fdialog.Callback = () => OnFileDialogClosed();
|
||||
fdialog.OnClose += OnFileDialogClosed;
|
||||
}
|
||||
editor.SetDescription(PropertyName, desc);
|
||||
UpdateValue();
|
||||
@@ -133,10 +133,10 @@ namespace Cryville.Common.Unity {
|
||||
prop.SetValue(Target, v, new object[]{ });
|
||||
}
|
||||
catch (TargetInvocationException ex) {
|
||||
CallHelper.ShowMessageBox(ex.InnerException.Message);
|
||||
// CallHelper.ShowMessageBox(ex.InnerException.Message);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
CallHelper.ShowMessageBox(ex.Message);
|
||||
// CallHelper.ShowMessageBox(ex.Message);
|
||||
}
|
||||
}
|
||||
UpdateValue();
|
||||
|
@@ -126,8 +126,8 @@ namespace Cryville.Common.Unity.UI {
|
||||
void Update() {
|
||||
Vector2 cprectsize = ((RectTransform)transform.parent).rect.size;
|
||||
if (cprectsize != pprectsize) {
|
||||
OnFrameUpdate();
|
||||
pprectsize = cprectsize;
|
||||
OnFrameUpdate();
|
||||
}
|
||||
}
|
||||
#pragma warning restore IDE0051
|
||||
@@ -200,8 +200,7 @@ namespace Cryville.Common.Unity.UI {
|
||||
|
||||
void GenerateLine(int index, int line) {
|
||||
for (int j = 0; j < LineItemCount; j++) {
|
||||
var child = GameObject.Instantiate(m_itemTemplate);
|
||||
child.transform.SetParent(transform, false);
|
||||
var child = GameObject.Instantiate(m_itemTemplate, transform, false);
|
||||
lines[index][j] = child;
|
||||
}
|
||||
LoadLine(index, line);
|
||||
|
@@ -1,15 +1,17 @@
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Cryville.Crtr {
|
||||
public class Anchor {
|
||||
bool _opened;
|
||||
public bool Opened { get { return _opened; } }
|
||||
public Transform Transform { get; set; }
|
||||
public void Open() {
|
||||
_opened = true;
|
||||
}
|
||||
public void Close() {
|
||||
_opened = false;
|
||||
public int Name { get; private set; }
|
||||
public Transform Transform { get; private set; }
|
||||
public SkinContext SkinContext { get; private set; }
|
||||
public Dictionary<int, PropSrc> PropSrcs { get; private set; }
|
||||
public Anchor(int name, Transform transform, bool hasProps = false) {
|
||||
Name = name;
|
||||
Transform = transform;
|
||||
if (hasProps) PropSrcs = new Dictionary<int, PropSrc>();
|
||||
SkinContext = new SkinContext(transform, PropSrcs);
|
||||
}
|
||||
}
|
||||
}
|
22
Assets/Cryville/Crtr/Browsing/ChartResourceImporter.cs
Normal file
22
Assets/Cryville/Crtr/Browsing/ChartResourceImporter.cs
Normal file
@@ -0,0 +1,22 @@
|
||||
using Newtonsoft.Json;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace Cryville.Crtr.Browsing {
|
||||
public class ChartResourceImporter : ResourceConverter {
|
||||
static readonly string[] SUPPORTED_FORMATS = { ".umgc" };
|
||||
public override string[] GetSupportedFormats() {
|
||||
return SUPPORTED_FORMATS;
|
||||
}
|
||||
|
||||
public override IEnumerable<Resource> ConvertFrom(FileInfo file) {
|
||||
var meta = Path.Combine(file.Directory.FullName, "meta.json");
|
||||
if (!File.Exists(meta)) throw new FileNotFoundException("Meta file for the chart not found");
|
||||
using (StreamReader reader = new StreamReader(meta, Encoding.UTF8)) {
|
||||
var data = JsonConvert.DeserializeObject<ChartMeta>(reader.ReadToEnd());
|
||||
return new Resource[] { new ChartResource(data.name, file) };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,8 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 58e01e1e11af164408a19c1086709bd7
|
||||
timeCreated: 1638411495
|
||||
licenseType: Free
|
||||
guid: 168366bb891392b42a1d0a6bfa068ff3
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
@@ -47,11 +47,11 @@ namespace Cryville.Crtr.Browsing {
|
||||
_cover.sprite = m_coverPlaceholder;
|
||||
if (data.Cover != null) data.Cover.Destination = DisplayCover;
|
||||
var meta = data.Meta;
|
||||
_title.text = string.Format("{0}\n{1}", meta.song.name, meta.chart.name);
|
||||
_title.text = string.Format("{0}\n{1}", meta.song.name, meta.name);
|
||||
_desc.text = string.Format(
|
||||
"Music artist: {0}\nCharter: {1}\nLength: {2}\nNote Count: {3}",
|
||||
meta.song.author, meta.chart.author,
|
||||
TimeSpan.FromSeconds(meta.chart.length).ToString(3), meta.note_count
|
||||
meta.song.author, meta.author,
|
||||
TimeSpan.FromSeconds(meta.length).ToString(3), meta.note_count
|
||||
);
|
||||
}
|
||||
private void DisplayCover(bool succeeded, Texture2D tex) {
|
||||
@@ -60,10 +60,10 @@ namespace Cryville.Crtr.Browsing {
|
||||
}
|
||||
}
|
||||
public void OnPlay() {
|
||||
Master.Open(_id);
|
||||
Master.Open(_id, _data);
|
||||
}
|
||||
public void OnConfig() {
|
||||
Master.OpenConfig(_id);
|
||||
Master.OpenConfig(_id, _data);
|
||||
}
|
||||
}
|
||||
}
|
9
Assets/Cryville/Crtr/Browsing/ExtensionInterface.cs
Normal file
9
Assets/Cryville/Crtr/Browsing/ExtensionInterface.cs
Normal file
@@ -0,0 +1,9 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Cryville.Crtr.Browsing {
|
||||
public abstract class ExtensionInterface {
|
||||
public abstract IEnumerable<ResourceConverter> GetResourceConverters();
|
||||
public abstract IEnumerable<LocalResourceFinder> GetResourceFinders();
|
||||
}
|
||||
}
|
11
Assets/Cryville/Crtr/Browsing/ExtensionInterface.cs.meta
Normal file
11
Assets/Cryville/Crtr/Browsing/ExtensionInterface.cs.meta
Normal file
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4ffe72fef6ebb9e4da3571b4117f0d6d
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
@@ -1,4 +1,6 @@
|
||||
namespace Cryville.Crtr.Browsing {
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Cryville.Crtr.Browsing {
|
||||
public interface IResourceManager<T> {
|
||||
string[] CurrentDirectory { get; }
|
||||
int ChangeDirectory(string[] dir);
|
||||
@@ -10,5 +12,6 @@
|
||||
|
||||
bool ImportItemFrom(string path);
|
||||
string[] GetSupportedFormats();
|
||||
Dictionary<string, string> GetPresetPaths();
|
||||
}
|
||||
}
|
@@ -6,6 +6,7 @@ using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
using Logger = Cryville.Common.Logger;
|
||||
|
||||
namespace Cryville.Crtr.Browsing {
|
||||
internal class LegacyResourceManager : IResourceManager<ChartDetail> {
|
||||
@@ -16,6 +17,8 @@ namespace Cryville.Crtr.Browsing {
|
||||
|
||||
static readonly Dictionary<string, List<ResourceConverter>> converters
|
||||
= new Dictionary<string, List<ResourceConverter>>();
|
||||
static readonly Dictionary<string, string> localRes
|
||||
= new Dictionary<string, string>();
|
||||
|
||||
public LegacyResourceManager(string rootPath) {
|
||||
_rootPath = rootPath;
|
||||
@@ -24,13 +27,35 @@ namespace Cryville.Crtr.Browsing {
|
||||
static LegacyResourceManager() {
|
||||
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies()) {
|
||||
foreach (var type in asm.GetTypes()) {
|
||||
if (type.IsSubclassOf(typeof(ResourceConverter))) {
|
||||
var converter = (ResourceConverter)Activator.CreateInstance(type);
|
||||
foreach (var f in converter.GetSupportedFormats()) {
|
||||
if (!converters.ContainsKey(f))
|
||||
converters.Add(f, new List<ResourceConverter> { converter });
|
||||
else converters[f].Add(converter);
|
||||
if (!type.IsSubclassOf(typeof(ExtensionInterface))) continue;
|
||||
var ext = (ExtensionInterface)Activator.CreateInstance(type);
|
||||
try {
|
||||
var cs = ext.GetResourceConverters();
|
||||
if (cs != null) {
|
||||
foreach (var c in cs) {
|
||||
var fs = c.GetSupportedFormats();
|
||||
if (fs == null) continue;
|
||||
foreach (var f in fs) {
|
||||
if (f == null) continue;
|
||||
if (!converters.ContainsKey(f))
|
||||
converters.Add(f, new List<ResourceConverter> { c });
|
||||
else converters[f].Add(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
var fs2 = ext.GetResourceFinders();
|
||||
if (fs2 != null) {
|
||||
foreach (var f in fs2) {
|
||||
var name = f.Name;
|
||||
var path = f.GetRootPath();
|
||||
if (name != null && path != null)
|
||||
localRes.Add(name, path);
|
||||
}
|
||||
}
|
||||
Logger.Log("main", 1, "Resource", "Loaded extension {0}", ReflectionHelper.GetNamespaceQualifiedName(type));
|
||||
}
|
||||
catch (Exception ex) {
|
||||
Logger.Log("main", 4, "Resource", "Failed to initialize extension {0}: {1}", ReflectionHelper.GetNamespaceQualifiedName(type), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,22 +83,25 @@ namespace Cryville.Crtr.Browsing {
|
||||
|
||||
public ResourceItemMeta GetItemMeta(int id) {
|
||||
var item = items[id];
|
||||
AsyncDelivery<Texture2D> cover = null;
|
||||
var coverFile = item.GetFiles("cover.*");
|
||||
if (coverFile.Length > 0) {
|
||||
cover = new AsyncDelivery<Texture2D>();
|
||||
var task = new LoadTextureTask(Game.FileProtocolPrefix + coverFile[0].FullName, cover.Deliver);
|
||||
cover.CancelSource = task.Cancel;
|
||||
Game.NetworkTaskWorker.SubmitNetworkTask(task);
|
||||
}
|
||||
var meta = new ChartMeta();
|
||||
string name = item.Name;
|
||||
string desc = "(Unknown)";
|
||||
var metaFile = new FileInfo(item.FullName + "/meta.json");
|
||||
var metaFile = new FileInfo(item.FullName + "/.umgc");
|
||||
if (metaFile.Exists) {
|
||||
using (var reader = new StreamReader(metaFile.FullName)) {
|
||||
var meta = JsonConvert.DeserializeObject<ChartMeta>(reader.ReadToEnd());
|
||||
meta = JsonConvert.DeserializeObject<ChartMeta>(reader.ReadToEnd());
|
||||
name = meta.song.name;
|
||||
desc = meta.chart.name;
|
||||
desc = meta.name;
|
||||
}
|
||||
}
|
||||
AsyncDelivery<Texture2D> cover = null;
|
||||
if (meta.cover != null && meta.cover != "") {
|
||||
var coverFile = item.GetFiles(meta.cover);
|
||||
if (coverFile.Length > 0) {
|
||||
cover = new AsyncDelivery<Texture2D>();
|
||||
var task = new LoadTextureTask(Game.FileProtocolPrefix + coverFile[0].FullName, cover.Deliver);
|
||||
cover.CancelSource = task.Cancel;
|
||||
Game.NetworkTaskWorker.SubmitNetworkTask(task);
|
||||
}
|
||||
}
|
||||
return new ResourceItemMeta {
|
||||
@@ -86,21 +114,23 @@ namespace Cryville.Crtr.Browsing {
|
||||
|
||||
public ChartDetail GetItemDetail(int id) {
|
||||
var item = items[id];
|
||||
AsyncDelivery<Texture2D> cover = null;
|
||||
var coverFile = item.GetFiles("cover.*");
|
||||
if (coverFile.Length > 0) {
|
||||
cover = new AsyncDelivery<Texture2D>();
|
||||
var task = new LoadTextureTask(Game.FileProtocolPrefix + coverFile[0].FullName, cover.Deliver);
|
||||
cover.CancelSource = task.Cancel;
|
||||
Game.NetworkTaskWorker.SubmitNetworkTask(task);
|
||||
}
|
||||
ChartMeta meta = new ChartMeta();
|
||||
var metaFile = new FileInfo(item.FullName + "/meta.json");
|
||||
var meta = new ChartMeta();
|
||||
var metaFile = new FileInfo(item.FullName + "/.umgc");
|
||||
if (metaFile.Exists) {
|
||||
using (var reader = new StreamReader(metaFile.FullName)) {
|
||||
meta = JsonConvert.DeserializeObject<ChartMeta>(reader.ReadToEnd());
|
||||
}
|
||||
}
|
||||
AsyncDelivery<Texture2D> cover = null;
|
||||
if (meta.cover != null && meta.cover != "") {
|
||||
var coverFile = item.GetFiles(meta.cover);
|
||||
if (coverFile.Length > 0) {
|
||||
cover = new AsyncDelivery<Texture2D>();
|
||||
var task = new LoadTextureTask(Game.FileProtocolPrefix + coverFile[0].FullName, cover.Deliver);
|
||||
cover.CancelSource = task.Cancel;
|
||||
Game.NetworkTaskWorker.SubmitNetworkTask(task);
|
||||
}
|
||||
}
|
||||
return new ChartDetail {
|
||||
Cover = cover,
|
||||
Meta = meta,
|
||||
@@ -108,39 +138,74 @@ namespace Cryville.Crtr.Browsing {
|
||||
}
|
||||
|
||||
public string GetItemPath(int id) {
|
||||
return items[id].Name + "/.umgc";
|
||||
var item = items[id];
|
||||
var meta = new ChartMeta();
|
||||
var metaFile = new FileInfo(item.FullName + "/.umgc");
|
||||
using (var reader = new StreamReader(metaFile.FullName)) {
|
||||
meta = JsonConvert.DeserializeObject<ChartMeta>(reader.ReadToEnd());
|
||||
}
|
||||
return string.Format("{0}/{1}.json", items[id].Name, meta.data);
|
||||
}
|
||||
|
||||
public bool ImportItemFrom(string path) {
|
||||
var file = new FileInfo(path);
|
||||
if (!converters.ContainsKey(file.Extension)) return false;
|
||||
foreach (var converter in converters[file.Extension]) {
|
||||
var resources = converter.ConvertFrom(file);
|
||||
IEnumerable<Resource> resources = null;
|
||||
try {
|
||||
resources = converter.ConvertFrom(file);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
LogAndPopup(4, ex.Message);
|
||||
return false;
|
||||
}
|
||||
foreach (var res in resources) {
|
||||
if (res is ChartResource) {
|
||||
var tres = (ChartResource)res;
|
||||
if (!res.Valid) {
|
||||
LogAndPopup(3, "Attempt to import invalid resource: {0}", res);
|
||||
}
|
||||
else if (res is RawChartResource) {
|
||||
var tres = (RawChartResource)res;
|
||||
var dir = new DirectoryInfo(_rootPath + "/charts/" + res.Name);
|
||||
if (!dir.Exists) dir.Create();
|
||||
using (var writer = new StreamWriter(dir.FullName + "/.umgc")) {
|
||||
using (var writer = new StreamWriter(dir.FullName + "/.json")) {
|
||||
writer.Write(JsonConvert.SerializeObject(tres.Main, Game.GlobalJsonSerializerSettings));
|
||||
}
|
||||
using (var writer = new StreamWriter(dir.FullName + "/meta.json")) {
|
||||
using (var writer = new StreamWriter(dir.FullName + "/.umgc")) {
|
||||
tres.Meta.data = "";
|
||||
writer.Write(JsonConvert.SerializeObject(tres.Meta, Game.GlobalJsonSerializerSettings));
|
||||
}
|
||||
if (tres.Meta.cover != null) {
|
||||
var coverFile = new FileInfo(Path.Combine(file.Directory.FullName, tres.Meta.cover));
|
||||
if (coverFile.Exists)
|
||||
coverFile.CopyTo(Path.Combine(dir.FullName, tres.Meta.cover), true);
|
||||
}
|
||||
}
|
||||
else if (res is CoverResource) {
|
||||
var tres = (CoverResource)res;
|
||||
var dir = new DirectoryInfo(_rootPath + "/charts/" + res.Name);
|
||||
if (!dir.Exists) dir.Create();
|
||||
var dest = new FileInfo(_rootPath + "/charts/" + res.Name + "/cover" + tres.Source.Extension);
|
||||
if (!dest.Exists) tres.Source.CopyTo(dest.FullName);
|
||||
else if (res is FileResource) {
|
||||
var tres = (FileResource)res;
|
||||
DirectoryInfo dest;
|
||||
if (res is ChartResource)
|
||||
dest = new DirectoryInfo(_rootPath + "/charts/" + res.Name);
|
||||
else if (res is RulesetResource)
|
||||
dest = new DirectoryInfo(_rootPath + "/rulesets/" + res.Name);
|
||||
else if (res is SkinResource)
|
||||
dest = new DirectoryInfo(_rootPath + "/skins/" + (res as SkinResource).RulesetName + "/" + res.Name);
|
||||
else if (res is SongResource)
|
||||
dest = new DirectoryInfo(_rootPath + "/songs/" + res.Name);
|
||||
else {
|
||||
LogAndPopup(3, "Attempt to import unsupported file resource: {0}", res);
|
||||
continue;
|
||||
}
|
||||
if (!dest.Exists) {
|
||||
dest.Create();
|
||||
tres.Master.CopyTo(Path.Combine(dest.FullName, tres.Master.Extension));
|
||||
foreach (var attachment in tres.Attachments) {
|
||||
attachment.CopyTo(Path.Combine(dest.FullName, attachment.Name));
|
||||
}
|
||||
}
|
||||
else LogAndPopup(1, "Resource already exists: {0}", res);
|
||||
}
|
||||
else if (res is SongResource) {
|
||||
var tres = (SongResource)res;
|
||||
var dir = new DirectoryInfo(_rootPath + "/songs/" + res.Name);
|
||||
if (!dir.Exists) dir.Create();
|
||||
var dest = new FileInfo(_rootPath + "/songs/" + res.Name + "/.ogg");
|
||||
if (!dest.Exists) tres.Source.CopyTo(dest.FullName);
|
||||
else {
|
||||
LogAndPopup(3, "Attempt to import unsupported resource: {0}", res);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
@@ -148,8 +213,18 @@ namespace Cryville.Crtr.Browsing {
|
||||
return false;
|
||||
}
|
||||
|
||||
void LogAndPopup(int level, string format, params object[] args) {
|
||||
var msg = string.Format(format, args);
|
||||
Logger.Log("main", level, "Resource", msg);
|
||||
Popup.Create(msg);
|
||||
}
|
||||
|
||||
public string[] GetSupportedFormats() {
|
||||
return converters.Keys.ToArray();
|
||||
}
|
||||
|
||||
public Dictionary<string, string> GetPresetPaths() {
|
||||
return localRes;
|
||||
}
|
||||
}
|
||||
}
|
6
Assets/Cryville/Crtr/Browsing/LocalResourceFinder.cs
Normal file
6
Assets/Cryville/Crtr/Browsing/LocalResourceFinder.cs
Normal file
@@ -0,0 +1,6 @@
|
||||
namespace Cryville.Crtr.Browsing {
|
||||
public abstract class LocalResourceFinder {
|
||||
public abstract string Name { get; }
|
||||
public abstract string GetRootPath();
|
||||
}
|
||||
}
|
11
Assets/Cryville/Crtr/Browsing/LocalResourceFinder.cs.meta
Normal file
11
Assets/Cryville/Crtr/Browsing/LocalResourceFinder.cs.meta
Normal file
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f5b3f3294f679f14f8ec1195b0def630
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
@@ -24,10 +24,6 @@ namespace Cryville.Crtr.Browsing {
|
||||
const float SPEED = 8;
|
||||
float _ratio;
|
||||
#pragma warning disable IDE0051
|
||||
void Start() {
|
||||
m_handleArea.sizeDelta = new Vector2(m_handle.rect.height - m_handle.rect.width, 0);
|
||||
}
|
||||
|
||||
void Update() {
|
||||
if (_value && _ratio != 1) {
|
||||
_ratio += SPEED * Time.deltaTime;
|
||||
@@ -40,6 +36,10 @@ namespace Cryville.Crtr.Browsing {
|
||||
UpdateGraphics();
|
||||
}
|
||||
}
|
||||
|
||||
void OnRectTransformDimensionsChange() {
|
||||
m_handleArea.sizeDelta = new Vector2(m_handle.rect.height - m_handle.rect.width, 0);
|
||||
}
|
||||
#pragma warning restore IDE0051
|
||||
|
||||
void UpdateGraphics() {
|
||||
|
@@ -60,7 +60,6 @@ namespace Cryville.Crtr.Browsing {
|
||||
ev.callback.AddListener(e => OnPointerClick((PointerEventData)e));
|
||||
m_ctn.triggers.Add(ev);
|
||||
|
||||
m_handleArea.sizeDelta = new Vector2(m_handle.rect.height - m_handle.rect.width, 0);
|
||||
if (MaxStep != 0) SetRatio(0.5f);
|
||||
}
|
||||
|
||||
@@ -70,6 +69,10 @@ namespace Cryville.Crtr.Browsing {
|
||||
SetValueFromPos(pp);
|
||||
}
|
||||
}
|
||||
|
||||
void OnRectTransformDimensionsChange() {
|
||||
m_handleArea.sizeDelta = new Vector2(m_handle.rect.height - m_handle.rect.width, 0);
|
||||
}
|
||||
#pragma warning restore IDE0051
|
||||
|
||||
Vector2 pp;
|
||||
|
28
Assets/Cryville/Crtr/Browsing/PVPString.cs
Normal file
28
Assets/Cryville/Crtr/Browsing/PVPString.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
using UnityEngine.UI;
|
||||
|
||||
namespace Cryville.Crtr.Browsing {
|
||||
public class PVPString : PropertyValuePanel {
|
||||
string m_value;
|
||||
public override object Value {
|
||||
get {
|
||||
return m_value;
|
||||
}
|
||||
set {
|
||||
m_value = (string)value;
|
||||
_inputField.text = m_value;
|
||||
}
|
||||
}
|
||||
|
||||
InputField _inputField;
|
||||
|
||||
void Awake() {
|
||||
_inputField = GetComponent<InputField>();
|
||||
_inputField.onValueChanged.AddListener(OnValueChanged);
|
||||
}
|
||||
|
||||
void OnValueChanged(string value) {
|
||||
m_value = value;
|
||||
Callback(Value);
|
||||
}
|
||||
}
|
||||
}
|
11
Assets/Cryville/Crtr/Browsing/PVPString.cs.meta
Normal file
11
Assets/Cryville/Crtr/Browsing/PVPString.cs.meta
Normal file
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: aadf11739189bc94e9cb4f702eb7ccd3
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
@@ -32,8 +32,7 @@ namespace Cryville.Crtr.Browsing {
|
||||
public void Load(string name, IEnumerable<PropertyInfo> props, object target) {
|
||||
Name = name.ToUpper();
|
||||
foreach (var prop in props) {
|
||||
var obj = GameObject.Instantiate<GameObject>(m_propertyPrefab);
|
||||
obj.transform.SetParent(transform, false);
|
||||
var obj = GameObject.Instantiate<GameObject>(m_propertyPrefab, transform, false);
|
||||
obj.GetComponent<PropertyPanel>().Load(prop, target);
|
||||
}
|
||||
}
|
||||
|
@@ -10,6 +10,8 @@ namespace Cryville.Crtr.Browsing {
|
||||
GameObject m_bool;
|
||||
[SerializeField]
|
||||
GameObject m_number;
|
||||
[SerializeField]
|
||||
GameObject m_string;
|
||||
|
||||
PropertyInfo _property;
|
||||
object _target;
|
||||
@@ -32,8 +34,9 @@ namespace Cryville.Crtr.Browsing {
|
||||
GameObject vp;
|
||||
if (prop.PropertyType == typeof(bool)) vp = m_bool;
|
||||
else if (prop.PropertyType == typeof(float) || prop.PropertyType == typeof(int)) vp = m_number;
|
||||
else if (prop.PropertyType == typeof(string)) vp = m_string;
|
||||
else return;
|
||||
_value = GameObject.Instantiate(vp, _valueContainer).GetComponent<PropertyValuePanel>();
|
||||
_value = GameObject.Instantiate(vp, _valueContainer, false).GetComponent<PropertyValuePanel>();
|
||||
if (_value is PVPNumber) {
|
||||
var t = (PVPNumber)_value;
|
||||
t.IntegerMode = prop.PropertyType == typeof(int);
|
||||
|
@@ -1,5 +1,6 @@
|
||||
using Cryville.Common.Unity;
|
||||
using Cryville.Common.Unity.UI;
|
||||
using System;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
||||
@@ -19,6 +20,9 @@ namespace Cryville.Crtr.Browsing {
|
||||
|
||||
_dialog = GameObject.Instantiate(Resources.Load<GameObject>("Common/FileDialog")).GetComponent<FileDialog>();
|
||||
_dialog.gameObject.SetActive(false);
|
||||
_dialog.Filter = ResourceManager.GetSupportedFormats();
|
||||
_dialog.PresetPaths = ResourceManager.GetPresetPaths();
|
||||
_dialog.OnClose += OnAddDialogClosed;
|
||||
}
|
||||
|
||||
private bool LoadPathPart(int id, GameObject obj) {
|
||||
@@ -29,8 +33,13 @@ namespace Cryville.Crtr.Browsing {
|
||||
|
||||
private bool LoadItem(int id, GameObject obj) {
|
||||
var bi = obj.GetComponent<BrowserItem>();
|
||||
var item = ResourceManager.GetItemMeta(id);
|
||||
bi.Load(id, item);
|
||||
try {
|
||||
var item = ResourceManager.GetItemMeta(id);
|
||||
bi.Load(id, item);
|
||||
}
|
||||
catch (Exception) {
|
||||
bi.Load(id, new ResourceItemMeta { Name = "<color=#ff0000>Invalid resource</color>" });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -51,19 +60,17 @@ namespace Cryville.Crtr.Browsing {
|
||||
}
|
||||
|
||||
public void OnAddButtonClicked() {
|
||||
_dialog.Callback = OnAddDialogClosed;
|
||||
_dialog.Filter = ResourceManager.GetSupportedFormats();
|
||||
_dialog.Show();
|
||||
}
|
||||
|
||||
private void OnAddDialogClosed() {
|
||||
if (_dialog.FileName == null) return;
|
||||
if (ResourceManager.ImportItemFrom(_dialog.FileName)) {
|
||||
Debug.Log("Import succeeded"); // TODO
|
||||
Popup.Create("Import succeeded");
|
||||
OnPathClicked(ResourceManager.CurrentDirectory.Length - 1);
|
||||
}
|
||||
else {
|
||||
Debug.Log("Import failed"); // TODO
|
||||
Popup.Create("Import failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,5 +1,6 @@
|
||||
using Cryville.Common;
|
||||
using Cryville.Common.Unity.UI;
|
||||
using Newtonsoft.Json;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.SceneManagement;
|
||||
@@ -64,18 +65,21 @@ namespace Cryville.Crtr.Browsing {
|
||||
_units[_slideDest + 1].SlideToRight();
|
||||
}
|
||||
|
||||
public void Open(int id) {
|
||||
SetDataSettings(id);
|
||||
public void Open(int id, ChartDetail detail) {
|
||||
SetDataSettings(id, detail);
|
||||
#if UNITY_5_3_OR_NEWER
|
||||
SceneManager.LoadScene("Play", LoadSceneMode.Additive);
|
||||
#else
|
||||
Application.LoadLevelAdditive("Play");
|
||||
#endif
|
||||
GameObject.Find("/Master").GetComponent<Master>().HideMenu();
|
||||
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
|
||||
DiscordController.Instance.SetPlaying(string.Format("{0} - {1}", detail.Meta.song.name, detail.Meta.name), detail.Meta.length);
|
||||
#endif
|
||||
}
|
||||
|
||||
public void OpenConfig(int id) {
|
||||
SetDataSettings(id);
|
||||
public void OpenConfig(int id, ChartDetail detail) {
|
||||
SetDataSettings(id, detail);
|
||||
#if UNITY_5_3_OR_NEWER
|
||||
SceneManager.LoadScene("Config", LoadSceneMode.Additive);
|
||||
#else
|
||||
@@ -84,9 +88,9 @@ namespace Cryville.Crtr.Browsing {
|
||||
GameObject.Find("/Master").GetComponent<Master>().HideMenu();
|
||||
}
|
||||
|
||||
void SetDataSettings(int id) {
|
||||
Settings.Default.LoadRuleset = "key/.umgr";
|
||||
Settings.Default.LoadSkin = "key/0/.umgs";
|
||||
void SetDataSettings(int id, ChartDetail detail) {
|
||||
Settings.Default.LoadRuleset = detail.Meta.ruleset + "/.umgr";
|
||||
Settings.Default.LoadRulesetConfig = detail.Meta.ruleset + ".json";
|
||||
Settings.Default.LoadChart = MainBrowser.ResourceManager.GetItemPath(id);
|
||||
}
|
||||
}
|
||||
@@ -97,16 +101,22 @@ namespace Cryville.Crtr.Browsing {
|
||||
}
|
||||
|
||||
#pragma warning disable IDE1006
|
||||
public struct ChartMeta {
|
||||
public MetaInfo song { get; set; }
|
||||
public MetaInfo chart { get; set; }
|
||||
public struct MetaInfo {
|
||||
public string name { get; set; }
|
||||
public string author { get; set; }
|
||||
public float length { get; set; }
|
||||
}
|
||||
public class MetaInfo {
|
||||
public string name { get; set; }
|
||||
public string author { get; set; }
|
||||
[JsonRequired]
|
||||
public string data { get; set; }
|
||||
}
|
||||
public class SongMetaInfo {
|
||||
public string name { get; set; }
|
||||
public string author { get; set; }
|
||||
}
|
||||
public class ChartMeta : MetaInfo {
|
||||
public SongMetaInfo song { get; set; }
|
||||
public float length { get; set; }
|
||||
public string ruleset { get; set; }
|
||||
public int note_count { get; set; }
|
||||
public string cover { get; set; }
|
||||
}
|
||||
#pragma warning restore IDE1006
|
||||
}
|
||||
|
@@ -1,4 +1,5 @@
|
||||
using Cryville.Common;
|
||||
using Newtonsoft.Json;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
@@ -12,24 +13,67 @@ namespace Cryville.Crtr.Browsing {
|
||||
Name = StringUtils.EscapeFileName(name);
|
||||
}
|
||||
public string Name { get; private set; }
|
||||
public abstract bool Valid { get; }
|
||||
public override string ToString() {
|
||||
return string.Format("{0} ({1})", Name, ReflectionHelper.GetSimpleName(GetType()));
|
||||
}
|
||||
}
|
||||
public class ChartResource : Resource {
|
||||
public ChartResource(string name, Chart main, ChartMeta meta) : base(name) {
|
||||
public class RawChartResource : Resource {
|
||||
public RawChartResource(string name, Chart main, ChartMeta meta) : base(name) {
|
||||
Main = main; Meta = meta;
|
||||
}
|
||||
public Chart Main { get; private set; }
|
||||
public ChartMeta Meta { get; private set; }
|
||||
public override bool Valid { get { return true; } }
|
||||
}
|
||||
public class CoverResource : Resource {
|
||||
public CoverResource(string name, FileInfo src) : base(name) {
|
||||
Source = src;
|
||||
public abstract class FileResource : Resource {
|
||||
public FileResource(string name, FileInfo master) : base(name) {
|
||||
Master = master;
|
||||
Attachments = new List<FileInfo>();
|
||||
}
|
||||
public FileInfo Master { get; private set; }
|
||||
public List<FileInfo> Attachments { get; private set; }
|
||||
public override bool Valid {
|
||||
get {
|
||||
if (!Master.Exists) return false;
|
||||
foreach (var file in Attachments) {
|
||||
if (!file.Exists) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
public FileInfo Source { get; private set; }
|
||||
}
|
||||
public class SongResource : Resource {
|
||||
public SongResource(string name, FileInfo src) : base(name) {
|
||||
Source = src;
|
||||
public class ChartResource : FileResource {
|
||||
public ChartResource(string name, FileInfo master) : base(name, master) {
|
||||
using (var reader = new StreamReader(master.FullName)) {
|
||||
var meta = JsonConvert.DeserializeObject<ChartMeta>(reader.ReadToEnd());
|
||||
Attachments.Add(new FileInfo(Path.Combine(master.Directory.FullName, meta.data + ".json")));
|
||||
if (meta.cover != null) Attachments.Add(new FileInfo(Path.Combine(master.Directory.FullName, meta.cover)));
|
||||
}
|
||||
}
|
||||
}
|
||||
public class SongResource : FileResource {
|
||||
public SongResource(string name, FileInfo master) : base(name, master) { }
|
||||
}
|
||||
public class RulesetResource : FileResource {
|
||||
public RulesetResource(string name, FileInfo master) : base(name, master) {
|
||||
using (var reader = new StreamReader(master.FullName)) {
|
||||
var meta = JsonConvert.DeserializeObject<Ruleset>(reader.ReadToEnd());
|
||||
Attachments.Add(new FileInfo(Path.Combine(master.Directory.FullName, meta.data + ".pdt")));
|
||||
}
|
||||
}
|
||||
}
|
||||
public class SkinResource : FileResource {
|
||||
public string RulesetName { get; private set; }
|
||||
public SkinResource(string name, FileInfo master) : base(name, master) {
|
||||
using (var reader = new StreamReader(master.FullName)) {
|
||||
var meta = JsonConvert.DeserializeObject<Skin>(reader.ReadToEnd());
|
||||
RulesetName = meta.ruleset;
|
||||
Attachments.Add(new FileInfo(Path.Combine(master.Directory.FullName, meta.data + ".pdt")));
|
||||
foreach (var frame in meta.frames) {
|
||||
Attachments.Add(new FileInfo(Path.Combine(master.Directory.FullName, frame)));
|
||||
}
|
||||
}
|
||||
}
|
||||
public FileInfo Source { get; private set; }
|
||||
}
|
||||
}
|
20
Assets/Cryville/Crtr/Browsing/RulesetResourceImporter.cs
Normal file
20
Assets/Cryville/Crtr/Browsing/RulesetResourceImporter.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
using Newtonsoft.Json;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace Cryville.Crtr.Browsing {
|
||||
public class RulesetResourceImporter : ResourceConverter {
|
||||
static readonly string[] SUPPORTED_FORMATS = { ".umgr" };
|
||||
public override string[] GetSupportedFormats() {
|
||||
return SUPPORTED_FORMATS;
|
||||
}
|
||||
|
||||
public override IEnumerable<Resource> ConvertFrom(FileInfo file) {
|
||||
using (StreamReader reader = new StreamReader(file.FullName, Encoding.UTF8)) {
|
||||
var data = JsonConvert.DeserializeObject<Ruleset>(reader.ReadToEnd());
|
||||
return new Resource[] { new RulesetResource(data.name, file) };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f2c1531e76f19a647865f7ec335561cd
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
20
Assets/Cryville/Crtr/Browsing/SkinResourceImporter.cs
Normal file
20
Assets/Cryville/Crtr/Browsing/SkinResourceImporter.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
using Newtonsoft.Json;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace Cryville.Crtr.Browsing {
|
||||
public class SkinResourceImporter : ResourceConverter {
|
||||
static readonly string[] SUPPORTED_FORMATS = { ".umgs" };
|
||||
public override string[] GetSupportedFormats() {
|
||||
return SUPPORTED_FORMATS;
|
||||
}
|
||||
|
||||
public override IEnumerable<Resource> ConvertFrom(FileInfo file) {
|
||||
using (StreamReader reader = new StreamReader(file.FullName, Encoding.UTF8)) {
|
||||
var data = JsonConvert.DeserializeObject<Skin>(reader.ReadToEnd());
|
||||
return new Resource[] { new SkinResource(data.name, file) };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
11
Assets/Cryville/Crtr/Browsing/SkinResourceImporter.cs.meta
Normal file
11
Assets/Cryville/Crtr/Browsing/SkinResourceImporter.cs.meta
Normal file
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9904b4c21758c5046afc341fe2fa8845
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
@@ -3,18 +3,24 @@ using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Cryville.Crtr {
|
||||
[JsonConverter(typeof(BeatTimeConverter))]
|
||||
public struct BeatTime {
|
||||
public struct BeatTime : IComparable<BeatTime>, IEquatable<BeatTime> {
|
||||
[JsonConstructor()]
|
||||
public BeatTime(int _b, int _n, int _d) {
|
||||
b = _b;
|
||||
n = _n;
|
||||
d = _d;
|
||||
}
|
||||
public BeatTime(int _n, int _d) {
|
||||
b = _n / _d;
|
||||
n = _n % _d;
|
||||
d = _d;
|
||||
}
|
||||
|
||||
[JsonIgnore]
|
||||
public int b;
|
||||
@@ -24,6 +30,36 @@ namespace Cryville.Crtr {
|
||||
|
||||
[JsonIgnore]
|
||||
public int d;
|
||||
|
||||
[JsonIgnore]
|
||||
public double Decimal { get { return b + (double)n / d; } }
|
||||
|
||||
public int CompareTo(BeatTime other) {
|
||||
var c = b.CompareTo(other.b);
|
||||
if (c != 0) return c;
|
||||
return ((double)n / d).CompareTo((double)other.n / other.d);
|
||||
}
|
||||
|
||||
public override bool Equals(object obj) {
|
||||
if (!(obj is BeatTime)) return false;
|
||||
return Equals((BeatTime)obj);
|
||||
}
|
||||
|
||||
public bool Equals(BeatTime other) {
|
||||
return b.Equals(other.b) && ((double)n / d).Equals((double)other.n / other.d);
|
||||
}
|
||||
|
||||
public override int GetHashCode() {
|
||||
return Decimal.GetHashCode();
|
||||
}
|
||||
|
||||
public static bool operator ==(BeatTime left, BeatTime right) {
|
||||
return left.Equals(right);
|
||||
}
|
||||
|
||||
public static bool operator !=(BeatTime left, BeatTime right) {
|
||||
return !left.Equals(right);
|
||||
}
|
||||
}
|
||||
|
||||
public class BeatTimeConverter : JsonConverter {
|
||||
@@ -55,7 +91,7 @@ namespace Cryville.Crtr {
|
||||
[JsonIgnore]
|
||||
public float BeatPosition {
|
||||
get {
|
||||
return time.Value.b + time.Value.n / (float)time.Value.d + BeatOffset;
|
||||
return (float)time.Value.Decimal + BeatOffset;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,7 +101,7 @@ namespace Cryville.Crtr {
|
||||
public float EndBeatPosition {
|
||||
get {
|
||||
if (endtime == null) return BeatPosition;
|
||||
return endtime.Value.b + endtime.Value.n / (float)endtime.Value.d + BeatOffset;
|
||||
return (float)endtime.Value.Decimal + BeatOffset;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,15 +130,6 @@ namespace Cryville.Crtr {
|
||||
get { return Duration > 0; }
|
||||
}
|
||||
|
||||
private InstantEvent attev = null;
|
||||
[JsonIgnore]
|
||||
public InstantEvent AttackEvent {
|
||||
get {
|
||||
if (attev == null) attev = new InstantEvent(this);
|
||||
return attev;
|
||||
}
|
||||
}
|
||||
|
||||
private InstantEvent relev = null;
|
||||
[JsonIgnore]
|
||||
public InstantEvent ReleaseEvent {
|
||||
@@ -167,7 +194,7 @@ namespace Cryville.Crtr {
|
||||
public virtual EventList GetEventsOfType(string type) {
|
||||
switch (type) {
|
||||
case "motions": return new EventList<Chart.Motion>(motions);
|
||||
default: throw new ArgumentException("Unknown type");
|
||||
default: throw new ArgumentException(string.Format("Unknown event type {0}", type));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -274,8 +301,10 @@ namespace Cryville.Crtr {
|
||||
#pragma warning restore IDE1006
|
||||
|
||||
private void LoadFromString(string s) {
|
||||
if (RelativeNode != null || AbsoluteValue != null)
|
||||
throw new InvalidOperationException("The motion property can only be set at initialization");
|
||||
Match m = Regex.Match(s, @"^(.+?)(#(\d+))?(@(.+?))?(\^(.+?))?(\*(.+?))?(:(.+))?$");
|
||||
if (!m.Success) throw new ArgumentException(); // TODO
|
||||
if (!m.Success) throw new ArgumentException("Invalid motion string format");
|
||||
name = new Identifier(m.Groups[1].Value);
|
||||
var registry = ChartPlayer.motionRegistry[name];
|
||||
if (m.Groups[3].Success) {
|
||||
@@ -295,6 +324,10 @@ namespace Cryville.Crtr {
|
||||
else {
|
||||
AbsoluteValue = Vector.Construct(registry.Type, m.Groups[11].Value);
|
||||
}
|
||||
SubmitPropSrc("value", VectorSrc.Construct(() => {
|
||||
if (RelativeNode != null) return RelativeNode.Value;
|
||||
else return AbsoluteValue;
|
||||
}));
|
||||
}
|
||||
|
||||
public override string ToString() {
|
||||
@@ -303,7 +336,7 @@ namespace Cryville.Crtr {
|
||||
var node = RelativeNode;
|
||||
result += "#" + node.Id;
|
||||
if (node.Time != null) result += "@" + node.Time.ToString();
|
||||
if (node.Transition != null) result = "^" + node.Transition.ToString();
|
||||
if (node.Transition != null) result = "^" + ((byte)node.Transition).ToString(CultureInfo.InvariantCulture);
|
||||
if (node.Rate != null) result += "*" + node.Rate.ToString();
|
||||
if (node.Value != null) result += ":" + node.Value.ToString();
|
||||
}
|
||||
@@ -346,10 +379,6 @@ namespace Cryville.Crtr {
|
||||
}
|
||||
|
||||
public Motion() {
|
||||
SubmitPropSrc("value", new VectorSrc(() => {
|
||||
if (RelativeNode != null) return RelativeNode.Value;
|
||||
else return AbsoluteValue;
|
||||
}));
|
||||
SubmitPropOp("motion", new PropOp.String(v => motion = v));
|
||||
SubmitPropOp("name", new PropOp.Identifier(v => {
|
||||
var n = new Identifier(v);
|
||||
@@ -377,14 +406,6 @@ namespace Cryville.Crtr {
|
||||
}
|
||||
}
|
||||
|
||||
public Note() {
|
||||
SubmitPropSrc("track", new PropSrc.Float(() => {
|
||||
var i = motions.FirstOrDefault(m => m.RelativeNode == null && m.Name == "track");
|
||||
if (i == null) return ((Vec1)ChartPlayer.motionRegistry["track"].InitValue).Value;
|
||||
else return ((Vec1)i.AbsoluteValue).Value;
|
||||
}));
|
||||
}
|
||||
|
||||
public override EventList GetEventsOfType(string type) {
|
||||
switch (type) {
|
||||
case "judges": return new EventList<Judge>(judges);
|
||||
@@ -399,10 +420,12 @@ namespace Cryville.Crtr {
|
||||
public class Judge : ChartEvent {
|
||||
[JsonIgnore]
|
||||
public Identifier Id;
|
||||
#pragma warning disable IDE1006
|
||||
public string name {
|
||||
get { return Id.ToString(); }
|
||||
set { Id = new Identifier(value); }
|
||||
}
|
||||
#pragma warning restore IDE1006
|
||||
|
||||
public override int Priority {
|
||||
get { return 0; }
|
||||
|
@@ -37,9 +37,9 @@ namespace Cryville.Crtr {
|
||||
else if (ev.Unstamped == null) { }
|
||||
else if (ev.Unstamped is Chart.Sound) {
|
||||
Chart.Sound tev = (Chart.Sound)ev.Unstamped;
|
||||
var source = new LibavFileAudioSource(
|
||||
Game.GameDataPath + "/songs/" + tev.id + "/.ogg"
|
||||
);
|
||||
var dir = new DirectoryInfo(Game.GameDataPath + "/songs/" + tev.id);
|
||||
var files = dir.GetFiles();
|
||||
var source = new LibavFileAudioSource(files[0].FullName);
|
||||
source.SelectStream();
|
||||
sounds.Add(source);
|
||||
Game.AudioSession.Sequence(
|
||||
|
@@ -1,9 +1,7 @@
|
||||
//#define NO_THREAD
|
||||
#define BUILD
|
||||
|
||||
using Cryville.Common;
|
||||
using Cryville.Common.Plist;
|
||||
using Cryville.Common.Unity.Input;
|
||||
using Cryville.Crtr.Config;
|
||||
using Cryville.Crtr.Event;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
@@ -27,8 +25,7 @@ namespace Cryville.Crtr {
|
||||
Ruleset ruleset;
|
||||
PdtRuleset pruleset;
|
||||
Dictionary<string, Texture2D> texs;
|
||||
public static Dictionary<string, Cocos2dFrames.Frame> frames;
|
||||
List<Cocos2dFrames> plists;
|
||||
public static Dictionary<string, SpriteFrame> frames;
|
||||
|
||||
readonly Queue<string> texLoadQueue = new Queue<string>();
|
||||
#if UNITY_5_4_OR_NEWER
|
||||
@@ -53,11 +50,12 @@ namespace Cryville.Crtr {
|
||||
public static Rect hitRect;
|
||||
public static Plane[] frustumPlanes;
|
||||
|
||||
RulesetConfig _rscfg;
|
||||
static bool disableGC = true;
|
||||
static float clippingDist = 1f;
|
||||
static float renderDist = 6f;
|
||||
static float renderStep = 0.05f;
|
||||
public static float actualRenderStep = 0f;
|
||||
static double renderStep = 0.05;
|
||||
public static double actualRenderStep = 0;
|
||||
static bool autoRenderStep = false;
|
||||
public static float soundOffset = 0;
|
||||
static float startOffset = 0;
|
||||
@@ -69,17 +67,6 @@ namespace Cryville.Crtr {
|
||||
|
||||
InputProxy inputProxy;
|
||||
|
||||
~ChartPlayer() {
|
||||
Dispose();
|
||||
}
|
||||
|
||||
public void Dispose() {
|
||||
#if !NO_THREAD
|
||||
if (loadThread != null) loadThread.Abort();
|
||||
#endif
|
||||
if (texLoader != null) texLoader.Dispose();
|
||||
}
|
||||
|
||||
#region MonoBehaviour
|
||||
void Start() {
|
||||
var logobj = GameObject.Find("Logs");
|
||||
@@ -96,134 +83,158 @@ namespace Cryville.Crtr {
|
||||
|
||||
texHandler = new DownloadHandlerTexture();
|
||||
#if BUILD
|
||||
Play();
|
||||
try {
|
||||
Play();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
Game.LogException("Load/WorkerThread", "An error occured while loading the data", ex);
|
||||
Popup.CreateException(ex);
|
||||
ReturnToMenu();
|
||||
}
|
||||
#endif
|
||||
|
||||
// Camera.main.RenderToCubemap();
|
||||
}
|
||||
|
||||
void OnDestroy() {
|
||||
if (cbus != null) cbus.Dispose();
|
||||
if (bbus != null) bbus.Dispose();
|
||||
if (tbus != null) tbus.Dispose();
|
||||
if (nbus != null) nbus.Dispose();
|
||||
if (loadThread != null) loadThread.Abort();
|
||||
if (texLoader != null) texLoader.Dispose();
|
||||
if (inputProxy != null) inputProxy.Dispose();
|
||||
if (texs != null) foreach (var t in texs) Texture.Destroy(t.Value);
|
||||
Camera.onPostRender -= OnCameraPostRender;
|
||||
GC.Collect();
|
||||
}
|
||||
|
||||
bool texloaddone;
|
||||
diag::Stopwatch texloadtimer = new diag::Stopwatch();
|
||||
bool firstFrame;
|
||||
int forceSyncFrames;
|
||||
double atime0;
|
||||
void Update() {
|
||||
// if (Input.GetKeyDown(KeyCode.Return)) TogglePlay();
|
||||
if (started) {
|
||||
try {
|
||||
if (Screen.width != screenSize.x || Screen.height != screenSize.y)
|
||||
throw new InvalidOperationException("Window resized while playing");
|
||||
float dt = firstFrame
|
||||
? 1f / Application.targetFrameRate
|
||||
: Time.deltaTime;
|
||||
firstFrame = false;
|
||||
inputProxy.ForceTick();
|
||||
cbus.ForwardByTime(dt);
|
||||
bbus.ForwardByTime(dt);
|
||||
UnityEngine.Profiling.Profiler.BeginSample("ChartPlayer.Forward");
|
||||
UnityEngine.Profiling.Profiler.BeginSample("EventBus.Copy");
|
||||
bbus.CopyTo(2, tbus);
|
||||
bbus.CopyTo(3, nbus);
|
||||
UnityEngine.Profiling.Profiler.EndSample();
|
||||
float step = autoRenderStep ? ( firstFrame
|
||||
? 1f / Application.targetFrameRate
|
||||
: Time.smoothDeltaTime
|
||||
) : renderStep;
|
||||
actualRenderStep = step;
|
||||
|
||||
nbus.ForwardStepByTime(clippingDist, step);
|
||||
nbus.BroadcastEndUpdate();
|
||||
nbus.Anchor();
|
||||
|
||||
tbus.ForwardStepByTime(clippingDist, step);
|
||||
tbus.ForwardStepByTime(renderDist, step);
|
||||
tbus.BroadcastEndUpdate();
|
||||
UnityEngine.Profiling.Profiler.EndSample();
|
||||
if (started) GameUpdate();
|
||||
else if (loadThread != null) LoadUpdate();
|
||||
if (logEnabled) LogUpdate();
|
||||
else Game.MainLogger.Enumerate((level, module, msg) => { });
|
||||
}
|
||||
void GameUpdate() {
|
||||
try {
|
||||
if (Screen.width != screenSize.x || Screen.height != screenSize.y)
|
||||
throw new InvalidOperationException("Window resized while playing");
|
||||
double dt, step;
|
||||
if (forceSyncFrames != 0) {
|
||||
forceSyncFrames--;
|
||||
double target = Game.AudioClient.Position - atime0;
|
||||
dt = target - cbus.Time;
|
||||
step = autoRenderStep ? 1f / Application.targetFrameRate : renderStep;
|
||||
inputProxy.SyncTime(target);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
Game.LogException("Game", "An error occured while playing", ex);
|
||||
Stop();
|
||||
else {
|
||||
dt = Time.deltaTime;
|
||||
step = autoRenderStep ? Time.smoothDeltaTime : renderStep;
|
||||
}
|
||||
inputProxy.ForceTick();
|
||||
cbus.ForwardByTime(dt);
|
||||
bbus.ForwardByTime(dt);
|
||||
UnityEngine.Profiling.Profiler.BeginSample("ChartPlayer.Forward");
|
||||
UnityEngine.Profiling.Profiler.BeginSample("EventBus.Copy");
|
||||
bbus.CopyTo(2, tbus);
|
||||
bbus.CopyTo(3, nbus);
|
||||
UnityEngine.Profiling.Profiler.EndSample();
|
||||
actualRenderStep = step;
|
||||
|
||||
nbus.ForwardStepByTime(clippingDist, step);
|
||||
nbus.BroadcastEndUpdate();
|
||||
nbus.Anchor();
|
||||
|
||||
tbus.StripTempEvents();
|
||||
tbus.ForwardStepByTime(clippingDist, step);
|
||||
tbus.ForwardStepByTime(renderDist, step);
|
||||
tbus.BroadcastEndUpdate();
|
||||
UnityEngine.Profiling.Profiler.EndSample();
|
||||
}
|
||||
#if !NO_THREAD
|
||||
else if (loadThread != null) {
|
||||
if (texLoader != null) {
|
||||
string url = texLoader.url;
|
||||
string name = StringUtils.TrimExt(url.Substring(url.LastIndexOfAny(new char[] {'/', '\\'}) + 1));
|
||||
catch (Exception ex) {
|
||||
Game.LogException("Game", "An error occured while playing", ex);
|
||||
Popup.CreateException(ex);
|
||||
Stop();
|
||||
}
|
||||
}
|
||||
void LoadUpdate() {
|
||||
if (texLoader != null) {
|
||||
string url = texLoader.url;
|
||||
string name = StringUtils.TrimExt(url.Substring(url.LastIndexOfAny(new char[] {'/', '\\'}) + 1));
|
||||
#if UNITY_5_4_OR_NEWER
|
||||
if (texHandler.isDone) {
|
||||
var tex = texHandler.texture;
|
||||
texs.Add(name, tex);
|
||||
Logger.Log("main", 0, "Load/MainThread", "Loaded texture {0} ({1} bytes)", name, texLoader.downloadedBytes);
|
||||
texLoader.Dispose();
|
||||
texHandler.Dispose();
|
||||
texLoader = null;
|
||||
}
|
||||
else if (texLoader.downloadProgress != 0) {
|
||||
Logger.Log("main", 0, "Load/MainThread", "Loading texture {0} {1:P0}", name, texLoader.downloadProgress);
|
||||
}
|
||||
#else
|
||||
if (texLoader.isDone) {
|
||||
var tex = texLoader.texture;
|
||||
texs.Add(name, tex);
|
||||
Logger.Log("main", 0, "Load/MainThread", "Loaded texture {0} ({1} bytes)", name, texLoader.bytesDownloaded);
|
||||
texLoader.Dispose();
|
||||
texLoader = null;
|
||||
}
|
||||
else if (texLoader.progress != 0) {
|
||||
Logger.Log("main", 0, "Load/MainThread", "Loading texture {0} {1:P0}", name, texLoader.progress);
|
||||
}
|
||||
#endif
|
||||
if (texHandler.isDone) {
|
||||
var tex = texHandler.texture;
|
||||
tex.wrapMode = TextureWrapMode.Clamp;
|
||||
texs.Add(name, tex);
|
||||
texLoader.Dispose();
|
||||
texHandler.Dispose();
|
||||
texLoader = null;
|
||||
}
|
||||
if (texLoader == null)
|
||||
if (texLoadQueue.Count > 0) {
|
||||
#else
|
||||
if (texLoader.isDone) {
|
||||
var tex = texLoader.texture;
|
||||
tex.wrapMode = TextureWrapMode.Clamp;
|
||||
texs.Add(name, tex);
|
||||
texLoader.Dispose();
|
||||
texLoader = null;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
if (texLoader == null)
|
||||
if (texLoadQueue.Count > 0) {
|
||||
#if UNITY_5_4_OR_NEWER
|
||||
texHandler = new DownloadHandlerTexture();
|
||||
texLoader = new UnityWebRequest(Game.FileProtocolPrefix + texLoadQueue.Dequeue(), "GET", texHandler, null);
|
||||
texLoader.SendWebRequest();
|
||||
texHandler = new DownloadHandlerTexture();
|
||||
texLoader = new UnityWebRequest(Game.FileProtocolPrefix + texLoadQueue.Dequeue(), "GET", texHandler, null);
|
||||
texLoader.SendWebRequest();
|
||||
#else
|
||||
texLoader = new WWW(Game.FileProtocolPrefix + texLoadQueue.Dequeue());
|
||||
#endif
|
||||
}
|
||||
else if (!texloaddone) {
|
||||
texloaddone = true;
|
||||
texloadtimer.Stop();
|
||||
Logger.Log("main", 1, "Load/MainThread", "Main thread done ({0}ms)", texloadtimer.Elapsed.TotalMilliseconds);
|
||||
}
|
||||
if (!loadThread.IsAlive) {
|
||||
if (cbus == null) {
|
||||
Logger.Log("main", 4, "Load/MainThread", "Load failed");
|
||||
loadThread = null;
|
||||
}
|
||||
else if (!texloaddone) {
|
||||
texloaddone = true;
|
||||
texloadtimer.Stop();
|
||||
Logger.Log("main", 1, "Load/MainThread", "Main thread done ({0}ms)", texloadtimer.Elapsed.TotalMilliseconds);
|
||||
}
|
||||
if (!loadThread.IsAlive) {
|
||||
if (threadException != null) {
|
||||
Logger.Log("main", 4, "Load/MainThread", "Load failed");
|
||||
loadThread = null;
|
||||
Popup.CreateException(threadException);
|
||||
#if BUILD
|
||||
ReturnToMenu();
|
||||
ReturnToMenu();
|
||||
#endif
|
||||
}
|
||||
else if (texLoader == null) {
|
||||
Prehandle();
|
||||
loadThread = null;
|
||||
}
|
||||
}
|
||||
else if (texLoader == null) {
|
||||
Prehandle();
|
||||
loadThread = null;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
if (logEnabled) {
|
||||
string _logs = logs.text;
|
||||
Game.MainLogger.Enumerate((level, module, msg) => {
|
||||
string color;
|
||||
switch (level) {
|
||||
case 0: color = "#888888"; break;
|
||||
case 1: color = "#bbbbbb"; break;
|
||||
case 2: color = "#0088ff"; break;
|
||||
case 3: color = "#ffff00"; break;
|
||||
case 4: color = "#ff0000"; break;
|
||||
case 5: color = "#bb0000"; break;
|
||||
default: color = "#ff00ff"; break;
|
||||
}
|
||||
_logs += string.Format(
|
||||
"\r\n<color={1}bb><{2}> {3}</color>",
|
||||
DateTime.UtcNow.ToString("s"), color, module, msg
|
||||
);
|
||||
});
|
||||
logs.text = _logs.Substring(Mathf.Max(0, _logs.IndexOf('\n', Mathf.Max(0, _logs.Length - 4096))));
|
||||
var sttext = string.Format(
|
||||
}
|
||||
string timetext = string.Empty;
|
||||
void LogUpdate() {
|
||||
string _logs = logs.text;
|
||||
Game.MainLogger.Enumerate((level, module, msg) => {
|
||||
string color;
|
||||
switch (level) {
|
||||
case 0: color = "#888888"; break;
|
||||
case 1: color = "#bbbbbb"; break;
|
||||
case 2: color = "#0088ff"; break;
|
||||
case 3: color = "#ffff00"; break;
|
||||
case 4: color = "#ff0000"; break;
|
||||
case 5: color = "#bb0000"; break;
|
||||
default: color = "#ff00ff"; break;
|
||||
}
|
||||
_logs += string.Format(
|
||||
"\r\n<color={1}bb><{2}> {3}</color>",
|
||||
DateTime.UtcNow.ToString("s"), color, module, msg
|
||||
);
|
||||
});
|
||||
logs.text = _logs.Substring(Mathf.Max(0, _logs.IndexOf('\n', Mathf.Max(0, _logs.Length - 4096))));
|
||||
var sttext = string.Format(
|
||||
"FPS: i{0:0} / s{1:0}\nSMem: {2:N0} / {3:N0}\nIMem: {4:N0} / {5:N0}",
|
||||
1 / Time.deltaTime,
|
||||
1 / Time.smoothDeltaTime,
|
||||
@@ -239,18 +250,20 @@ namespace Cryville.Crtr {
|
||||
UnityEngine.Profiling.Profiler.GetTotalReservedMemory()
|
||||
#endif
|
||||
);
|
||||
if (started) sttext += string.Format(
|
||||
"\nSTime: {0:R}\nATime: {1:R}\nITime: {2:R}",
|
||||
cbus.Time,
|
||||
Game.AudioClient.Position - atime0,
|
||||
inputProxy.GetTimestampAverage()
|
||||
);
|
||||
if (judge != null) sttext += "\n== Scores ==\n" + judge.GetFullFormattedScoreString();
|
||||
status.text = sttext;
|
||||
}
|
||||
else {
|
||||
Game.MainLogger.Enumerate((level, module, msg) => { });
|
||||
}
|
||||
sttext += timetext;
|
||||
if (judge != null) sttext += "\n== Scores ==\n" + judge.GetFullFormattedScoreString();
|
||||
status.text = sttext;
|
||||
}
|
||||
void OnCameraPostRender(Camera cam) {
|
||||
if (!started) return;
|
||||
if (!logEnabled) return;
|
||||
timetext = string.Format(
|
||||
"\nSTime: {0:R}s {3}\ndATime: {1:+0.0ms;-0.0ms;0} {3}\ndITime: {2:+0.0ms;-0.0ms;0} {3}",
|
||||
cbus.Time,
|
||||
(Game.AudioClient.Position - atime0 - cbus.Time) * 1e3,
|
||||
(inputProxy.GetTimestampAverage() - cbus.Time) * 1e3,
|
||||
forceSyncFrames != 0 ? "(force sync)" : ""
|
||||
);
|
||||
}
|
||||
#endregion
|
||||
|
||||
@@ -271,6 +284,9 @@ namespace Cryville.Crtr {
|
||||
SceneManager.UnloadSceneAsync("Play");
|
||||
#elif UNITY_5_3_OR_NEWER
|
||||
SceneManager.UnloadScene("Play");
|
||||
#endif
|
||||
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
|
||||
DiscordController.Instance.SetIdle();
|
||||
#endif
|
||||
}
|
||||
#pragma warning restore IDE1006
|
||||
@@ -301,14 +317,13 @@ namespace Cryville.Crtr {
|
||||
autoRenderStep = renderStep == 0;
|
||||
soundOffset = Settings.Default.SoundOffset;
|
||||
startOffset = Settings.Default.StartOffset;
|
||||
sv = Settings.Default.ScrollVelocity;
|
||||
firstFrame = true;
|
||||
#if !NO_THREAD
|
||||
forceSyncFrames= Settings.Default.ForceSyncFrames;
|
||||
texloaddone = false;
|
||||
#endif
|
||||
Game.NetworkTaskWorker.SuspendBackgroundTasks();
|
||||
Game.AudioSession = Game.AudioSequencer.NewSession();
|
||||
|
||||
Camera.onPostRender += OnCameraPostRender;
|
||||
|
||||
var hitPlane = new Plane(Vector3.forward, Vector3.zero);
|
||||
var r0 = Camera.main.ViewportPointToRay(new Vector3(0, 0, 1));
|
||||
float dist;
|
||||
@@ -325,45 +340,49 @@ namespace Cryville.Crtr {
|
||||
FileInfo chartFile = new FileInfo(
|
||||
Game.GameDataPath + "/charts/" + Settings.Default.LoadChart
|
||||
);
|
||||
|
||||
FileInfo rulesetFile = new FileInfo(
|
||||
Game.GameDataPath + "/rulesets/" + Settings.Default.LoadRuleset
|
||||
);
|
||||
FileInfo skinFile = new FileInfo(
|
||||
Game.GameDataPath + "/skins/" + Settings.Default.LoadSkin
|
||||
if (!rulesetFile.Exists) throw new FileNotFoundException("Ruleset for the chart not found\nMake sure you have imported the ruleset");
|
||||
|
||||
FileInfo rulesetConfigFile = new FileInfo(
|
||||
Game.GameDataPath + "/config/rulesets/" + Settings.Default.LoadRulesetConfig
|
||||
);
|
||||
#if NO_THREAD
|
||||
texloadtimer.Stop();
|
||||
Logger.LogFormat("main", 0, "Load/MainThread", "Textures loaded successfully ({0}ms)", texloadtimer.Elapsed.TotalMilliseconds);
|
||||
Load(new LoadInfo(){
|
||||
chartFile = chartFile,
|
||||
rulesetFile = rulesetFile,
|
||||
skinFile = skinFile,
|
||||
});
|
||||
Prehandle();
|
||||
#else
|
||||
if (!rulesetConfigFile.Exists) throw new FileNotFoundException("Ruleset config not found\nPlease open the config to generate");
|
||||
using (StreamReader cfgreader = new StreamReader(rulesetConfigFile.FullName, Encoding.UTF8)) {
|
||||
_rscfg = JsonConvert.DeserializeObject<RulesetConfig>(cfgreader.ReadToEnd(), new JsonSerializerSettings() {
|
||||
MissingMemberHandling = MissingMemberHandling.Error
|
||||
});
|
||||
}
|
||||
sv = _rscfg.generic.ScrollVelocity;
|
||||
|
||||
FileInfo skinFile = new FileInfo(
|
||||
string.Format("{0}/skins/{1}/{2}/.umgs", Game.GameDataPath, rulesetFile.Directory.Name, _rscfg.generic.Skin)
|
||||
);
|
||||
if (!skinFile.Exists) throw new FileNotFoundException("Skin not found\nPlease specify an available skin in the config");
|
||||
using (StreamReader reader = new StreamReader(skinFile.FullName, Encoding.UTF8)) {
|
||||
skin = JsonConvert.DeserializeObject<Skin>(reader.ReadToEnd(), new JsonSerializerSettings() {
|
||||
MissingMemberHandling = MissingMemberHandling.Error
|
||||
});
|
||||
if (skin.format != Skin.CURRENT_FORMAT) throw new FormatException("Invalid skin file version");
|
||||
}
|
||||
|
||||
loadThread = new Thread(new ParameterizedThreadStart(Load));
|
||||
loadThread.Start(new LoadInfo() {
|
||||
chartFile = chartFile,
|
||||
rulesetFile = rulesetFile,
|
||||
skinFile = skinFile,
|
||||
});
|
||||
#endif
|
||||
|
||||
Logger.Log("main", 0, "Load/MainThread", "Loading textures...");
|
||||
texloadtimer = new diag::Stopwatch();
|
||||
texloadtimer.Start();
|
||||
frames = new Dictionary<string, SpriteFrame>();
|
||||
texs = new Dictionary<string, Texture2D>();
|
||||
var flist = skinFile.Directory.GetFiles("*.png");
|
||||
foreach (FileInfo f in flist) {
|
||||
#if NO_THREAD
|
||||
using (WWW w = new WWW("file:///" + f.FullName)) {
|
||||
string name = StringUtils.TrimExt(f.Name);
|
||||
while (!w.isDone);
|
||||
texs.Add(name, w.texture);
|
||||
}
|
||||
#else
|
||||
texLoadQueue.Enqueue(f.FullName);
|
||||
#endif
|
||||
var skinDir = skinFile.Directory.FullName;
|
||||
foreach (var f in skin.frames) {
|
||||
texLoadQueue.Enqueue(Path.Combine(skinDir, f));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -371,42 +390,35 @@ namespace Cryville.Crtr {
|
||||
try {
|
||||
diag::Stopwatch timer = new diag::Stopwatch();
|
||||
timer.Reset(); timer.Start();
|
||||
Logger.Log("main", 0, "Load/Prehandle", "Prehandling (iteration 3)");
|
||||
foreach (var i in plists) i.Init(texs);
|
||||
Logger.Log("main", 0, "Load/Prehandle", "Initializing textures");
|
||||
foreach (var t in texs) {
|
||||
if (frames.ContainsKey(t.Key)) {
|
||||
Logger.Log("main", 3, "Load/Prehandle", "Duplicated texture name: {0}", t.Key);
|
||||
continue;
|
||||
}
|
||||
var f = new Cocos2dFrames.Frame(t.Value);
|
||||
var f = new SpriteFrame(t.Value);
|
||||
f.Init();
|
||||
frames.Add(t.Key, f);
|
||||
}
|
||||
Logger.Log("main", 0, "Load/Prehandle", "Initializing states");
|
||||
cbus.BroadcastInit();
|
||||
|
||||
inputProxy = new InputProxy(pruleset, judge);
|
||||
foreach (var i in Game.InputManager._handlers) {
|
||||
/*if (i is UnityKeyHandler<UnityKeyboardReceiver>) {
|
||||
inputProxy.Set(new InputProxyEntry { Source = new InputSource { Handler = i, Type = (int)KeyCode.Z }, Target = "track0" });
|
||||
inputProxy.Set(new InputProxyEntry { Source = new InputSource { Handler = i, Type = (int)KeyCode.X }, Target = "track1" });
|
||||
inputProxy.Set(new InputProxyEntry { Source = new InputSource { Handler = i, Type = (int)KeyCode.Comma }, Target = "track2" });
|
||||
inputProxy.Set(new InputProxyEntry { Source = new InputSource { Handler = i, Type = (int)KeyCode.Period }, Target = "track3" });
|
||||
break;
|
||||
}*/
|
||||
if (i is UnityMouseHandler) {
|
||||
inputProxy.Set(new InputProxyEntry { Source = new InputSource { Handler = i, Type = 0 }, Target = "screen_x" });
|
||||
break;
|
||||
}
|
||||
Logger.Log("main", 0, "Load/Prehandle", "Prehandling (iteration 2)");
|
||||
cbus.BroadcastPreInit();
|
||||
Logger.Log("main", 0, "Load/Prehandle", "Prehandling (iteration 3)");
|
||||
using (var pbus = cbus.Clone(17)) {
|
||||
pbus.Forward();
|
||||
}
|
||||
Logger.Log("main", 0, "Load/Prehandle", "Prehandling (iteration 4)");
|
||||
cbus.BroadcastPostInit();
|
||||
inputProxy.Activate();
|
||||
|
||||
if (logEnabled) ToggleLogs();
|
||||
if (logEnabled && Settings.Default.HideLogOnPlay) ToggleLogs();
|
||||
Logger.Log("main", 0, "Load/Prehandle", "Cleaning up");
|
||||
GC.Collect();
|
||||
if (disableGC) GarbageCollector.GCMode = GarbageCollector.Mode.Disabled;
|
||||
timer.Stop();
|
||||
Logger.Log("main", 1, "Load/Prehandle", "Prehandling done ({0}ms)", timer.Elapsed.TotalMilliseconds);
|
||||
if (Settings.Default.ClearLogOnPlay) {
|
||||
logs.text = "";
|
||||
Game.MainLogger.Enumerate((level, module, msg) => { });
|
||||
}
|
||||
Game.AudioSequencer.Playing = true;
|
||||
atime0 = Game.AudioClient.BufferPosition;
|
||||
Thread.Sleep((int)((atime0 - Game.AudioClient.Position) * 1000));
|
||||
@@ -415,6 +427,7 @@ namespace Cryville.Crtr {
|
||||
}
|
||||
catch (Exception ex) {
|
||||
Game.LogException("Load/Prehandle", "An error occured while prehandling the data", ex);
|
||||
Popup.CreateException(ex);
|
||||
Stop();
|
||||
}
|
||||
}
|
||||
@@ -422,19 +435,18 @@ namespace Cryville.Crtr {
|
||||
public void Stop() {
|
||||
try {
|
||||
Logger.Log("main", 1, "Game", "Stopping");
|
||||
chart = null;
|
||||
Game.AudioSession = Game.AudioSequencer.NewSession();
|
||||
if (cbus != null) cbus.Dispose();
|
||||
if (bbus != null) bbus.Dispose();
|
||||
if (tbus != null) tbus.Dispose();
|
||||
if (nbus != null) nbus.Dispose();
|
||||
inputProxy.Deactivate();
|
||||
foreach (var t in texs) Texture.Destroy(t.Value);
|
||||
if (cbus != null) { cbus.Dispose(); cbus = null; }
|
||||
if (bbus != null) { bbus.Dispose(); bbus = null; }
|
||||
if (tbus != null) { tbus.Dispose(); tbus = null; }
|
||||
if (nbus != null) { nbus.Dispose(); nbus = null; }
|
||||
Logger.Log("main", 1, "Game", "Stopped");
|
||||
}
|
||||
catch (Exception ex) {
|
||||
if (!logEnabled) ToggleLogs();
|
||||
Game.LogException("Game", "An error occured while stopping", ex);
|
||||
Popup.CreateException(ex);
|
||||
}
|
||||
finally {
|
||||
if (started) {
|
||||
@@ -462,6 +474,7 @@ namespace Cryville.Crtr {
|
||||
public FileInfo skinFile;
|
||||
}
|
||||
|
||||
Exception threadException;
|
||||
#if !NO_THREAD
|
||||
Thread loadThread = null;
|
||||
diag::Stopwatch workerTimer;
|
||||
@@ -472,12 +485,14 @@ namespace Cryville.Crtr {
|
||||
workerTimer = new diag::Stopwatch();
|
||||
workerTimer.Start();
|
||||
RMVPool.Prepare();
|
||||
MotionCachePool.Prepare();
|
||||
LoadChart(info);
|
||||
workerTimer.Stop();
|
||||
Logger.Log("main", 1, "Load/WorkerThread", "Worker thread done ({0}ms)", workerTimer.Elapsed.TotalMilliseconds);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
Game.LogException("Load/WorkerThread", "An error occured while loading the data", ex);
|
||||
threadException = ex;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -502,14 +517,19 @@ namespace Cryville.Crtr {
|
||||
var batcher = new EventBatcher(chart);
|
||||
batcher.Forward();
|
||||
cbus = batcher.Batch();
|
||||
Logger.Log("main", 0, "Load/WorkerThread", "Batched {0} event batches", cbus.events.Count);
|
||||
|
||||
judge = new Judge(pruleset);
|
||||
etor.ContextJudge = judge;
|
||||
|
||||
LoadSkin(info.skinFile);
|
||||
|
||||
cbus.AttachSystems(pskin, judge);
|
||||
Logger.Log("main", 0, "Load/WorkerThread", "Initializing judge and input");
|
||||
judge = new Judge(pruleset);
|
||||
etor.ContextJudge = judge;
|
||||
|
||||
inputProxy = new InputProxy(pruleset, judge);
|
||||
inputProxy.LoadFrom(_rscfg.inputs);
|
||||
if (!inputProxy.IsCompleted) {
|
||||
throw new ArgumentException("Input config not completed\nPlease complete the input settings");
|
||||
}
|
||||
|
||||
Logger.Log("main", 0, "Load/WorkerThread", "Attaching handlers");
|
||||
var ch = new ChartHandler(chart, dir);
|
||||
cbus.RootState.AttachHandler(ch);
|
||||
@@ -519,20 +539,19 @@ namespace Cryville.Crtr {
|
||||
foreach (var ts in gs.Value.Children) {
|
||||
ContainerHandler th;
|
||||
if (ts.Key is Chart.Note) {
|
||||
th = new NoteHandler(gh, (Chart.Note)ts.Key, pruleset, judge);
|
||||
th = new NoteHandler((Chart.Note)ts.Key, gh);
|
||||
}
|
||||
else {
|
||||
th = new TrackHandler(gh, (Chart.Track)ts.Key);
|
||||
th = new TrackHandler((Chart.Track)ts.Key, gh);
|
||||
}
|
||||
ts.Value.AttachHandler(th);
|
||||
}
|
||||
}
|
||||
cbus.AttachSystems(pskin, judge);
|
||||
Logger.Log("main", 0, "Load/WorkerThread", "Prehandling (iteration 1)");
|
||||
cbus.Clone(16).Forward();
|
||||
Logger.Log("main", 0, "Load/WorkerThread", "Patching events");
|
||||
cbus.DoPatch();
|
||||
Logger.Log("main", 0, "Load/WorkerThread", "Prehandling (iteration 2)");
|
||||
cbus.Clone(17).Forward();
|
||||
using (var pbus = cbus.Clone(16)) {
|
||||
pbus.Forward();
|
||||
}
|
||||
|
||||
Logger.Log("main", 0, "Load/WorkerThread", "Cloning states (type 1)");
|
||||
bbus = cbus.Clone(1, -clippingDist);
|
||||
@@ -550,7 +569,7 @@ namespace Cryville.Crtr {
|
||||
ruleset = JsonConvert.DeserializeObject<Ruleset>(reader.ReadToEnd(), new JsonSerializerSettings() {
|
||||
MissingMemberHandling = MissingMemberHandling.Error
|
||||
});
|
||||
if (ruleset.format != 1) throw new FormatException("Invalid ruleset file version");
|
||||
if (ruleset.format != Ruleset.CURRENT_FORMAT) throw new FormatException("Invalid ruleset file version");
|
||||
ruleset.LoadPdt(dir);
|
||||
pruleset = ruleset.Root;
|
||||
pruleset.Optimize(etor);
|
||||
@@ -560,23 +579,9 @@ namespace Cryville.Crtr {
|
||||
void LoadSkin(FileInfo file) {
|
||||
DirectoryInfo dir = file.Directory;
|
||||
Logger.Log("main", 0, "Load/WorkerThread", "Loading skin: {0}", file);
|
||||
using (StreamReader reader = new StreamReader(file.FullName, Encoding.UTF8)) {
|
||||
skin = JsonConvert.DeserializeObject<Skin>(reader.ReadToEnd(), new JsonSerializerSettings() {
|
||||
MissingMemberHandling = MissingMemberHandling.Error
|
||||
});
|
||||
if (skin.format != 1) throw new FormatException("Invalid skin file version");
|
||||
skin.LoadPdt(dir);
|
||||
pskin = skin.Root;
|
||||
pskin.Optimize(etor);
|
||||
}
|
||||
plists = new List<Cocos2dFrames>();
|
||||
frames = new Dictionary<string, Cocos2dFrames.Frame>();
|
||||
foreach (FileInfo f in file.Directory.GetFiles("*.plist")) {
|
||||
var pobj = PlistConvert.Deserialize<Cocos2dFrames>(f.FullName);
|
||||
plists.Add(pobj);
|
||||
foreach (var i in pobj.frames)
|
||||
frames.Add(StringUtils.TrimExt(i.Key), i.Value);
|
||||
}
|
||||
skin.LoadPdt(dir);
|
||||
pskin = skin.Root;
|
||||
pskin.Optimize(etor);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
|
@@ -1,176 +0,0 @@
|
||||
using Cryville.Common;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Cryville.Crtr {
|
||||
[BinderAttribute(typeof(Cocos2dFramesBinder))]
|
||||
public class Cocos2dFrames {
|
||||
public Metadata metadata;
|
||||
public class Metadata {
|
||||
public int format;
|
||||
public Vector2 size;
|
||||
public string textureFileName;
|
||||
}
|
||||
|
||||
public Dictionary<string, Frame> frames;
|
||||
public class Frame {
|
||||
#pragma warning disable IDE1006
|
||||
Rect _frame;
|
||||
public Rect frame {
|
||||
get { return _frame; }
|
||||
set { _frame = value; }
|
||||
}
|
||||
public Rect textureRect {
|
||||
get { return _frame; }
|
||||
set { _frame = value; }
|
||||
}
|
||||
|
||||
bool _rotated = false;
|
||||
public bool rotated {
|
||||
get { return _rotated; }
|
||||
set { _rotated = value; }
|
||||
}
|
||||
public bool textureRotated {
|
||||
get { return _rotated; }
|
||||
set { _rotated = value; }
|
||||
}
|
||||
#pragma warning restore IDE1006
|
||||
|
||||
public Vector2 offset;
|
||||
|
||||
public Rect sourceColorRect;
|
||||
public Vector2 sourceSize;
|
||||
private Rect _uv;
|
||||
private Vector2[] cuv;
|
||||
public Rect UV {
|
||||
get {
|
||||
return _uv;
|
||||
}
|
||||
private set {
|
||||
_uv = value;
|
||||
float x0 = Mathf.Min(_uv.xMin, _uv.xMax);
|
||||
float x1 = Mathf.Max(_uv.xMin, _uv.xMax);
|
||||
float y0 = Mathf.Min(_uv.yMin, _uv.yMax);
|
||||
float y1 = Mathf.Max(_uv.yMin, _uv.yMax);
|
||||
if (_rotated) cuv = new Vector2[]{
|
||||
new Vector2(x0, y1),
|
||||
new Vector2(x1, y0),
|
||||
new Vector2(x0, y0),
|
||||
new Vector2(x1, y1),
|
||||
};
|
||||
else cuv = new Vector2[]{
|
||||
new Vector2(x0, y0),
|
||||
new Vector2(x1, y1),
|
||||
new Vector2(x1, y0),
|
||||
new Vector2(x0, y1),
|
||||
};
|
||||
}
|
||||
}
|
||||
public Vector2 GetUV(Vector2 uv) {
|
||||
return GetUV(uv.x, uv.y);
|
||||
}
|
||||
public Vector2 GetUV(float u, float v) {
|
||||
Vector2 uv00 = cuv[0], uv11 = cuv[1],
|
||||
uv10 = cuv[2], uv01 = cuv[3];
|
||||
return (1 - u - v) * uv00
|
||||
+ u * uv10
|
||||
+ v * uv01
|
||||
+ u * v * (uv00 + uv11 - uv10 - uv01);
|
||||
}
|
||||
public Texture2D Texture {
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
public Vector2 Size {
|
||||
get {
|
||||
return new Vector2(Texture.width, Texture.height);
|
||||
}
|
||||
}
|
||||
|
||||
public void Init() {
|
||||
if (Texture == null)
|
||||
throw new InvalidOperationException(); // TODO
|
||||
_frame = new Rect(Vector2.zero, Size);
|
||||
var w = _frame.width;
|
||||
var h = _frame.height;
|
||||
float x = _frame.x / w;
|
||||
float y = 1 - _frame.y / h;
|
||||
float tw = (_rotated ? _frame.height : _frame.width) / w;
|
||||
float th = (_rotated ? _frame.width : _frame.height) / h;
|
||||
if (_rotated) UV = new Rect(x, y, tw, -th);
|
||||
else UV = new Rect(x, y, tw, -th);
|
||||
}
|
||||
|
||||
public void Init(int w, int h, Texture2D _base) {
|
||||
if (Texture != null)
|
||||
throw new InvalidOperationException(); // TODO
|
||||
Texture = _base;
|
||||
float x = _frame.x / w;
|
||||
float y = 1 - _frame.y / h;
|
||||
float tw = (_rotated ? _frame.height : _frame.width) / w;
|
||||
float th = (_rotated ? _frame.width : _frame.height) / h;
|
||||
if (_rotated) UV = new Rect(x, y, tw, -th);
|
||||
else UV = new Rect(x, y, tw, -th);
|
||||
}
|
||||
public Frame() { }
|
||||
public Frame(Texture2D tex) {
|
||||
Texture = tex;
|
||||
}
|
||||
}
|
||||
|
||||
Texture2D _base;
|
||||
|
||||
public void Init(Dictionary<string, Texture2D> texs) {
|
||||
_base = texs[StringUtils.TrimExt(metadata.textureFileName)];
|
||||
var w = (int)metadata.size.x;
|
||||
var h = (int)metadata.size.y;
|
||||
if (w == 0 || h == 0) {
|
||||
w = _base.width;
|
||||
h = _base.height;
|
||||
}
|
||||
foreach (var f in frames) {
|
||||
f.Value.Init(w, h, _base);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class Cocos2dFramesBinder : EmptyBinder {
|
||||
public override object ChangeType(object value, Type type, CultureInfo culture) {
|
||||
if (value is string) {
|
||||
var str = (string)value;
|
||||
if (type == typeof(Rect)) {
|
||||
var m = Regex.Match(str, @"^{({.*?}),({.*?})}$");
|
||||
var p = (Vector2)ChangeType(m.Groups[1].Value, typeof(Vector2), culture);
|
||||
var s = (Vector2)ChangeType(m.Groups[2].Value, typeof(Vector2), culture);
|
||||
return new Rect(p, s);
|
||||
}
|
||||
else if (type == typeof(Vector2)) {
|
||||
var m = Regex.Match(str, @"^{(.*?),(.*?)}$");
|
||||
var w = float.Parse(m.Groups[1].Value);
|
||||
var h = float.Parse(m.Groups[2].Value);
|
||||
return new Vector2(w, h);
|
||||
}
|
||||
}
|
||||
else if (typeof(IDictionary).IsAssignableFrom(value.GetType())) {
|
||||
var dict = (IDictionary)value;
|
||||
if (type == typeof(Rect)) {
|
||||
var x = float.Parse((string)dict["x"]);
|
||||
var y = float.Parse((string)dict["y"]);
|
||||
var w = float.Parse((string)dict["w"]);
|
||||
var h = float.Parse((string)dict["h"]);
|
||||
return new Rect(x, y, w, h);
|
||||
}
|
||||
else if (type == typeof(Vector2)) {
|
||||
var w = float.Parse((string)dict["w"]);
|
||||
var h = float.Parse((string)dict["h"]);
|
||||
return new Vector2(w, h);
|
||||
}
|
||||
}
|
||||
return base.ChangeType(value, type, culture);
|
||||
}
|
||||
}
|
||||
}
|
30
Assets/Cryville/Crtr/Components/MeshBase.cs
Normal file
30
Assets/Cryville/Crtr/Components/MeshBase.cs
Normal file
@@ -0,0 +1,30 @@
|
||||
using System;
|
||||
|
||||
namespace Cryville.Crtr.Components {
|
||||
public abstract class MeshBase : SkinComponent {
|
||||
public MeshBase() {
|
||||
SubmitProperty("zindex", new PropOp.Integer(v => ZIndex = (short)v));
|
||||
}
|
||||
|
||||
protected MeshWrapper mesh = new MeshWrapper();
|
||||
|
||||
short _zindex;
|
||||
public short ZIndex {
|
||||
get {
|
||||
return _zindex;
|
||||
}
|
||||
set {
|
||||
if (value < 0 || value > 5000)
|
||||
throw new ArgumentOutOfRangeException("value", "Z-index must be in [0..5000]");
|
||||
_zindex = value;
|
||||
UpdateZIndex();
|
||||
}
|
||||
}
|
||||
protected void UpdateZIndex() {
|
||||
if (!mesh.Initialized) return;
|
||||
foreach (var mat in mesh.Renderer.materials) {
|
||||
mat.renderQueue = _zindex;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
11
Assets/Cryville/Crtr/Components/MeshBase.cs.meta
Normal file
11
Assets/Cryville/Crtr/Components/MeshBase.cs.meta
Normal file
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 75daba44e5811b943a08e6f137cc2b0c
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
@@ -5,11 +5,22 @@ using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Cryville.Crtr.Components {
|
||||
public abstract class SectionalGameObject : SkinComponent {
|
||||
public abstract class SectionalGameObject : MeshBase {
|
||||
protected Vector3? prevpt;
|
||||
protected Quaternion? prevrot;
|
||||
protected int vertCount = 0;
|
||||
protected MeshWrapper mesh = new MeshWrapper();
|
||||
Part part = Part.whole;
|
||||
enum Part {
|
||||
whole = 0,
|
||||
idle = 1,
|
||||
start = 2,
|
||||
end = 3,
|
||||
}
|
||||
|
||||
public SectionalGameObject() {
|
||||
SubmitProperty("partial", new PropOp.Boolean(v => part = Part.idle));
|
||||
SubmitProperty("part", new PropOp.Enum<Part>(v => part = v, v => (Part)v), 2);
|
||||
}
|
||||
|
||||
protected override void OnDestroy() {
|
||||
mesh.Destroy();
|
||||
@@ -24,7 +35,7 @@ namespace Cryville.Crtr.Components {
|
||||
}
|
||||
|
||||
public void AppendPoint(Vector3 p, Quaternion r) {
|
||||
if (prevpt == p && prevrot == r) return;
|
||||
if (prevpt == p && prevrot == r || ((int)part & 1) == 1) return;
|
||||
AppendPointInternal(p, r);
|
||||
// if (!headGenerated) Logger.Log("main", 0, "Skin/Polysec", "{0}", r);
|
||||
prevpt = p;
|
||||
@@ -56,8 +67,7 @@ namespace Cryville.Crtr.Components {
|
||||
SubmitProperty("head", new PropOp.String(v => head.FrameName = v));
|
||||
SubmitProperty("body", new PropOp.String(v => body.FrameName = v));
|
||||
SubmitProperty("tail", new PropOp.String(v => tail.FrameName = v));
|
||||
SubmitProperty("transparent", new PropOp.Boolean(v => transparent = v));
|
||||
SubmitProperty("shape", new op_set_shape(this));
|
||||
SubmitProperty("shape", new op_set_shape(this), 2);
|
||||
}
|
||||
|
||||
#pragma warning disable IDE1006
|
||||
@@ -94,31 +104,20 @@ namespace Cryville.Crtr.Components {
|
||||
public SpriteInfo body = new SpriteInfo();
|
||||
public SpriteInfo tail = new SpriteInfo();
|
||||
|
||||
public bool transparent;
|
||||
List<Vector3> vertices;
|
||||
List<float> lengths;
|
||||
float sumLength = 0;
|
||||
|
||||
public override void Init() {
|
||||
base.Init();
|
||||
mesh.Init(transform);
|
||||
|
||||
head.Load();
|
||||
body.Load();
|
||||
tail.Load();
|
||||
var mats = mesh.Renderer.materials = new Material[] { mesh.NewMaterial, mesh.NewMaterial, mesh.NewMaterial };
|
||||
head.Bind(mats[0]);
|
||||
body.Bind(mats[1]);
|
||||
tail.Bind(mats[2]);
|
||||
|
||||
mesh.Init(transform, transparent);
|
||||
|
||||
List<Material> materials = new List<Material>();
|
||||
if (head.FrameName != null) AddMat(materials, head.FrameName);
|
||||
if (body.FrameName != null) AddMat(materials, body.FrameName);
|
||||
if (tail.FrameName != null) AddMat(materials, tail.FrameName);
|
||||
mesh.Renderer.materials = materials.ToArray();
|
||||
}
|
||||
|
||||
void AddMat(List<Material> list, string frame) {
|
||||
var mat = mesh.NewMaterial;
|
||||
mat.mainTexture = ChartPlayer.frames[frame].Texture;
|
||||
list.Add(mat);
|
||||
UpdateZIndex();
|
||||
}
|
||||
|
||||
protected override void OnDestroy() {
|
||||
@@ -132,7 +131,6 @@ namespace Cryville.Crtr.Components {
|
||||
}
|
||||
}
|
||||
|
||||
// Vector3 prevp = Vector3.zero;
|
||||
protected override void AppendPointInternal(Vector3 p, Quaternion r) {
|
||||
if (vertices == null) {
|
||||
vertices = _ptPool.Rent();
|
||||
@@ -154,15 +152,16 @@ namespace Cryville.Crtr.Components {
|
||||
List<Vector3> verts;
|
||||
List<Vector2> uvs;
|
||||
List<int> trih = null, trib = null, trit = null;
|
||||
static List<int> _emptyTris = new List<int>();
|
||||
|
||||
public override void Seal() {
|
||||
if (vertCount <= 1 || sumLength == 0) return;
|
||||
int vcpsec = _shapeLength; // Vertex Count Per Section
|
||||
float width = GetWidth();
|
||||
float headLength = 0;
|
||||
if (head.FrameName != null) headLength = width / head.Ratio;
|
||||
if (head.Frame != null) headLength = width / head.Ratio;
|
||||
float tailLength = 0;
|
||||
if (tail.FrameName != null) tailLength = width / tail.Ratio;
|
||||
if (tail.Frame != null) tailLength = width / tail.Ratio;
|
||||
float endLength = headLength + tailLength;
|
||||
if (sumLength <= endLength) {
|
||||
// The total length of the two ends is longer than the whole mesh, squeeze the two ends
|
||||
@@ -190,17 +189,17 @@ namespace Cryville.Crtr.Components {
|
||||
verts = _vertPool.Rent(vc * vcpsec);
|
||||
uvs = _uvPool.Rent(vc * vcpsec);
|
||||
int i = 0; int t = 0; float l = 0; int m = 0;
|
||||
if (head.FrameName != null) { m++; GenerateMeshTo(verts, uvs, out trih, head, ref i, ref t, ref l, 0, headLength, vcpsec, hvc); }
|
||||
if (body.FrameName != null) { m++; GenerateMeshTo(verts, uvs, out trib, body, ref i, ref t, ref l, headLength, sumLength - tailLength, vcpsec, hvc + bvc); }
|
||||
if (tail.FrameName != null) { m++; GenerateMeshTo(verts, uvs, out trit, tail, ref i, ref t, ref l, sumLength - tailLength, sumLength, vcpsec, vc); }
|
||||
if (head.Frame != null) { m++; GenerateMeshTo(verts, uvs, out trih, head, ref i, ref t, ref l, 0, headLength, vcpsec, hvc); }
|
||||
if (body.Frame != null) { m++; GenerateMeshTo(verts, uvs, out trib, body, ref i, ref t, ref l, headLength, sumLength - tailLength, vcpsec, hvc + bvc); }
|
||||
if (tail.Frame != null) { m++; GenerateMeshTo(verts, uvs, out trit, tail, ref i, ref t, ref l, sumLength - tailLength, sumLength, vcpsec, vc); }
|
||||
|
||||
mesh.Mesh.subMeshCount = m;
|
||||
mesh.Mesh.subMeshCount = 3;
|
||||
m = 0;
|
||||
mesh.Mesh.SetVertices(verts);
|
||||
mesh.Mesh.SetUVs(0, uvs);
|
||||
if (head.FrameName != null) mesh.Mesh.SetTriangles(trih, m++);
|
||||
if (body.FrameName != null) mesh.Mesh.SetTriangles(trib, m++);
|
||||
if (tail.FrameName != null) mesh.Mesh.SetTriangles(trit, m++);
|
||||
mesh.Mesh.SetTriangles(head.Frame == null ? _emptyTris : trih, m++);
|
||||
mesh.Mesh.SetTriangles(body.Frame == null ? _emptyTris : trib, m++);
|
||||
mesh.Mesh.SetTriangles(tail.Frame == null ? _emptyTris : trit, m++);
|
||||
mesh.Mesh.RecalculateNormals();
|
||||
|
||||
_vertPool.Return(verts); verts = null;
|
||||
|
@@ -1,4 +1,5 @@
|
||||
using Cryville.Common.Pdt;
|
||||
using Cryville.Common;
|
||||
using Cryville.Common.Pdt;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
@@ -7,25 +8,32 @@ namespace Cryville.Crtr.Components {
|
||||
/// <summary>
|
||||
/// The property operators of the component.
|
||||
/// </summary>
|
||||
public Dictionary<string, PdtOperator> PropOps { get; private set; }
|
||||
public Dictionary<int, SkinProperty> Properties { get; private set; }
|
||||
/// <summary>
|
||||
/// Submits a property.
|
||||
/// </summary>
|
||||
/// <param name="name">The name of the property.</param>
|
||||
/// <param name="property">The property operator.</param>
|
||||
protected void SubmitProperty(string name, PdtOperator property) {
|
||||
PropOps.Add(name, property);
|
||||
/// <param name="property">The property.</param>
|
||||
protected void SubmitProperty(string name, PdtOperator property, int uct = 1) {
|
||||
Properties.Add(IdentifierManager.SharedInstance.Request(name), new SkinProperty(property, uct));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a skin component
|
||||
/// Creates a skin component.
|
||||
/// </summary>
|
||||
protected SkinComponent() {
|
||||
// Properties = new Dictionary<string, Property>();
|
||||
PropOps = new Dictionary<string, PdtOperator>();
|
||||
Properties = new Dictionary<int, SkinProperty>();
|
||||
}
|
||||
|
||||
public virtual void Init() { }
|
||||
protected abstract void OnDestroy();
|
||||
}
|
||||
public struct SkinProperty {
|
||||
public PdtOperator Operator { get; set; }
|
||||
public int UpdateCloneType { get; set; }
|
||||
public SkinProperty(PdtOperator op, int uct = 1) {
|
||||
Operator = op;
|
||||
UpdateCloneType = uct;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -2,14 +2,12 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace Cryville.Crtr.Components {
|
||||
public abstract class SpriteBase : SkinComponent {
|
||||
public abstract class SpriteBase : MeshBase {
|
||||
public SpriteBase() {
|
||||
SubmitProperty("bound", new op_set_bound(this));
|
||||
SubmitProperty("transparent", new PropOp.Boolean(v => transparent = v));
|
||||
SubmitProperty("pivot", new PropOp.Vector2(v => Pivot = v));
|
||||
SubmitProperty("scale", new PropOp.Vector2(v => Scale = v));
|
||||
SubmitProperty("ui", new PropOp.Boolean(v => UI = v));
|
||||
SubmitProperty("zindex", new PropOp.Integer(v => ZIndex = (short)v));
|
||||
}
|
||||
|
||||
#pragma warning disable IDE1006
|
||||
@@ -27,8 +25,6 @@ namespace Cryville.Crtr.Components {
|
||||
}
|
||||
#pragma warning restore IDE1006
|
||||
|
||||
protected MeshWrapper mesh = new MeshWrapper();
|
||||
|
||||
protected override void OnDestroy() {
|
||||
mesh.Destroy();
|
||||
}
|
||||
@@ -83,21 +79,6 @@ namespace Cryville.Crtr.Components {
|
||||
if (da.y != 0) _scale.y = dp.z / da.y;
|
||||
}
|
||||
|
||||
short _zindex;
|
||||
public short ZIndex {
|
||||
get {
|
||||
return _zindex;
|
||||
}
|
||||
set {
|
||||
_zindex = value;
|
||||
UpdateZIndex();
|
||||
}
|
||||
}
|
||||
protected void UpdateZIndex() {
|
||||
if (!mesh.Initialized) return;
|
||||
mesh.Renderer.sortingOrder = _zindex;
|
||||
}
|
||||
|
||||
static readonly Quaternion uirot
|
||||
= Quaternion.Euler(new Vector3(-90, 0, 0));
|
||||
bool _ui;
|
||||
@@ -109,10 +90,8 @@ namespace Cryville.Crtr.Components {
|
||||
}
|
||||
}
|
||||
|
||||
public bool transparent = false;
|
||||
|
||||
protected void InternalInit(string meshName = "quad") {
|
||||
mesh.Init(transform, transparent);
|
||||
mesh.Init(transform);
|
||||
mesh.Mesh = GenericResources.Meshes[meshName];
|
||||
UpdateScale();
|
||||
UpdateZIndex();
|
||||
|
@@ -4,13 +4,22 @@ using Logger = Cryville.Common.Logger;
|
||||
|
||||
namespace Cryville.Crtr.Components {
|
||||
public class SpriteInfo {
|
||||
public string FrameName;
|
||||
public Cocos2dFrames.Frame Frame {
|
||||
string m_frameName;
|
||||
public string FrameName {
|
||||
get {
|
||||
return m_frameName;
|
||||
}
|
||||
set {
|
||||
m_frameName = value;
|
||||
Reload();
|
||||
}
|
||||
}
|
||||
public SpriteFrame Frame {
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
public Rect Rect {
|
||||
get { return Frame.frame; }
|
||||
get { return Frame.Frame; }
|
||||
}
|
||||
/// <summary>
|
||||
/// The ratio of width divided by height.
|
||||
@@ -20,22 +29,39 @@ namespace Cryville.Crtr.Components {
|
||||
return Rect.width / Rect.height;
|
||||
}
|
||||
}
|
||||
bool _loaded;
|
||||
Material _mat;
|
||||
public void Bind(Material mat) {
|
||||
_loaded = true;
|
||||
_mat = mat;
|
||||
Reload();
|
||||
}
|
||||
public void Load() {
|
||||
if (FrameName != null) {
|
||||
_loaded = true;
|
||||
Reload();
|
||||
}
|
||||
public void Reload() {
|
||||
if (!_loaded) return;
|
||||
if (!string.IsNullOrEmpty(FrameName)) {
|
||||
if (ChartPlayer.frames.ContainsKey(FrameName)) {
|
||||
Frame = ChartPlayer.frames[FrameName];
|
||||
}
|
||||
else {
|
||||
Logger.Log("main", 4, "Skin", "Texture {0} not found", FrameName);
|
||||
Frame = null;
|
||||
}
|
||||
}
|
||||
else Frame = null;
|
||||
if (_mat != null) {
|
||||
_mat.mainTexture = Frame == null ? null : Frame.Texture;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class SpritePlane : SpriteBase {
|
||||
public SpritePlane() {
|
||||
SubmitProperty("frame", new PropOp.String(v => Frame = v));
|
||||
SubmitProperty("fit", new PropOp.Enum<FitMode>(v => Fit = v));
|
||||
SubmitProperty("fit", new PropOp.Enum<FitMode>(v => Fit = v, v => (FitMode)v));
|
||||
SubmitProperty("opacity", new PropOp.Float(v => Opacity = v));
|
||||
}
|
||||
|
||||
@@ -68,16 +94,11 @@ namespace Cryville.Crtr.Components {
|
||||
}
|
||||
protected void OnFrameUpdate() {
|
||||
if (!mesh.Initialized) return;
|
||||
if (frameInfo.FrameName == null) {
|
||||
if (frameInfo.Frame == null) {
|
||||
mesh.Renderer.enabled = false;
|
||||
return;
|
||||
}
|
||||
mesh.Renderer.enabled = true;
|
||||
frameInfo.Load();
|
||||
if (frameInfo.Frame != null)
|
||||
mesh.Renderer.material.mainTexture = frameInfo.Frame.Texture;
|
||||
else
|
||||
Logger.Log("main", 4, "Skin", "Unable to load texture {0}", frameInfo.FrameName);
|
||||
UpdateUV();
|
||||
UpdateScale();
|
||||
UpdateZIndex();
|
||||
@@ -140,8 +161,8 @@ namespace Cryville.Crtr.Components {
|
||||
}
|
||||
|
||||
public override void Init() {
|
||||
frameInfo.Load();
|
||||
InternalInit();
|
||||
frameInfo.Bind(mesh.Renderer.material);
|
||||
OnFrameUpdate();
|
||||
UpdateOpacity();
|
||||
}
|
||||
|
@@ -4,8 +4,6 @@ namespace Cryville.Crtr.Components {
|
||||
public class SpriteRect : SpriteBase {
|
||||
public SpriteRect() {
|
||||
SubmitProperty("color", new PropOp.Color(v => Color = v));
|
||||
|
||||
transparent = true;
|
||||
}
|
||||
|
||||
Color _color;
|
||||
|
@@ -63,13 +63,13 @@ namespace Cryville.Crtr.Components {
|
||||
case 1: x = _border.x; bx = b.x; break;
|
||||
case 2: x = _border.y; bx = b.y; break;
|
||||
case 3: x = 1; bx = 1; break;
|
||||
default: throw new Exception();
|
||||
default: throw new NotSupportedException("Built-in resource corrupted");
|
||||
}
|
||||
float y;
|
||||
switch ((int)muv[i].y) {
|
||||
case 0: y = 0; break;
|
||||
case 3: y = 1; break;
|
||||
default: throw new Exception();
|
||||
default: throw new NotSupportedException("Built-in resource corrupted");
|
||||
}
|
||||
uv[i] = frameInfo.Frame.GetUV(x, y);
|
||||
bx -= 0.5f; y -= 0.5f;
|
||||
|
@@ -1,4 +1,5 @@
|
||||
using Cryville.Common.Pdt;
|
||||
using Cryville.Common.Buffers;
|
||||
using Cryville.Common.Pdt;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
@@ -7,7 +8,7 @@ namespace Cryville.Crtr.Components {
|
||||
public class SpriteText : SpriteBase {
|
||||
public SpriteText() {
|
||||
SubmitProperty("frames", new op_set_frames(this));
|
||||
SubmitProperty("value", new PropOp.String(v => Value = v));
|
||||
SubmitProperty("value", new PropOp.TargetString(() => Value));
|
||||
SubmitProperty("size", new PropOp.Float(v => Size = v));
|
||||
SubmitProperty("spacing", new PropOp.Float(v => Spacing = v));
|
||||
SubmitProperty("opacity", new PropOp.Float(v => Opacity = v));
|
||||
@@ -41,21 +42,14 @@ namespace Cryville.Crtr.Components {
|
||||
foreach (var m in meshes) m.Value.Destroy();
|
||||
}
|
||||
|
||||
readonly Dictionary<Texture2D, MeshWrapper> meshes = new Dictionary<Texture2D, MeshWrapper>();
|
||||
Dictionary<char, SpriteInfo> m_frames;
|
||||
public Dictionary<char, SpriteInfo> Frames {
|
||||
get { return m_frames; }
|
||||
set { m_frames = value; UpdateFrames(); UpdateScale(); }
|
||||
}
|
||||
|
||||
public string m_value;
|
||||
public string Value {
|
||||
get { return m_value; }
|
||||
set {
|
||||
if (m_value == value) return;
|
||||
m_value = value; UpdateScale();
|
||||
}
|
||||
}
|
||||
readonly TargetString m_value = new TargetString();
|
||||
public TargetString Value { get { return m_value; } }
|
||||
|
||||
public float m_size;
|
||||
public float Size {
|
||||
@@ -80,30 +74,38 @@ namespace Cryville.Crtr.Components {
|
||||
float frameHeight = 0;
|
||||
foreach (var m in meshes) m.Value.Destroy();
|
||||
meshes.Clear();
|
||||
verts.Clear();
|
||||
uvs.Clear();
|
||||
foreach (var f in m_frames) {
|
||||
f.Value.Load();
|
||||
if (frameHeight == 0) frameHeight = f.Value.Rect.height;
|
||||
else if (frameHeight != f.Value.Rect.height) throw new Exception("Inconsistent frame height");
|
||||
if (!meshes.ContainsKey(f.Value.Frame.Texture)) {
|
||||
else if (frameHeight != f.Value.Rect.height) throw new Exception("Inconsistent frame height for text component");
|
||||
var tex = f.Value.Frame.Texture;
|
||||
if (!meshes.ContainsKey(tex)) {
|
||||
var m = new MeshWrapper();
|
||||
m.Init(mesh.MeshTransform, transparent);
|
||||
m.Init(mesh.MeshTransform);
|
||||
m.Mesh = new Mesh();
|
||||
m.Renderer.material.mainTexture = f.Value.Frame.Texture;
|
||||
meshes.Add(f.Value.Frame.Texture, m);
|
||||
m.Renderer.material.mainTexture = tex;
|
||||
meshes.Add(tex, m);
|
||||
verts.Add(tex, new List<Vector3>());
|
||||
uvs.Add(tex, new List<Vector2>());
|
||||
tris.Add(tex, new List<int>());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
float sum_x;
|
||||
readonly Dictionary<Texture2D, MeshWrapper> meshes = new Dictionary<Texture2D, MeshWrapper>();
|
||||
readonly Dictionary<Texture2D, List<Vector3>> verts = new Dictionary<Texture2D, List<Vector3>>();
|
||||
readonly Dictionary<Texture2D, List<Vector2>> uvs = new Dictionary<Texture2D, List<Vector2>>();
|
||||
readonly Dictionary<Texture2D, List<int>> tris = new Dictionary<Texture2D, List<int>>();
|
||||
void UpdateMeshes() {
|
||||
if (meshes.Count == 0) return;
|
||||
sum_x = 0;
|
||||
int vc = m_value.Length * 4;
|
||||
Dictionary<Texture2D, List<Vector3>> verts = new Dictionary<Texture2D, List<Vector3>>();
|
||||
Dictionary<Texture2D, List<Vector2>> uvs = new Dictionary<Texture2D, List<Vector2>>();
|
||||
foreach (var t in meshes.Keys) {
|
||||
verts.Add(t, new List<Vector3>(vc));
|
||||
uvs.Add(t, new List<Vector2>(vc));
|
||||
verts[t].Clear();
|
||||
uvs[t].Clear();
|
||||
tris[t].Clear();
|
||||
}
|
||||
foreach (var c in m_value) {
|
||||
var f = m_frames[c];
|
||||
@@ -123,18 +125,18 @@ namespace Cryville.Crtr.Components {
|
||||
var m = meshes[t].Mesh;
|
||||
m.Clear();
|
||||
int cc = verts[t].Count / 4;
|
||||
int[] tris = new int[cc * 6];
|
||||
var _tris = tris[t];
|
||||
for (int i = 0; i < cc; i++) {
|
||||
tris[i * 6 ] = i * 4 ;
|
||||
tris[i * 6 + 1] = i * 4 + 3;
|
||||
tris[i * 6 + 2] = i * 4 + 1;
|
||||
tris[i * 6 + 3] = i * 4 + 1;
|
||||
tris[i * 6 + 4] = i * 4 + 3;
|
||||
tris[i * 6 + 5] = i * 4 + 2;
|
||||
_tris.Add(i * 4);
|
||||
_tris.Add(i * 4 + 3);
|
||||
_tris.Add(i * 4 + 1);
|
||||
_tris.Add(i * 4 + 1);
|
||||
_tris.Add(i * 4 + 3);
|
||||
_tris.Add(i * 4 + 2);
|
||||
}
|
||||
m.vertices = verts[t].ToArray();
|
||||
m.uv = uvs[t].ToArray();
|
||||
m.triangles = tris;
|
||||
m.SetVertices(verts[t]);
|
||||
m.SetUVs(0, uvs[t]);
|
||||
m.SetTriangles(tris[t], 0);
|
||||
m.RecalculateNormals();
|
||||
}
|
||||
sum_x -= m_spacing;
|
||||
@@ -174,6 +176,7 @@ namespace Cryville.Crtr.Components {
|
||||
UpdateFrames();
|
||||
mesh.Mesh.Clear();
|
||||
UpdateScale();
|
||||
Value.OnUpdate += UpdateScale;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,8 +1,82 @@
|
||||
using UnityEngine;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityEngine.SceneManagement;
|
||||
|
||||
namespace Cryville.Crtr.Config {
|
||||
public class ConfigScene : MonoBehaviour {
|
||||
[SerializeField]
|
||||
Transform m_content;
|
||||
|
||||
[SerializeField]
|
||||
SettingsPanel m_genericConfigPanel;
|
||||
|
||||
[SerializeField]
|
||||
InputConfigPanel m_inputConfigPanel;
|
||||
|
||||
public Ruleset ruleset;
|
||||
RulesetConfig _rscfg;
|
||||
|
||||
void Start() {
|
||||
ChartPlayer.etor = new PdtEvaluator();
|
||||
FileInfo file = new FileInfo(
|
||||
Game.GameDataPath + "/rulesets/" + Settings.Default.LoadRuleset
|
||||
);
|
||||
if (!file.Exists) {
|
||||
Popup.Create("Ruleset for the chart not found\nMake sure you have imported the ruleset");
|
||||
ReturnToMenu();
|
||||
return;
|
||||
}
|
||||
DirectoryInfo dir = file.Directory;
|
||||
using (StreamReader reader = new StreamReader(file.FullName, Encoding.UTF8)) {
|
||||
ruleset = JsonConvert.DeserializeObject<Ruleset>(reader.ReadToEnd(), new JsonSerializerSettings() {
|
||||
MissingMemberHandling = MissingMemberHandling.Error
|
||||
});
|
||||
if (ruleset.format != Ruleset.CURRENT_FORMAT) throw new FormatException("Invalid ruleset file version");
|
||||
ruleset.LoadPdt(dir);
|
||||
}
|
||||
FileInfo cfgfile = new FileInfo(
|
||||
Game.GameDataPath + "/config/rulesets/" + Settings.Default.LoadRulesetConfig
|
||||
);
|
||||
if (!cfgfile.Exists) {
|
||||
if (!cfgfile.Directory.Exists) cfgfile.Directory.Create();
|
||||
_rscfg = new RulesetConfig();
|
||||
}
|
||||
else {
|
||||
using (StreamReader cfgreader = new StreamReader(cfgfile.FullName, Encoding.UTF8)) {
|
||||
_rscfg = JsonConvert.DeserializeObject<RulesetConfig>(cfgreader.ReadToEnd(), new JsonSerializerSettings() {
|
||||
MissingMemberHandling = MissingMemberHandling.Error
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
m_genericConfigPanel.Target = _rscfg.generic;
|
||||
|
||||
var proxy = new InputProxy(ruleset.Root, null);
|
||||
proxy.LoadFrom(_rscfg.inputs);
|
||||
m_inputConfigPanel.proxy = proxy;
|
||||
}
|
||||
|
||||
public void SwitchCategory(GameObject cat) {
|
||||
foreach (Transform c in m_content) {
|
||||
c.gameObject.SetActive(false);
|
||||
}
|
||||
cat.SetActive(true);
|
||||
}
|
||||
|
||||
public void SaveAndReturnToMenu() {
|
||||
m_inputConfigPanel.proxy.SaveTo(_rscfg.inputs);
|
||||
m_inputConfigPanel.proxy.Dispose();
|
||||
FileInfo cfgfile = new FileInfo(
|
||||
Game.GameDataPath + "/config/rulesets/" + Settings.Default.LoadRulesetConfig
|
||||
);
|
||||
using (StreamWriter cfgwriter = new StreamWriter(cfgfile.FullName, false, Encoding.UTF8)) {
|
||||
cfgwriter.Write(JsonConvert.SerializeObject(_rscfg, Game.GlobalJsonSerializerSettings));
|
||||
}
|
||||
ReturnToMenu();
|
||||
}
|
||||
public void ReturnToMenu() {
|
||||
GameObject.Find("Master").GetComponent<Master>().ShowMenu();
|
||||
#if UNITY_5_5_OR_NEWER
|
||||
|
@@ -1,15 +1,14 @@
|
||||
using Cryville.Common.Unity;
|
||||
using Cryville.Common.Unity.Input;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
||||
namespace Cryville.Crtr.Config {
|
||||
public class InputConfig : MonoBehaviour {
|
||||
public class InputConfigPanel : MonoBehaviour {
|
||||
[SerializeField]
|
||||
ConfigScene m_configScene;
|
||||
|
||||
[SerializeField]
|
||||
GameObject m_inputDialog;
|
||||
|
||||
@@ -25,54 +24,45 @@ namespace Cryville.Crtr.Config {
|
||||
[SerializeField]
|
||||
GameObject m_prefabInputConfigEntry;
|
||||
|
||||
InputProxy _proxy;
|
||||
Dictionary<string, InputConfigEntry> _entries = new Dictionary<string, InputConfigEntry>();
|
||||
readonly SimpleInputConsumer _consumer = new SimpleInputConsumer(Game.InputManager);
|
||||
public InputProxy proxy;
|
||||
readonly Dictionary<string, InputConfigPanelEntry> _entries = new Dictionary<string, InputConfigPanelEntry>();
|
||||
|
||||
string _sel;
|
||||
public void OpenDialog(string entry) {
|
||||
_sel = entry;
|
||||
m_inputDialog.SetActive(true);
|
||||
Game.InputManager.Activate();
|
||||
CallHelper.Purge(m_deviceList);
|
||||
_consumer.EnumerateEvents(ev => { });
|
||||
_recvsrcs.Clear();
|
||||
AddSourceItem(null);
|
||||
}
|
||||
|
||||
public void CloseDialog() {
|
||||
m_inputDialog.SetActive(false);
|
||||
Game.InputManager.Deactivate();
|
||||
}
|
||||
|
||||
public void CloseDialog(InputSource? src) {
|
||||
_proxy.Set(new InputProxyEntry {
|
||||
proxy.Set(new InputProxyEntry {
|
||||
Target = _sel,
|
||||
Source = src,
|
||||
});
|
||||
m_inputDialog.SetActive(false);
|
||||
Game.InputManager.Deactivate();
|
||||
CloseDialog();
|
||||
}
|
||||
|
||||
void Start() {
|
||||
ChartPlayer.etor = new PdtEvaluator();
|
||||
FileInfo file = new FileInfo(
|
||||
Game.GameDataPath + "/rulesets/" + Settings.Default.LoadRuleset
|
||||
);
|
||||
DirectoryInfo dir = file.Directory;
|
||||
using (StreamReader reader = new StreamReader(file.FullName, Encoding.UTF8)) {
|
||||
var ruleset = JsonConvert.DeserializeObject<Ruleset>(reader.ReadToEnd(), new JsonSerializerSettings() {
|
||||
MissingMemberHandling = MissingMemberHandling.Error
|
||||
});
|
||||
if (ruleset.format != 1) throw new FormatException("Invalid ruleset file version");
|
||||
ruleset.LoadPdt(dir);
|
||||
_proxy = new InputProxy(ruleset.Root, null);
|
||||
foreach (var i in ruleset.Root.inputs) {
|
||||
var e = GameObject.Instantiate(m_prefabInputConfigEntry).GetComponent<InputConfigEntry>();
|
||||
e.transform.SetParent(m_entryList.transform);
|
||||
_entries.Add(i.Key, e);
|
||||
e.SetKey(this, i.Key);
|
||||
}
|
||||
_proxy.ProxyChanged += OnProxyChanged;
|
||||
_consumer.Activate();
|
||||
foreach (var i in m_configScene.ruleset.Root.inputs) {
|
||||
var e = GameObject.Instantiate(m_prefabInputConfigEntry, m_entryList.transform).GetComponent<InputConfigPanelEntry>();
|
||||
_entries.Add(i.Key, e);
|
||||
e.SetKey(this, i.Key);
|
||||
OnProxyChanged(this, proxy[i.Key]);
|
||||
}
|
||||
proxy.ProxyChanged += OnProxyChanged;
|
||||
}
|
||||
|
||||
void OnDestroy() {
|
||||
_consumer.Deactivate();
|
||||
}
|
||||
|
||||
void OnProxyChanged(object sender, ProxyChangedEventArgs e) {
|
||||
@@ -83,7 +73,7 @@ namespace Cryville.Crtr.Config {
|
||||
readonly List<InputSource?> _recvsrcs = new List<InputSource?>();
|
||||
void Update() {
|
||||
if (m_inputDialog.activeSelf) {
|
||||
Game.InputManager.EnumerateEvents(ev => {
|
||||
_consumer.EnumerateEvents(ev => {
|
||||
AddSourceItem(ev.Id.Source);
|
||||
});
|
||||
}
|
||||
@@ -92,11 +82,10 @@ namespace Cryville.Crtr.Config {
|
||||
void AddSourceItem(InputSource? src) {
|
||||
if (_recvsrcs.Contains(src)) return;
|
||||
_recvsrcs.Add(src);
|
||||
var obj = Instantiate(m_prefabListItem);
|
||||
obj.transform.SetParent(m_deviceList);
|
||||
var obj = Instantiate(m_prefabListItem, m_deviceList);
|
||||
obj.transform.Find("Text").GetComponent<Text>().text = src == null ? "None" : src.Value.Handler.GetTypeName(src.Value.Type);
|
||||
var btn = obj.GetComponent<Button>();
|
||||
if (src != null) btn.interactable = !_proxy.IsUsed(src.Value);
|
||||
if (src != null) btn.interactable = !proxy.IsUsed(src.Value);
|
||||
btn.onClick.AddListener(() => {
|
||||
CloseDialog(src);
|
||||
});
|
@@ -2,7 +2,7 @@
|
||||
using UnityEngine.UI;
|
||||
|
||||
namespace Cryville.Crtr.Config {
|
||||
public class InputConfigEntry : MonoBehaviour {
|
||||
public class InputConfigPanelEntry : MonoBehaviour {
|
||||
[SerializeField]
|
||||
Text m_key;
|
||||
|
||||
@@ -12,7 +12,7 @@ namespace Cryville.Crtr.Config {
|
||||
[SerializeField]
|
||||
Button m_button;
|
||||
|
||||
public void SetKey(InputConfig master, string name) {
|
||||
public void SetKey(InputConfigPanel master, string name) {
|
||||
m_key.text = name;
|
||||
m_value.text = "None";
|
||||
m_button.onClick.AddListener(() => {
|
32
Assets/Cryville/Crtr/Config/RulesetConfig.cs
Normal file
32
Assets/Cryville/Crtr/Config/RulesetConfig.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
using Cryville.Common.ComponentModel;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace Cryville.Crtr.Config {
|
||||
public class RulesetConfig {
|
||||
public Generic generic = new Generic();
|
||||
public class Generic {
|
||||
[Category("basic")]
|
||||
[JsonProperty("skin")]
|
||||
public string Skin { get; set; }
|
||||
|
||||
[Category("deprecated")][Obsolete]
|
||||
[JsonProperty("scroll_velocity")][DefaultValue(1)]
|
||||
[LogarithmicScale][Step(0.5f)][Precision(1e-1)]
|
||||
public float ScrollVelocity { get; set; }
|
||||
|
||||
public Generic() {
|
||||
Skin = "";
|
||||
ScrollVelocity = 1;
|
||||
}
|
||||
}
|
||||
public Dictionary<string, InputEntry> inputs
|
||||
= new Dictionary<string, InputEntry>();
|
||||
public class InputEntry {
|
||||
public string handler;
|
||||
public int type;
|
||||
}
|
||||
}
|
||||
}
|
11
Assets/Cryville/Crtr/Config/RulesetConfig.cs.meta
Normal file
11
Assets/Cryville/Crtr/Config/RulesetConfig.cs.meta
Normal file
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: aa140184f4b7acb4b994a0826e1f107d
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
78
Assets/Cryville/Crtr/DiscordController.cs
Normal file
78
Assets/Cryville/Crtr/DiscordController.cs
Normal file
@@ -0,0 +1,78 @@
|
||||
using Discord;
|
||||
using System;
|
||||
using UnityEngine;
|
||||
using Logger = Cryville.Common.Logger;
|
||||
|
||||
namespace Cryville.Crtr {
|
||||
internal class DiscordController : MonoBehaviour {
|
||||
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
|
||||
public static DiscordController Instance;
|
||||
|
||||
const long CLIENT_ID = 1059021675578007622L;
|
||||
|
||||
Discord.Discord dc;
|
||||
ActivityManager am;
|
||||
long launchTime;
|
||||
|
||||
void Start() {
|
||||
Instance = this;
|
||||
launchTime = (long)(DateTime.UtcNow - DateTime.UnixEpoch).TotalSeconds;
|
||||
try {
|
||||
dc = new Discord.Discord(CLIENT_ID, (UInt64)CreateFlags.NoRequireDiscord);
|
||||
Logger.Log("main", 1, "Discord", "Connected to Discord");
|
||||
am = dc.GetActivityManager();
|
||||
SetIdle();
|
||||
}
|
||||
catch (ResultException) {
|
||||
if (dc != null) {
|
||||
dc.Dispose();
|
||||
dc = null;
|
||||
}
|
||||
Logger.Log("main", 3, "Discord", "Cannot connect to Discord");
|
||||
}
|
||||
}
|
||||
|
||||
void Update() {
|
||||
if (dc == null) return;
|
||||
try {
|
||||
dc.RunCallbacks();
|
||||
}
|
||||
catch (ResultException ex) {
|
||||
dc.Dispose();
|
||||
dc = null;
|
||||
Logger.Log("main", 4, "Discord", "An error occured while running callbacks: {0}", ex);
|
||||
}
|
||||
}
|
||||
|
||||
void OnApplicationQuit() {
|
||||
if (dc == null) return;
|
||||
dc.Dispose();
|
||||
}
|
||||
|
||||
void Callback(Result result) { }
|
||||
|
||||
public void SetIdle() {
|
||||
if (dc == null) return;
|
||||
am.UpdateActivity(new Activity {
|
||||
State = "Idle",
|
||||
Instance = false,
|
||||
Timestamps = { Start = launchTime },
|
||||
}, Callback);
|
||||
}
|
||||
|
||||
public void SetPlaying(string detail, double? duration) {
|
||||
if (dc == null) return;
|
||||
long now = (long)(DateTime.UtcNow - DateTime.UnixEpoch).TotalSeconds;
|
||||
am.UpdateActivity(new Activity {
|
||||
State = "Playing a chart",
|
||||
Details = detail,
|
||||
Instance = true,
|
||||
Timestamps = {
|
||||
Start = now,
|
||||
End = duration == null ? 0 : now + (long)duration,
|
||||
},
|
||||
}, Callback);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
11
Assets/Cryville/Crtr/DiscordController.cs.meta
Normal file
11
Assets/Cryville/Crtr/DiscordController.cs.meta
Normal file
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7f7c5da9a520bef4e832e2f89f7b737f
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
@@ -1,6 +1,9 @@
|
||||
using Cryville.Common;
|
||||
using Cryville.Common.Buffers;
|
||||
using Cryville.Crtr.Components;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Cryville.Crtr.Event {
|
||||
@@ -33,56 +36,63 @@ namespace Cryville.Crtr.Event {
|
||||
/// <summary>
|
||||
/// <see cref="GameObject"/> group, the <see cref="Transform"/> containing all the generated elements in the <see cref="ContainerHandler"/>.
|
||||
/// </summary>
|
||||
public Transform gogroup;
|
||||
protected Transform gogroup;
|
||||
public SkinContext SkinContext;
|
||||
|
||||
public readonly Dictionary<string, Anchor> Anchors = new Dictionary<string, Anchor>();
|
||||
public Transform a_head;
|
||||
public Transform a_tail;
|
||||
public Vector3 Position {
|
||||
get;
|
||||
protected set;
|
||||
}
|
||||
public Quaternion Rotation {
|
||||
get;
|
||||
protected set;
|
||||
}
|
||||
public bool Alive {
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
public bool Awoken {
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
public bool Disposed {
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
public Vector3 Position { get; protected set; }
|
||||
public Quaternion Rotation { get; protected set; }
|
||||
public bool Alive { get; private set; }
|
||||
public bool Awoken { get; private set; }
|
||||
public bool Disposed { get; private set; }
|
||||
|
||||
public EventContainer Container {
|
||||
get { return cs.Container; }
|
||||
}
|
||||
|
||||
SkinContainer skinContainer;
|
||||
protected Judge judge;
|
||||
public void AttachSystems(PdtSkin skin, Judge judge) {
|
||||
skinContainer = new SkinContainer(skin);
|
||||
this.judge = judge;
|
||||
}
|
||||
|
||||
public ContainerHandler() { }
|
||||
public abstract string TypeName {
|
||||
get;
|
||||
}
|
||||
public readonly Dictionary<int, List<Anchor>> Anchors = new Dictionary<int, List<Anchor>>();
|
||||
public Anchor OpenedAnchor;
|
||||
protected Anchor a_cur;
|
||||
protected Anchor a_head;
|
||||
protected Anchor a_tail;
|
||||
protected readonly static int _a_cur = IdentifierManager.SharedInstance.Request("cur");
|
||||
protected readonly static int _a_head = IdentifierManager.SharedInstance.Request("head");
|
||||
protected readonly static int _a_tail = IdentifierManager.SharedInstance.Request("tail");
|
||||
public virtual void PreInit() {
|
||||
gogroup = new GameObject(TypeName + ":" + Container.GetHashCode().ToString()).transform;
|
||||
gogroup = new GameObject(TypeName + ":" + Container.GetHashCode().ToString(CultureInfo.InvariantCulture)).transform;
|
||||
SkinContext = new SkinContext(gogroup);
|
||||
if (cs.Parent != null)
|
||||
gogroup.SetParent(cs.Parent.Handler.gogroup, false);
|
||||
a_head = new GameObject("::head").transform;
|
||||
a_head.SetParent(gogroup, false);
|
||||
Anchors.Add("head", new Anchor() { Transform = a_head });
|
||||
a_tail = new GameObject("::tail").transform;
|
||||
a_tail.SetParent(gogroup, false);
|
||||
Anchors.Add("tail", new Anchor() { Transform = a_tail });
|
||||
a_cur = RegisterAnchor(_a_cur);
|
||||
a_head = RegisterAnchor(_a_head);
|
||||
a_tail = RegisterAnchor(_a_tail);
|
||||
}
|
||||
protected Anchor RegisterAnchor(int name, bool hasPropSrcs = false) {
|
||||
var go = new GameObject("." + IdentifierManager.SharedInstance.Retrieve(name)).transform;
|
||||
go.SetParent(gogroup, false);
|
||||
var result = new Anchor(name, go, hasPropSrcs);
|
||||
List<Anchor> list;
|
||||
if (!Anchors.TryGetValue(name, out list))
|
||||
Anchors.Add(name, list = new List<Anchor>());
|
||||
list.Add(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called upon initialization of <see cref="cs" />.
|
||||
/// Called upon StartUpdate of ps 17.
|
||||
/// </summary>
|
||||
public virtual void Init() {
|
||||
cs.skinContainer.MatchStatic(cs);
|
||||
skinContainer.MatchStatic(ps);
|
||||
foreach (var i in gogroup.GetComponentsInChildren<SkinComponent>())
|
||||
i.Init();
|
||||
}
|
||||
@@ -98,12 +108,14 @@ namespace Cryville.Crtr.Event {
|
||||
Alive = false;
|
||||
}
|
||||
protected virtual void PreAwake(ContainerState s) {
|
||||
if (gogroup) gogroup.gameObject.SetActive(true);
|
||||
if (gogroup) {
|
||||
gogroup.gameObject.SetActive(true);
|
||||
OpenAnchor(a_head);
|
||||
}
|
||||
Awoken = true; Alive = true;
|
||||
OpenAnchor("head");
|
||||
}
|
||||
protected virtual void Awake(ContainerState s) {
|
||||
CloseAnchor("head");
|
||||
if (gogroup) CloseAnchor();
|
||||
}
|
||||
protected virtual void GetPosition(ContainerState s) { }
|
||||
public virtual void StartUpdate(ContainerState s) {
|
||||
@@ -111,27 +123,68 @@ namespace Cryville.Crtr.Event {
|
||||
PreAwake(s);
|
||||
Awake(s);
|
||||
}
|
||||
else if (s.CloneType == 17) {
|
||||
Init();
|
||||
}
|
||||
}
|
||||
static readonly SimpleObjectPool<StampedEvent.Anchor> anchorEvPool
|
||||
= new SimpleObjectPool<StampedEvent.Anchor>(1024);
|
||||
protected void PushAnchorEvent(double time, Anchor anchor) {
|
||||
var tev = anchorEvPool.Rent();
|
||||
tev.Time = time;
|
||||
tev.Container = Container;
|
||||
tev.Target = anchor;
|
||||
ts.Bus.PushTempEvent(tev);
|
||||
}
|
||||
public virtual void Discard(ContainerState s, StampedEvent ev) {
|
||||
if (ev is StampedEvent.Anchor) {
|
||||
anchorEvPool.Return((StampedEvent.Anchor)ev);
|
||||
}
|
||||
}
|
||||
public virtual void Update(ContainerState s, StampedEvent ev) {
|
||||
bool flag = !Awoken && s.CloneType >= 2 && s.CloneType < 16;
|
||||
if (flag) PreAwake(s);
|
||||
if (Awoken && s.CloneType <= 2) if (gogroup) cs.skinContainer.MatchDynamic(s);
|
||||
if (gogroup && s.CloneType <= 2) skinContainer.MatchDynamic(s);
|
||||
if (flag) Awake(s);
|
||||
}
|
||||
public virtual void ExUpdate(ContainerState s, StampedEvent ev) { }
|
||||
public virtual void ExUpdate(ContainerState s, StampedEvent ev) {
|
||||
if (ev is StampedEvent.Anchor) {
|
||||
var tev = (StampedEvent.Anchor)ev;
|
||||
if (gogroup) {
|
||||
OpenAnchor(tev.Target);
|
||||
#if UNITY_5_6_OR_NEWER
|
||||
tev.Target.Transform.SetPositionAndRotation(Position, Rotation);
|
||||
#else
|
||||
tev.Target.Transform.position = GetCurrentWorldPoint();
|
||||
tev.Target.Transform.rotation = Quaternion.Euler(s.Direction);
|
||||
#endif
|
||||
skinContainer.MatchDynamic(s);
|
||||
CloseAnchor();
|
||||
}
|
||||
anchorEvPool.Return(tev);
|
||||
}
|
||||
}
|
||||
public virtual void MotionUpdate(byte ct, Chart.Motion ev) { }
|
||||
public virtual void EndUpdate(ContainerState s) {
|
||||
if (s.CloneType < 16) {
|
||||
Awoken = false;
|
||||
if (gogroup && s.CloneType <= 2) cs.skinContainer.MatchDynamic(s);
|
||||
if (gogroup && s.CloneType <= 2) {
|
||||
OpenAnchor(a_tail);
|
||||
skinContainer.MatchDynamic(s);
|
||||
CloseAnchor();
|
||||
}
|
||||
}
|
||||
}
|
||||
public virtual void Anchor() { }
|
||||
protected void OpenAnchor(string name) {
|
||||
if (Anchors.ContainsKey(name)) Anchors[name].Open();
|
||||
public virtual void Anchor() {
|
||||
skinContainer.MatchDynamic(cs);
|
||||
if (cs.Working) PushAnchorEvent(cs.Time, a_cur);
|
||||
}
|
||||
protected void CloseAnchor(string name) {
|
||||
if (Anchors.ContainsKey(name)) Anchors[name].Close();
|
||||
protected void OpenAnchor(Anchor anchor) {
|
||||
if (OpenedAnchor != null) throw new InvalidOperationException("An anchor has been opened");
|
||||
OpenedAnchor = anchor;
|
||||
}
|
||||
protected void CloseAnchor() {
|
||||
OpenedAnchor = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -9,6 +9,7 @@ namespace Cryville.Crtr.Event {
|
||||
public class ContainerState {
|
||||
public EventBus Bus;
|
||||
public EventContainer Container;
|
||||
public StampedEvent StampedContainer;
|
||||
public ContainerState Parent = null;
|
||||
public ushort Depth;
|
||||
|
||||
@@ -38,6 +39,7 @@ namespace Cryville.Crtr.Event {
|
||||
InvalidatedChildren.Clear();
|
||||
}
|
||||
|
||||
public bool Active { get; set; }
|
||||
private bool m_Working;
|
||||
public bool Working {
|
||||
get { return m_Working; }
|
||||
@@ -50,25 +52,23 @@ namespace Cryville.Crtr.Event {
|
||||
public byte CloneType;
|
||||
private ContainerState rootPrototype = null;
|
||||
private ContainerState prototype = null;
|
||||
public SkinContainer skinContainer;
|
||||
public Judge judge;
|
||||
|
||||
public ContainerHandler Handler {
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
|
||||
public float Time {
|
||||
public double Time {
|
||||
get {
|
||||
return Bus.Time;
|
||||
}
|
||||
}
|
||||
|
||||
readonly RMVPool RMVPool = new RMVPool();
|
||||
protected Dictionary<StampedEvent, RealtimeMotionValue> PlayingMotions = new Dictionary<StampedEvent, RealtimeMotionValue>();
|
||||
protected Dictionary<Identifier, RealtimeMotionValue> Values;
|
||||
protected Dictionary<Identifier, Vector> CachedValues;
|
||||
protected Dictionary<Identifier, bool> CachedValueStates;
|
||||
readonly MotionCachePool MCPool = new MotionCachePool();
|
||||
Dictionary<StampedEvent, RealtimeMotionValue> PlayingMotions = new Dictionary<StampedEvent, RealtimeMotionValue>(4);
|
||||
Dictionary<Identifier, RealtimeMotionValue> Values;
|
||||
Dictionary<Identifier, MotionCache> CachedValues;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a motion value.
|
||||
@@ -77,22 +77,19 @@ namespace Cryville.Crtr.Event {
|
||||
/// <param name="clone">Returns a cloned motion value instead.</param>
|
||||
/// <returns>A motion value.</returns>
|
||||
RealtimeMotionValue GetMotionValue(Identifier name, bool clone = false) {
|
||||
RealtimeMotionValue value;
|
||||
if (!Values.TryGetValue(name, out value)) {
|
||||
value = new RealtimeMotionValue().Init(Parent == null
|
||||
? ChartPlayer.motionRegistry[name].GlobalInitValue
|
||||
: ChartPlayer.motionRegistry[name].InitValue
|
||||
);
|
||||
Values.Add(name, value);
|
||||
}
|
||||
RealtimeMotionValue value = Values[name];
|
||||
if (clone) return value.Clone();
|
||||
return value;
|
||||
}
|
||||
|
||||
void InvalidateMotion(Identifier name) {
|
||||
CachedValueStates[name] = false;
|
||||
foreach (var c in Children)
|
||||
c.Value.InvalidateMotion(name);
|
||||
MotionCache cache;
|
||||
if (!CachedValues.TryGetValue(name, out cache))
|
||||
CachedValues.Add(name, cache = MCPool.Rent(name));
|
||||
cache.Valid = false;
|
||||
ValidateChildren();
|
||||
foreach (var c in WorkingChildren)
|
||||
Children[c].InvalidateMotion(name);
|
||||
}
|
||||
|
||||
public ContainerState(Chart c, EventContainer _ev, ContainerState parent = null) {
|
||||
@@ -104,8 +101,7 @@ namespace Cryville.Crtr.Event {
|
||||
}
|
||||
|
||||
Values = new Dictionary<Identifier, RealtimeMotionValue>(ChartPlayer.motionRegistry.Count);
|
||||
CachedValues = new Dictionary<Identifier, Vector>(ChartPlayer.motionRegistry.Count);
|
||||
CachedValueStates = new Dictionary<Identifier, bool>(ChartPlayer.motionRegistry.Count);
|
||||
CachedValues = new Dictionary<Identifier, MotionCache>(ChartPlayer.motionRegistry.Count);
|
||||
foreach (var m in ChartPlayer.motionRegistry)
|
||||
Values.Add(m.Key, new RealtimeMotionValue().Init(Parent == null ? m.Value.GlobalInitValue : m.Value.InitValue));
|
||||
}
|
||||
@@ -126,18 +122,14 @@ namespace Cryville.Crtr.Event {
|
||||
}
|
||||
r.Values = mvs;
|
||||
|
||||
var cvs = new Dictionary<Identifier, Vector>(ChartPlayer.motionRegistry.Count);
|
||||
var cvs = new Dictionary<Identifier, MotionCache>(ChartPlayer.motionRegistry.Count);
|
||||
foreach (var cv in CachedValues) {
|
||||
cvs.Add(cv.Key, cv.Value.Clone());
|
||||
var dv = r.MCPool.Rent(cv.Key);
|
||||
cv.Value.CopyTo(dv);
|
||||
cvs.Add(cv.Key, dv);
|
||||
}
|
||||
r.CachedValues = cvs;
|
||||
|
||||
var cvss = new Dictionary<Identifier, bool>(ChartPlayer.motionRegistry.Count);
|
||||
foreach (var cv in CachedValueStates) {
|
||||
cvss.Add(cv.Key, cv.Value);
|
||||
}
|
||||
r.CachedValueStates = cvss;
|
||||
|
||||
r.Children = new Dictionary<EventContainer, ContainerState>();
|
||||
foreach (var child in Children) {
|
||||
var cc = child.Value.Clone(ct);
|
||||
@@ -145,7 +137,7 @@ namespace Cryville.Crtr.Event {
|
||||
AddChild(child.Key, cc, r);
|
||||
}
|
||||
|
||||
var pms = new Dictionary<StampedEvent, RealtimeMotionValue>(PlayingMotions.Count);
|
||||
var pms = new Dictionary<StampedEvent, RealtimeMotionValue>(Math.Max(4, PlayingMotions.Count));
|
||||
foreach (var m in PlayingMotions)
|
||||
pms.Add(m.Key, m.Value);
|
||||
r.PlayingMotions = pms;
|
||||
@@ -171,20 +163,21 @@ namespace Cryville.Crtr.Event {
|
||||
else dest.Values.Add(mv.Key, mv.Value.Clone());
|
||||
}
|
||||
|
||||
foreach (var cv in dest.CachedValues) cv.Value.Valid = false;
|
||||
foreach (var cv in CachedValues) {
|
||||
Vector dv;
|
||||
if(dest.CachedValues.TryGetValue(cv.Key, out dv)) cv.Value.CopyTo(dv);
|
||||
else dest.CachedValues.Add(cv.Key, cv.Value.Clone());
|
||||
MotionCache dv;
|
||||
if (!dest.CachedValues.TryGetValue(cv.Key, out dv)) {
|
||||
dest.CachedValues.Add(cv.Key, dv = dest.MCPool.Rent(cv.Key));
|
||||
}
|
||||
cv.Value.CopyTo(dv);
|
||||
}
|
||||
foreach (var cvs in CachedValueStates) dest.CachedValueStates[cvs.Key] = cvs.Value;
|
||||
|
||||
if (ct != 1) foreach (var cev in WorkingChildren)
|
||||
Children[cev].CopyTo(ct, dest.Children[cev]);
|
||||
else foreach (var child in Children)
|
||||
child.Value.CopyTo(ct, dest.Children[child.Key]);
|
||||
ValidateChildren();
|
||||
dest.ValidateChildren();
|
||||
|
||||
RMVPool.ReturnAll();
|
||||
dest.PlayingMotions.Clear();
|
||||
foreach (var m in PlayingMotions) dest.PlayingMotions.Add(m.Key, m.Value);
|
||||
}
|
||||
@@ -196,41 +189,38 @@ namespace Cryville.Crtr.Event {
|
||||
public void Dispose() {
|
||||
if (Disposed) return;
|
||||
Disposed = true;
|
||||
if (Handler != null) Handler.Dispose();
|
||||
if (CloneType < 16 && Handler != null) Handler.Dispose();
|
||||
foreach (var s in Children)
|
||||
s.Value.Dispose();
|
||||
RMVPool.ReturnAll();
|
||||
MCPool.ReturnAll();
|
||||
}
|
||||
|
||||
public void AttachHandler(ContainerHandler h) {
|
||||
if (Handler != null)
|
||||
throw new InvalidOperationException();
|
||||
throw new InvalidOperationException("Handler attached twice");
|
||||
Handler = h;
|
||||
h.cs = this;
|
||||
}
|
||||
|
||||
public void AttachSystems(PdtSkin skin, Judge judge) {
|
||||
skinContainer = new SkinContainer(skin);
|
||||
this.judge = judge;
|
||||
Handler.AttachSystems(skin, judge);
|
||||
}
|
||||
|
||||
public Vector GetRawValue(Identifier key) {
|
||||
Vector tr;
|
||||
if (!CachedValues.TryGetValue(key, out tr)) {
|
||||
tr = (Vector)ReflectionHelper.InvokeEmptyConstructor(ChartPlayer.motionRegistry[key].Type);
|
||||
CachedValues.Add(key, tr);
|
||||
CachedValueStates[key] = false;
|
||||
}
|
||||
Vector r = tr;
|
||||
MotionCache tr;
|
||||
if (!CachedValues.TryGetValue(key, out tr))
|
||||
CachedValues.Add(key, tr = MCPool.Rent(key));
|
||||
Vector r = tr.Value;
|
||||
#if !DISABLE_CACHE
|
||||
if (CachedValueStates[key]) return r;
|
||||
if (tr.Valid) return r;
|
||||
#endif
|
||||
float reltime = 0;
|
||||
if (rootPrototype != null) reltime = Time - rootPrototype.Time;
|
||||
if (rootPrototype != null) reltime = (float)(Time - rootPrototype.Time);
|
||||
GetMotionValue(key).GetValue(reltime, ref r);
|
||||
if (Parent != null) r.ApplyFrom(Parent.GetRawValue(key));
|
||||
#if !DISABLE_CACHE
|
||||
CachedValueStates[key] = true;
|
||||
tr.Valid = true;
|
||||
#endif
|
||||
return r;
|
||||
}
|
||||
@@ -318,17 +308,24 @@ namespace Cryville.Crtr.Event {
|
||||
Working = false;
|
||||
}
|
||||
|
||||
public void Handle(StampedEvent ev, Action<StampedEvent> callback = null) {
|
||||
public void Discard(StampedEvent ev) {
|
||||
Handler.Discard(this, ev);
|
||||
}
|
||||
|
||||
public void Handle(StampedEvent ev) {
|
||||
if (breakflag) return;
|
||||
if (ev != null) {
|
||||
if (ev.Unstamped is Chart.Motion) {
|
||||
var tev = (Chart.Motion)ev.Unstamped;
|
||||
var mv = RMVPool.Rent(tev.Name);
|
||||
mv.CloneTypeFlag = CloneType;
|
||||
GetMotionValue(tev.Name).CopyTo(mv);
|
||||
PlayingMotions.Add(ev, mv);
|
||||
Callback(ev, callback);
|
||||
if (!ev.Unstamped.IsLong)
|
||||
Update(ev);
|
||||
if (!ev.Unstamped.IsLong) {
|
||||
PlayingMotions.Remove(ev);
|
||||
RMVPool.Return(mv);
|
||||
}
|
||||
}
|
||||
else if (ev.Unstamped is EventContainer) {
|
||||
var cev = (EventContainer)ev.Unstamped;
|
||||
@@ -336,7 +333,7 @@ namespace Cryville.Crtr.Event {
|
||||
ccs.Working = true;
|
||||
ccs.StartUpdate();
|
||||
UpdateMotions();
|
||||
if (!ev.Unstamped.IsLong) {
|
||||
if (!cev.IsLong) {
|
||||
ccs.Working = false;
|
||||
ccs.BroadcastEndUpdate();
|
||||
if (CloneType == 1) ccs.Dispose();
|
||||
@@ -347,7 +344,9 @@ namespace Cryville.Crtr.Event {
|
||||
if (tev.IsRelease) {
|
||||
var nev = tev.Original;
|
||||
if (nev is Chart.Motion) {
|
||||
Callback(ev, callback);
|
||||
Update(ev);
|
||||
var mv = PlayingMotions[ev.Origin];
|
||||
if (mv.CloneTypeFlag == CloneType) RMVPool.Return(mv);
|
||||
PlayingMotions.Remove(ev.Origin);
|
||||
}
|
||||
else if (nev is EventContainer) {
|
||||
@@ -360,15 +359,13 @@ namespace Cryville.Crtr.Event {
|
||||
}
|
||||
}
|
||||
}
|
||||
Callback(ev.Unstamped == null || ev.Unstamped.Priority >= 0 ? ev : null, callback);
|
||||
Update(ev.Unstamped == null || ev.Unstamped.Priority >= 0 ? ev : null);
|
||||
}
|
||||
else Callback(null, callback);
|
||||
else Update(null);
|
||||
}
|
||||
|
||||
void Callback(StampedEvent ev, Action<StampedEvent> callback) {
|
||||
void Update(StampedEvent ev) {
|
||||
UpdateMotions();
|
||||
if (callback != null)
|
||||
callback(ev);
|
||||
if (ev == null || ev.Unstamped != null) Handler.Update(this, ev);
|
||||
else Handler.ExUpdate(this, ev);
|
||||
foreach (var m in PlayingMotions)
|
||||
@@ -390,7 +387,7 @@ namespace Cryville.Crtr.Event {
|
||||
}
|
||||
}
|
||||
else {
|
||||
var scaledTime = (Time - m.Key.Time - ChartPlayer.actualRenderStep * tev.sumfix) / m.Key.Duration;
|
||||
var scaledTime = (float)((Time - m.Key.Time - ChartPlayer.actualRenderStep * tev.sumfix) / m.Key.Duration);
|
||||
var lerpedTime = MotionLerper.GetEaseTime(scaledTime, tev.transition, tev.rate);
|
||||
if (tev.RelativeNode != null) {
|
||||
var target = value.QueryRelativeNode(tev.RelativeNode.Id);
|
||||
@@ -404,13 +401,17 @@ namespace Cryville.Crtr.Event {
|
||||
}
|
||||
}
|
||||
|
||||
public void BroadcastInit() {
|
||||
public void BroadcastPreInit() {
|
||||
Handler.PreInit();
|
||||
Handler.Init();
|
||||
foreach (var s in Children) {
|
||||
s.Value.BroadcastInit();
|
||||
foreach (var c in Children.Values) {
|
||||
c.BroadcastPreInit();
|
||||
}
|
||||
}
|
||||
public void BroadcastPostInit() {
|
||||
Handler.PostInit();
|
||||
foreach (var c in Children.Values) {
|
||||
c.BroadcastPostInit();
|
||||
}
|
||||
}
|
||||
|
||||
public void StartUpdate() {
|
||||
|
@@ -4,7 +4,7 @@ using System.Collections.Generic;
|
||||
|
||||
namespace Cryville.Crtr.Event {
|
||||
public class EventBatch : IComparable<EventBatch>, IEnumerable<StampedEvent> {
|
||||
public float Time {
|
||||
public double Time {
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
@@ -14,7 +14,7 @@ namespace Cryville.Crtr.Event {
|
||||
get { return queue.Count; }
|
||||
}
|
||||
|
||||
public EventBatch(float time) {
|
||||
public EventBatch(double time) {
|
||||
Time = time;
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ namespace Cryville.Crtr.Event {
|
||||
}
|
||||
|
||||
public int CompareTo(EventBatch other) {
|
||||
return this.Time.CompareTo(other.Time);
|
||||
return Time.CompareTo(other.Time);
|
||||
}
|
||||
|
||||
public IEnumerator<StampedEvent> GetEnumerator() {
|
||||
|
@@ -9,124 +9,127 @@ namespace Cryville.Crtr.Event {
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
ContainerState RootState;
|
||||
/// <summary>
|
||||
/// event => the container state that handles the event
|
||||
/// </summary>
|
||||
readonly Dictionary<ChartEvent, ContainerState> table
|
||||
readonly Chart chart;
|
||||
ContainerState rootState;
|
||||
readonly Dictionary<ChartEvent, ContainerState> containerMap
|
||||
= new Dictionary<ChartEvent, ContainerState>();
|
||||
public List<StampedEvent> stampedEvents = new List<StampedEvent>();
|
||||
readonly Dictionary<EventContainer, ContainerState> stateMap
|
||||
= new Dictionary<EventContainer, ContainerState>();
|
||||
readonly Dictionary<ChartEvent, StampedEvent> map
|
||||
= new Dictionary<ChartEvent, StampedEvent>();
|
||||
readonly Dictionary<EventContainer, List<StampedEvent>> coeventMap
|
||||
= new Dictionary<EventContainer, List<StampedEvent>>();
|
||||
readonly HashSet<ChartEvent> coevents = new HashSet<ChartEvent>();
|
||||
readonly List<StampedEvent> stampedEvents = new List<StampedEvent>();
|
||||
readonly List<EventBatch> batches = new List<EventBatch>();
|
||||
|
||||
float beat;
|
||||
double beat;
|
||||
float tempo;
|
||||
|
||||
public EventBatcher(Chart c) : base(c, new List<ChartEvent>()) {
|
||||
public EventBatcher(Chart c) : base(new List<ChartEvent>()) {
|
||||
chart = c;
|
||||
beat = chart.BeatPosition;
|
||||
tempo = (float)c.sigs[0].tempo;
|
||||
events.Add(c);
|
||||
events.Add(c.ReleaseEvent);
|
||||
Events.Add(c);
|
||||
Events.Add(c.ReleaseEvent);
|
||||
AddEventContainer(c);
|
||||
events.Sort((a, b) => a.BeatPosition.CompareTo(b.BeatPosition));
|
||||
Events.Sort((a, b) => a.BeatPosition.CompareTo(b.BeatPosition));
|
||||
}
|
||||
|
||||
void AddEventContainer(EventContainer c, ContainerState parent = null) {
|
||||
var cs = new ContainerState(chart, c, parent);
|
||||
stateMap.Add(c, cs);
|
||||
if (parent == null) {
|
||||
cs.Depth = 0;
|
||||
RootState = cs;
|
||||
rootState = cs;
|
||||
}
|
||||
else {
|
||||
cs.Depth = (ushort)(parent.Depth + 1);
|
||||
}
|
||||
foreach (var ev in c.Events) {
|
||||
if (ev.time == null) {
|
||||
coevents.Add(ev);
|
||||
ev.time = c.time;
|
||||
if (ev is EventContainer)
|
||||
ev.endtime = c.endtime;
|
||||
}
|
||||
if (ev.IsLong) {
|
||||
events.Add(ev.ReleaseEvent);
|
||||
table.Add(ev.ReleaseEvent, cs);
|
||||
Events.Add(ev.ReleaseEvent);
|
||||
containerMap.Add(ev.ReleaseEvent, cs);
|
||||
}
|
||||
events.Add(ev);
|
||||
table.Add(ev, cs);
|
||||
Events.Add(ev);
|
||||
containerMap.Add(ev, cs);
|
||||
if (ev is EventContainer)
|
||||
AddEventContainer((EventContainer)ev, cs);
|
||||
}
|
||||
}
|
||||
|
||||
public override void ForwardOnceToTime(float toTime, Action<ChartEvent> callback) {
|
||||
float toBeat = (float)Math.Round(beat + (toTime - Time) * tempo / 60f, 6);
|
||||
if (EventId >= events.Count)
|
||||
public override void ForwardOnceToTime(double toTime) {
|
||||
double toBeat = Math.Round(beat + (toTime - Time) * tempo / 60f, 6);
|
||||
if (EventId >= Events.Count)
|
||||
goto return_ahead;
|
||||
float ebeat = events[EventId].BeatPosition;
|
||||
float etime = (float)Math.Round((ebeat - beat) / tempo * 60f + Time, 6);
|
||||
double ebeat = Events[EventId].BeatPosition;
|
||||
double etime = Math.Round((ebeat - beat) / tempo * 60f + Time, 6);
|
||||
if (etime > toTime)
|
||||
goto return_ahead;
|
||||
var batch = GetEventBatch();
|
||||
Time = etime;
|
||||
beat = ebeat;
|
||||
bool flag = false;
|
||||
foreach (var ev in batch) {
|
||||
EventContainer con = null;
|
||||
if (table.ContainsKey(ev)) con = table[ev].Container;
|
||||
if (containerMap.ContainsKey(ev)) con = containerMap[ev].Container;
|
||||
var sev = new StampedEvent() {
|
||||
Time = etime,
|
||||
Unstamped = ev,
|
||||
Container = con
|
||||
};
|
||||
if (ev is EventContainer) {
|
||||
stateMap[(EventContainer)ev].StampedContainer = sev;
|
||||
}
|
||||
if (ev is InstantEvent) {
|
||||
var tev = (InstantEvent)ev;
|
||||
var pev = stampedEvents.First(tpev => tpev.Unstamped == tev.Original);
|
||||
var pev = map[tev.Original];
|
||||
pev.Subevents.Add(sev);
|
||||
sev.Origin = pev;
|
||||
}
|
||||
stampedEvents.Add(sev);
|
||||
if (ev.Priority >= 0) {
|
||||
if (callback != null) callback(ev);
|
||||
flag = true;
|
||||
if (con != null && coevents.Contains(ev)) {
|
||||
List<StampedEvent> cevs;
|
||||
if (!coeventMap.TryGetValue(con, out cevs)) {
|
||||
coeventMap.Add(con, cevs = new List<StampedEvent>());
|
||||
}
|
||||
cevs.Add(sev);
|
||||
}
|
||||
else stampedEvents.Add(sev);
|
||||
map.Add(ev, sev);
|
||||
if (ev is Chart.Signature) {
|
||||
var tev = (Chart.Signature)ev;
|
||||
if (tev.tempo != null) tempo = (float)tev.tempo;
|
||||
}
|
||||
EventId++;
|
||||
}
|
||||
if (callback != null && !flag) callback(batch.First());
|
||||
return;
|
||||
return_ahead:
|
||||
Time = toTime;
|
||||
beat = toBeat;
|
||||
if (callback != null) callback(null);
|
||||
}
|
||||
|
||||
IOrderedEnumerable<ChartEvent> GetEventBatch() {
|
||||
float cbeat = events[EventId].BeatPosition;
|
||||
float cbeat = Events[EventId].BeatPosition;
|
||||
int b = EventId;
|
||||
while (Mathf.Approximately(events[b].BeatPosition, cbeat)) {
|
||||
while (Mathf.Approximately(Events[b].BeatPosition, cbeat)) {
|
||||
b--;
|
||||
if (b == -1) break;
|
||||
}
|
||||
int a = EventId;
|
||||
while (Mathf.Approximately(events[a].BeatPosition, cbeat)) {
|
||||
while (Mathf.Approximately(Events[a].BeatPosition, cbeat)) {
|
||||
a++;
|
||||
if (a == events.Count) break;
|
||||
if (a == Events.Count) break;
|
||||
}
|
||||
return from ev in events.GetRange(b + 1, a - b - 1) orderby ev.Priority select ev;
|
||||
return from ev in Events.GetRange(b + 1, a - b - 1) orderby ev.Priority select ev;
|
||||
}
|
||||
|
||||
public EventBus Batch() {
|
||||
stampedEvents.Sort((a, b) => {
|
||||
int u = a.CompareTo(b);
|
||||
if (u != 0) return u;
|
||||
if (a.Unstamped != null && b.Unstamped != null)
|
||||
if (table.ContainsKey(a.Unstamped) && table.ContainsKey(b.Unstamped)) {
|
||||
u = table[a.Unstamped].Depth.CompareTo(table[b.Unstamped].Depth);
|
||||
if (u != 0) return u;
|
||||
}
|
||||
return a.GetHashCode().CompareTo(b.GetHashCode());
|
||||
});
|
||||
stampedEvents.Sort(CompareStampedEvents);
|
||||
var cb = new EventBatch(stampedEvents[0].Time);
|
||||
foreach (var ev in stampedEvents) {
|
||||
if (ev.Time != cb.Time) {
|
||||
@@ -134,10 +137,36 @@ namespace Cryville.Crtr.Event {
|
||||
cb = new EventBatch(ev.Time);
|
||||
}
|
||||
cb.Enqueue(ev);
|
||||
BatchCoevents(ev);
|
||||
}
|
||||
batches.Add(cb);
|
||||
Bus = new EventBus(chart, RootState, batches);
|
||||
Bus = new EventBus(rootState, batches);
|
||||
return Bus;
|
||||
}
|
||||
|
||||
void BatchCoevents(StampedEvent ev, List<StampedEvent> ocevs = null) {
|
||||
if (!(ev.Unstamped is EventContainer)) return;
|
||||
List<StampedEvent> cevs;
|
||||
if (coeventMap.TryGetValue((EventContainer)ev.Unstamped, out cevs)) {
|
||||
var rootFlag = ocevs == null;
|
||||
if (rootFlag) ev.Coevents = ocevs = new List<StampedEvent>();
|
||||
foreach (var cev in cevs) {
|
||||
ocevs.Add(cev);
|
||||
BatchCoevents(cev, ocevs);
|
||||
}
|
||||
if (rootFlag) ocevs.Sort(CompareStampedEvents);
|
||||
else ocevs.Add(ev);
|
||||
}
|
||||
}
|
||||
|
||||
int CompareStampedEvents(StampedEvent a, StampedEvent b) {
|
||||
int u = a.CompareTo(b);
|
||||
if (u != 0) return u;
|
||||
if (a.Unstamped != null && b.Unstamped != null && containerMap.ContainsKey(a.Unstamped) && containerMap.ContainsKey(b.Unstamped)) {
|
||||
u = containerMap[a.Unstamped].Depth.CompareTo(containerMap[b.Unstamped].Depth);
|
||||
if (u != 0) return u;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -11,15 +11,14 @@ namespace Cryville.Crtr.Event {
|
||||
|
||||
Dictionary<EventContainer, ContainerState> states
|
||||
= new Dictionary<EventContainer, ContainerState>();
|
||||
List<EventContainer> activeContainers
|
||||
= new List<EventContainer>();
|
||||
HashSet<EventContainer> activeContainers
|
||||
= new HashSet<EventContainer>();
|
||||
HashSet<ContainerState> workingStates
|
||||
= new HashSet<ContainerState>();
|
||||
HashSet<ContainerState> invalidatedStates
|
||||
= new HashSet<ContainerState>();
|
||||
|
||||
public EventBus(Chart c, ContainerState root, List<EventBatch> b)
|
||||
: base(c, b) {
|
||||
public EventBus(ContainerState root, List<EventBatch> b) : base(b) {
|
||||
RootState = root;
|
||||
Expand();
|
||||
AttachBus();
|
||||
@@ -30,11 +29,13 @@ namespace Cryville.Crtr.Event {
|
||||
var r = (EventBus)MemberwiseClone();
|
||||
r.prototype = this;
|
||||
r.states = new Dictionary<EventContainer, ContainerState>();
|
||||
r.activeContainers = new List<EventContainer>();
|
||||
r.activeContainers = new HashSet<EventContainer>();
|
||||
r.workingStates = new HashSet<ContainerState>();
|
||||
r.invalidatedStates = new HashSet<ContainerState>();
|
||||
r.tempEvents = new List<StampedEvent>();
|
||||
r.Time += offsetTime;
|
||||
r.RootState = RootState.Clone(ct);
|
||||
r.RootState.StartUpdate();
|
||||
r.Expand();
|
||||
r.AttachBus();
|
||||
foreach (var s in r.states) r.invalidatedStates.Add(s.Value);
|
||||
@@ -84,8 +85,18 @@ namespace Cryville.Crtr.Event {
|
||||
|
||||
void EnsureActivity(EventContainer c) {
|
||||
if (activeContainers.Contains(c)) return;
|
||||
if (RootState.CloneType >= 2) prototype.states[c].CopyTo(RootState.CloneType, states[c]);
|
||||
var state = states[c];
|
||||
if (state.Parent != null) EnsureActivity(state.Parent.Container);
|
||||
if (RootState.CloneType >= 2) prototype.states[c].CopyTo(RootState.CloneType, state);
|
||||
state.Active = true;
|
||||
activeContainers.Add(c);
|
||||
|
||||
if (state.StampedContainer.Coevents == null) return;
|
||||
foreach (var cev in state.StampedContainer.Coevents) {
|
||||
if (cev.Container == null) continue;
|
||||
EnsureActivity(cev.Container);
|
||||
states[cev.Container].Handle(cev);
|
||||
}
|
||||
}
|
||||
|
||||
void AttachBus() {
|
||||
@@ -98,39 +109,60 @@ namespace Cryville.Crtr.Event {
|
||||
s.AttachSystems(skin, judge);
|
||||
}
|
||||
|
||||
readonly List<StampedEvent> patch = new List<StampedEvent>();
|
||||
public void IssuePatch(IEnumerable<StampedEvent> l) {
|
||||
patch.AddRange(l);
|
||||
}
|
||||
public void DoPatch() {
|
||||
foreach (var ev in patch) {
|
||||
var batch = new EventBatch(ev.Time);
|
||||
var batchIndex = events.BinarySearch(batch);
|
||||
if (batchIndex >= 0) batch = events[batchIndex];
|
||||
else events.Insert(~batchIndex, batch);
|
||||
batch.Add(ev);
|
||||
}
|
||||
patch.Clear();
|
||||
List<StampedEvent> tempEvents = new List<StampedEvent>();
|
||||
public void PushTempEvent(StampedEvent ev) {
|
||||
var index = tempEvents.BinarySearch(ev);
|
||||
if (index < 0) index = ~index;
|
||||
tempEvents.Insert(index, ev);
|
||||
}
|
||||
|
||||
public override void ForwardOnceToTime(float toTime, Action<EventBatch> callback = null) {
|
||||
if (EventId < events.Count && events[EventId].Time <= toTime) {
|
||||
Time = events[EventId].Time;
|
||||
var batch = events[EventId];
|
||||
readonly StampedEvent _dummyEvent = new StampedEvent();
|
||||
public void StripTempEvents() {
|
||||
_dummyEvent.Time = Time;
|
||||
var index = tempEvents.BinarySearch(_dummyEvent);
|
||||
if (index < 0) index = ~index;
|
||||
for (var i = 0; i < index; i++) {
|
||||
var ev = tempEvents[i];
|
||||
if (ev.Container != null) {
|
||||
states[ev.Container].Discard(ev);
|
||||
}
|
||||
}
|
||||
tempEvents.RemoveRange(0, index);
|
||||
}
|
||||
|
||||
public override void ForwardOnceToTime(double toTime) {
|
||||
double time1 = EventId < Events.Count ? Events[EventId].Time : double.PositiveInfinity;
|
||||
double time2 = tempEvents.Count > 0 ? tempEvents[0].Time : double.PositiveInfinity;
|
||||
double time0 = Math.Min(time1, time2);
|
||||
if (time0 <= toTime && time0 != double.PositiveInfinity) {
|
||||
Time = time0;
|
||||
foreach (var s in workingStates) s.Handle(null);
|
||||
ValidateStates();
|
||||
for (var i = 0; i < batch.Count; i++) {
|
||||
var ev = batch[i];
|
||||
if (ev.Container != null) {
|
||||
EnsureActivity(ev.Container);
|
||||
states[ev.Container].Handle(ev);
|
||||
if (time1 == time0) {
|
||||
var batch = Events[EventId];
|
||||
for (var i = 0; i < batch.Count; i++) {
|
||||
var ev = batch[i];
|
||||
if (ev.Container != null) {
|
||||
if (ev.Unstamped is EventContainer) EnsureActivity((EventContainer)ev.Unstamped);
|
||||
else EnsureActivity(ev.Container);
|
||||
states[ev.Container].Handle(ev);
|
||||
}
|
||||
else if (ev.Coevents != null) EnsureActivity((EventContainer)ev.Unstamped);
|
||||
}
|
||||
if (ev.Unstamped is EventContainer) {
|
||||
if (ev.Container != null) EnsureActivity((EventContainer)ev.Unstamped);
|
||||
EventId++;
|
||||
}
|
||||
if (time2 == time0) {
|
||||
while (tempEvents.Count > 0) {
|
||||
var ev = tempEvents[0];
|
||||
if (ev.Time != time0) break;
|
||||
if (ev.Container != null) {
|
||||
EnsureActivity(ev.Container);
|
||||
states[ev.Container].Handle(ev);
|
||||
}
|
||||
tempEvents.RemoveAt(0);
|
||||
}
|
||||
}
|
||||
ValidateStates();
|
||||
EventId++;
|
||||
}
|
||||
else {
|
||||
Time = toTime;
|
||||
@@ -146,12 +178,16 @@ namespace Cryville.Crtr.Event {
|
||||
invalidatedStates.Clear();
|
||||
}
|
||||
|
||||
public void BroadcastInit() {
|
||||
RootState.BroadcastInit();
|
||||
public void BroadcastPreInit() {
|
||||
RootState.BroadcastPreInit();
|
||||
}
|
||||
public void BroadcastPostInit() {
|
||||
RootState.BroadcastPostInit();
|
||||
}
|
||||
|
||||
public void BroadcastEndUpdate() {
|
||||
RootState.BroadcastEndUpdate();
|
||||
tempEvents.Clear();
|
||||
}
|
||||
|
||||
public void Anchor() {
|
||||
|
55
Assets/Cryville/Crtr/Event/MotionCache.cs
Normal file
55
Assets/Cryville/Crtr/Event/MotionCache.cs
Normal file
@@ -0,0 +1,55 @@
|
||||
using Cryville.Common;
|
||||
using Cryville.Common.Buffers;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Cryville.Crtr.Event {
|
||||
internal class MotionCache {
|
||||
public bool Valid { get; set; }
|
||||
public Vector Value { get; set; }
|
||||
public void CopyTo(MotionCache dest) {
|
||||
dest.Valid = Valid;
|
||||
Value.CopyTo(dest.Value);
|
||||
}
|
||||
}
|
||||
internal class MotionCachePool {
|
||||
private class Bucket : ObjectPool<MotionCache> {
|
||||
readonly MotionRegistry _reg;
|
||||
public Bucket(string name, int capacity) : base(capacity) {
|
||||
_reg = ChartPlayer.motionRegistry[name];
|
||||
}
|
||||
protected override MotionCache Construct() {
|
||||
var result = new MotionCache();
|
||||
result.Value = (Vector)ReflectionHelper.InvokeEmptyConstructor(_reg.Type);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
static Dictionary<Identifier, Bucket> _buckets;
|
||||
public static void Prepare() {
|
||||
_buckets = new Dictionary<Identifier, Bucket>(ChartPlayer.motionRegistry.Count);
|
||||
foreach (var reg in ChartPlayer.motionRegistry)
|
||||
_buckets.Add(reg.Key, new Bucket(reg.Key, 4096));
|
||||
}
|
||||
|
||||
static readonly SimpleObjectPool<Dictionary<MotionCache, Identifier>> _dictPool
|
||||
= new SimpleObjectPool<Dictionary<MotionCache, Identifier>>(1024);
|
||||
Dictionary<MotionCache, Identifier> _rented;
|
||||
public MotionCache Rent(Identifier name) {
|
||||
var obj = _buckets[name].Rent();
|
||||
obj.Valid = false;
|
||||
if (_rented == null) _rented = _dictPool.Rent();
|
||||
_rented.Add(obj, name);
|
||||
return obj;
|
||||
}
|
||||
public void Return(MotionCache obj) {
|
||||
_buckets[_rented[obj]].Return(obj);
|
||||
_rented.Remove(obj);
|
||||
}
|
||||
public void ReturnAll() {
|
||||
if (_rented == null) return;
|
||||
foreach (var obj in _rented)
|
||||
_buckets[obj.Value].Return(obj.Key);
|
||||
_rented.Clear();
|
||||
_dictPool.Return(_rented);
|
||||
}
|
||||
}
|
||||
}
|
11
Assets/Cryville/Crtr/Event/MotionCache.cs.meta
Normal file
11
Assets/Cryville/Crtr/Event/MotionCache.cs.meta
Normal file
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5d11b50a98974254f87273c94ed20de7
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
@@ -20,11 +20,13 @@ namespace Cryville.Crtr.Event {
|
||||
_buckets.Add(reg.Key, new Bucket(reg.Key, 4096));
|
||||
}
|
||||
|
||||
readonly Dictionary<RealtimeMotionValue, string> _rented = new Dictionary<RealtimeMotionValue, string>();
|
||||
static readonly SimpleObjectPool<Dictionary<RealtimeMotionValue, Identifier>> _dictPool
|
||||
= new SimpleObjectPool<Dictionary<RealtimeMotionValue, Identifier>>(1024);
|
||||
Dictionary<RealtimeMotionValue, Identifier> _rented;
|
||||
public RealtimeMotionValue Rent(Identifier name) {
|
||||
var n = name;
|
||||
var obj = _buckets[n].Rent();
|
||||
_rented.Add(obj, n);
|
||||
var obj = _buckets[name].Rent();
|
||||
if (_rented == null) _rented = _dictPool.Rent();
|
||||
_rented.Add(obj, name);
|
||||
return obj;
|
||||
}
|
||||
public void Return(RealtimeMotionValue obj) {
|
||||
@@ -32,9 +34,11 @@ namespace Cryville.Crtr.Event {
|
||||
_rented.Remove(obj);
|
||||
}
|
||||
public void ReturnAll() {
|
||||
if (_rented == null) return;
|
||||
foreach (var obj in _rented)
|
||||
_buckets[obj.Value].Return(obj.Key);
|
||||
_rented.Clear();
|
||||
_dictPool.Return(_rented);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,9 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ef3100799cf39eb4d8585dcfba2529a5
|
||||
guid: b9bd9e24d7c553341a2a12391843542f
|
||||
folderAsset: yes
|
||||
timeCreated: 1623583530
|
||||
licenseType: Pro
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
@@ -0,0 +1,189 @@
|
||||
using Cryville.Common;
|
||||
using Cryville.Common.Math;
|
||||
using Cryville.Crtr.Browsing;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
|
||||
namespace Cryville.Crtr.Extensions.Bestdori {
|
||||
public class BestdoriChartConverter : ResourceConverter {
|
||||
static readonly string[] SUPPORTED_FORMATS = { ".bestdori" };
|
||||
public override string[] GetSupportedFormats() {
|
||||
return SUPPORTED_FORMATS;
|
||||
}
|
||||
|
||||
public override IEnumerable<Resource> ConvertFrom(FileInfo file) {
|
||||
List<Resource> result = new List<Resource>();
|
||||
List<BestdoriChartEvent> src;
|
||||
using (var reader = new StreamReader(file.FullName)) {
|
||||
src = JsonConvert.DeserializeObject<List<BestdoriChartEvent>>(reader.ReadToEnd());
|
||||
}
|
||||
var group = new Chart.Group() {
|
||||
tracks = new List<Chart.Track>(),
|
||||
notes = new List<Chart.Note>(),
|
||||
motions = new List<Chart.Motion>(),
|
||||
};
|
||||
Chart chart = new Chart {
|
||||
format = 2,
|
||||
time = new BeatTime(0, 0, 1),
|
||||
ruleset = "bang_dream_girls_band_party",
|
||||
sigs = new List<Chart.Signature>(),
|
||||
sounds = new List<Chart.Sound>(),
|
||||
motions = new List<Chart.Motion>(),
|
||||
groups = new List<Chart.Group> { group },
|
||||
};
|
||||
var tm = new BeatTimeTimingModel();
|
||||
string bgm = null;
|
||||
double endbeat = 0;
|
||||
foreach (var ev in src) {
|
||||
tm.ForwardTo(ev.StartBeat);
|
||||
if (ev.StartBeat > endbeat) endbeat = ev.StartBeat;
|
||||
if (ev is BestdoriChartEvent.System) {
|
||||
if (bgm != null) continue;
|
||||
var tev = (BestdoriChartEvent.System)ev;
|
||||
bgm = StringUtils.TrimExt(tev.data);
|
||||
var name = "bang_dream_girls_band_party__" + bgm;
|
||||
result.Add(new SongResource(name, new FileInfo(Path.Combine(file.Directory.FullName, tev.data))));
|
||||
chart.sounds.Add(new Chart.Sound { time = ToBeatTime(tev.beat), id = name });
|
||||
}
|
||||
else if (ev is BestdoriChartEvent.BPM) {
|
||||
var tev = (BestdoriChartEvent.BPM)ev;
|
||||
tm.BPM = tev.bpm;
|
||||
chart.sigs.Add(new Chart.Signature { time = ToBeatTime(tev.beat), tempo = (float)tev.bpm });
|
||||
}
|
||||
else if (ev is BestdoriChartEvent.Single) {
|
||||
var tev = (BestdoriChartEvent.Single)ev;
|
||||
group.notes.Add(new Chart.Note {
|
||||
time = ToBeatTime(tev.beat),
|
||||
judges = new List<Chart.Judge> { new Chart.Judge { name = tev.flick ? "single_flick" : "single" } },
|
||||
motions = new List<Chart.Motion> { new Chart.Motion { motion = "track:" + tev.lane.ToString(CultureInfo.InvariantCulture) } },
|
||||
});
|
||||
}
|
||||
else if (ev is BestdoriChartEvent.Long) {
|
||||
var tev = (BestdoriChartEvent.Long)ev;
|
||||
var c1 = tev.connections[tev.connections.Count - 1];
|
||||
var note = new Chart.Note {
|
||||
time = ToBeatTime(tev.connections[0].beat),
|
||||
endtime = ToBeatTime(c1.beat),
|
||||
judges = new List<Chart.Judge>(),
|
||||
};
|
||||
for (int i = 0; i < tev.connections.Count; i++) {
|
||||
BestdoriChartEvent.Connection c = tev.connections[i];
|
||||
var motion = new Chart.Motion { motion = "track:" + c.lane.ToString(CultureInfo.InvariantCulture) };
|
||||
if (i == 0) {
|
||||
note.judges.Add(new Chart.Judge { name = "single" });
|
||||
note.motions.Add(motion);
|
||||
}
|
||||
else {
|
||||
var cbeat = motion.endtime = ToBeatTime(c.beat);
|
||||
if (i > 1) motion.time = ToBeatTime(tev.connections[i - 1].beat);
|
||||
note.motions.Add(motion);
|
||||
if (i == tev.connections.Count - 1)
|
||||
note.judges.Add(new Chart.Judge { time = cbeat, name = c.flick ? "longend_flick" : "longend" });
|
||||
else if (!c.hidden)
|
||||
note.judges.Add(new Chart.Judge { time = cbeat, name = "longnode" });
|
||||
}
|
||||
}
|
||||
if (c1.beat > endbeat) endbeat = c1.beat;
|
||||
group.notes.Add(note);
|
||||
}
|
||||
else throw new NotImplementedException("Unsupported event: " + ev.type);
|
||||
}
|
||||
if (bgm == null) throw new FormatException("Chart contains no song");
|
||||
chart.endtime = ToBeatTime(endbeat + 4);
|
||||
if (endbeat > tm.BeatTime) tm.ForwardTo(endbeat);
|
||||
result.Add(new RawChartResource(string.Format("bang_dream_girls_band_party__{0}__{1}", bgm, StringUtils.TrimExt(file.Name)), chart, new ChartMeta {
|
||||
name = string.Format("Bandori {0} {1}", bgm, StringUtils.TrimExt(file.Name)),
|
||||
author = "©BanG Dream! Project ©Craft Egg Inc. ©bushiroad",
|
||||
ruleset = "bang_dream_girls_band_party",
|
||||
note_count = group.notes.Count,
|
||||
length = (float)tm.Time,
|
||||
song = new SongMetaInfo {
|
||||
name = bgm,
|
||||
author = "©BanG Dream! Project ©Craft Egg Inc. ©bushiroad",
|
||||
}
|
||||
}));
|
||||
return result;
|
||||
}
|
||||
|
||||
BeatTime ToBeatTime(double beat, double error = 1e-4) {
|
||||
int i, n, d;
|
||||
FractionUtils.ToFraction(beat, error, out n, out d);
|
||||
i = n / d; n %= d;
|
||||
return new BeatTime(i, n, d);
|
||||
}
|
||||
|
||||
#pragma warning disable IDE1006
|
||||
[JsonConverter(typeof(BestdoriChartEventCreator))]
|
||||
abstract class BestdoriChartEvent {
|
||||
public abstract string type { get; }
|
||||
public abstract double StartBeat { get; }
|
||||
public abstract class InstantEvent : BestdoriChartEvent {
|
||||
public double beat;
|
||||
public override double StartBeat { get { return beat; } }
|
||||
}
|
||||
public class BPM : InstantEvent {
|
||||
public override string type { get { return "BPM"; } }
|
||||
public double bpm;
|
||||
}
|
||||
public class System : InstantEvent {
|
||||
public override string type { get { return "System"; } }
|
||||
public string data;
|
||||
}
|
||||
public abstract class SingleBase : InstantEvent {
|
||||
public double lane;
|
||||
public bool skill;
|
||||
public bool flick;
|
||||
}
|
||||
public class Single : SingleBase {
|
||||
public override string type { get { return "Single"; } }
|
||||
}
|
||||
public class Directional : SingleBase {
|
||||
public override string type { get { return "Directional"; } }
|
||||
public string direction;
|
||||
public int width;
|
||||
}
|
||||
public class Connection : SingleBase {
|
||||
public override string type { get { return null; } }
|
||||
public bool hidden;
|
||||
}
|
||||
public class Long : BestdoriChartEvent {
|
||||
public override string type { get { return "Long"; } }
|
||||
public List<Connection> connections;
|
||||
public override double StartBeat { get { return connections[0].beat; } }
|
||||
}
|
||||
public class Slide : Long {
|
||||
public override string type { get { return "Slide"; } }
|
||||
}
|
||||
}
|
||||
#pragma warning restore IDE1006
|
||||
class BestdoriChartEventCreator : CustomCreationConverter<BestdoriChartEvent> {
|
||||
string _currentType;
|
||||
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
|
||||
var obj = JObject.ReadFrom(reader);
|
||||
var type = obj["type"];
|
||||
if (type == null) _currentType = null;
|
||||
else _currentType = obj["type"].ToObject<string>();
|
||||
return base.ReadJson(obj.CreateReader(), objectType, existingValue, serializer);
|
||||
}
|
||||
|
||||
public override BestdoriChartEvent Create(Type objectType) {
|
||||
switch (_currentType) {
|
||||
case "BPM": return new BestdoriChartEvent.BPM();
|
||||
case "System": return new BestdoriChartEvent.System();
|
||||
case "Single": return new BestdoriChartEvent.Single();
|
||||
case "Directional": return new BestdoriChartEvent.Directional();
|
||||
case null: return new BestdoriChartEvent.Connection();
|
||||
case "Long": return new BestdoriChartEvent.Long();
|
||||
case "Slide": return new BestdoriChartEvent.Slide();
|
||||
default: throw new ArgumentException("Unknown event type: " + _currentType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e3c5a8bf05d5e284ba498e91cb0dd35e
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
27
Assets/Cryville/Crtr/Extensions/Extensions.cs
Normal file
27
Assets/Cryville/Crtr/Extensions/Extensions.cs
Normal file
@@ -0,0 +1,27 @@
|
||||
using Cryville.Crtr.Browsing;
|
||||
using Cryville.Crtr.Extensions.Bestdori;
|
||||
using Cryville.Crtr.Extensions.Malody;
|
||||
using Cryville.Crtr.Extensions.osu;
|
||||
using Cryville.Crtr.Extensions.Quaver;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Cryville.Crtr.Extensions {
|
||||
public class Extensions : ExtensionInterface {
|
||||
public override IEnumerable<ResourceConverter> GetResourceConverters() {
|
||||
return new ResourceConverter[] {
|
||||
new BestdoriChartConverter(),
|
||||
new MalodyChartConverter(),
|
||||
new osuChartConverter(),
|
||||
new QuaverChartConverter(),
|
||||
};
|
||||
}
|
||||
|
||||
public override IEnumerable<LocalResourceFinder> GetResourceFinders() {
|
||||
return new LocalResourceFinder[] {
|
||||
new MalodyChartFinder(),
|
||||
new osuChartFinder(),
|
||||
new QuaverChartFinder(),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
11
Assets/Cryville/Crtr/Extensions/Extensions.cs.meta
Normal file
11
Assets/Cryville/Crtr/Extensions/Extensions.cs.meta
Normal file
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 23377bf2926d93a4b8e3f3ab6040c7f2
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
@@ -2,6 +2,7 @@ using Cryville.Crtr.Browsing;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
@@ -17,23 +18,31 @@ namespace Cryville.Crtr.Extensions.Malody {
|
||||
public override IEnumerable<Resource> ConvertFrom(FileInfo file) {
|
||||
List<Resource> result = new List<Resource>();
|
||||
MalodyChart src;
|
||||
if (file.Extension != ".mc") throw new NotImplementedException("mcz file is not supported yet");
|
||||
using (var reader = new StreamReader(file.FullName)) {
|
||||
src = JsonConvert.DeserializeObject<MalodyChart>(reader.ReadToEnd());
|
||||
}
|
||||
if (src.meta.mode != 0) throw new NotImplementedException("The chart mode is not supported");
|
||||
if (src.meta.mode != 0) throw new NotImplementedException(string.Format("{0} mode is not supported yet", MODES[src.meta.mode]));
|
||||
|
||||
var ruleset = "malody!" + MODES[src.meta.mode];
|
||||
if (src.meta.mode == 0) {
|
||||
ruleset += "." + src.meta.mode_ext.column.ToString(CultureInfo.InvariantCulture) + "k";
|
||||
}
|
||||
|
||||
ChartMeta meta = new ChartMeta() {
|
||||
song = new ChartMeta.MetaInfo() {
|
||||
name = src.meta.version,
|
||||
author = src.meta.creator,
|
||||
song = new SongMetaInfo() {
|
||||
name = src.meta.song.titleorg != null ? src.meta.song.titleorg : src.meta.song.title,
|
||||
author = src.meta.song.artistorg != null ? src.meta.song.artistorg : src.meta.song.artist,
|
||||
},
|
||||
ruleset = "malody!" + MODES[src.meta.mode],
|
||||
ruleset = ruleset,
|
||||
};
|
||||
|
||||
Chart chart = new Chart {
|
||||
format = 2,
|
||||
time = new BeatTime(-4, 0, 1),
|
||||
ruleset = "malody!" + MODES[src.meta.mode],
|
||||
ruleset = ruleset,
|
||||
sigs = new List<Chart.Signature>(),
|
||||
sounds = new List<Chart.Sound>(),
|
||||
motions = new List<Chart.Motion>(),
|
||||
@@ -65,29 +74,28 @@ namespace Cryville.Crtr.Extensions.Malody {
|
||||
= new Dictionary<MalodyChart.IEvent, StartEventState>();
|
||||
|
||||
float? baseBpm = null;
|
||||
float pbeat = 0f, ctime = 0f;
|
||||
int[] endbeat = new int[] { 0, 0, 1 };
|
||||
var tm = new FractionalBeatTimeTimingModel();
|
||||
foreach (var ev in events) {
|
||||
float cbeat = bp(ev.beat);
|
||||
ctime += baseBpm == null ? 0 : (cbeat - pbeat) / baseBpm.Value * 60f;
|
||||
pbeat = cbeat;
|
||||
var beat = new BeatTime(ev.beat[0], ev.beat[1], ev.beat[2]);
|
||||
tm.ForwardTo(beat);
|
||||
if (ev is MalodyChart.Time) {
|
||||
var tev = (MalodyChart.Time)ev;
|
||||
if (baseBpm == null) baseBpm = tev.bpm;
|
||||
tm.BPM = tev.bpm;
|
||||
chart.sigs.Add(new Chart.Signature {
|
||||
time = new BeatTime(ev.beat[0], ev.beat[1], ev.beat[2]),
|
||||
time = beat,
|
||||
tempo = tev.bpm,
|
||||
});
|
||||
chart.motions.Add(new Chart.Motion {
|
||||
time = new BeatTime(ev.beat[0], ev.beat[1], ev.beat[2]),
|
||||
motion = "svm:" + (tev.bpm / baseBpm).ToString()
|
||||
time = beat,
|
||||
motion = "svm:" + (tev.bpm / baseBpm.Value).ToString(CultureInfo.InvariantCulture)
|
||||
});
|
||||
}
|
||||
else if (ev is MalodyChart.Effect) {
|
||||
var tev = (MalodyChart.Effect)ev;
|
||||
if (tev.scroll != null) group.motions.Add(new Chart.Motion {
|
||||
time = new BeatTime(ev.beat[0], ev.beat[1], ev.beat[2]),
|
||||
motion = "svm:" + tev.scroll.ToString()
|
||||
time = beat,
|
||||
motion = "svm:" + tev.scroll.Value.ToString(CultureInfo.InvariantCulture)
|
||||
});
|
||||
}
|
||||
else if (ev is MalodyChart.Note) {
|
||||
@@ -102,22 +110,20 @@ namespace Cryville.Crtr.Extensions.Malody {
|
||||
offset = -tev.offset / 1000f,
|
||||
});
|
||||
}
|
||||
else throw new NotImplementedException();
|
||||
else throw new NotImplementedException("Key sounds are not supported yet");
|
||||
}
|
||||
else {
|
||||
if (bp(tev.beat) > bp(endbeat)) endbeat = tev.beat;
|
||||
var rn = new Chart.Note() {
|
||||
time = new BeatTime(tev.beat[0], tev.beat[1], tev.beat[2]),
|
||||
time = beat,
|
||||
motions = new List<Chart.Motion> {
|
||||
new Chart.Motion() { motion = "track:" + tev.column.ToString() }
|
||||
new Chart.Motion() { motion = "track:" + tev.column.ToString(CultureInfo.InvariantCulture) }
|
||||
},
|
||||
};
|
||||
if (tev.endbeat != null) {
|
||||
if (bp(tev.endbeat) > bp(endbeat)) endbeat = tev.endbeat;
|
||||
rn.endtime = new BeatTime(tev.endbeat[0], tev.endbeat[1], tev.endbeat[2]);
|
||||
longEvents.Add(ev, new StartEventState {
|
||||
Destination = rn,
|
||||
Time = ctime,
|
||||
Time = tm.Time,
|
||||
});
|
||||
}
|
||||
group.notes.Add(rn);
|
||||
@@ -129,96 +135,91 @@ namespace Cryville.Crtr.Extensions.Malody {
|
||||
var sev = tev.StartEvent;
|
||||
longEvents.Remove(sev);
|
||||
}
|
||||
else throw new NotSupportedException();
|
||||
else throw new NotSupportedException("Unrecognized long event");
|
||||
}
|
||||
else throw new NotSupportedException();
|
||||
else throw new NotSupportedException("Unrecognized event");
|
||||
}
|
||||
chart.endtime = new BeatTime(endbeat[0] + 4, endbeat[1], endbeat[2]);
|
||||
meta.chart = new ChartMeta.MetaInfo() {
|
||||
name = src.meta.version,
|
||||
author = src.meta.creator,
|
||||
length = ctime,
|
||||
};
|
||||
var endbeat = tm.FractionalBeatTime;
|
||||
endbeat.b += 4;
|
||||
chart.endtime = endbeat;
|
||||
meta.length = (float)tm.Time;
|
||||
meta.note_count = group.notes.Count;
|
||||
string chartName = string.Format("{0} - {1}", meta.song.name, meta.chart.name);
|
||||
result.Add(new ChartResource(chartName, chart, meta));
|
||||
if (src.meta.background != null)
|
||||
result.Add(new CoverResource(chartName, new FileInfo(file.DirectoryName + "/" + src.meta.background)));
|
||||
string chartName = string.Format("{0} - {1}", meta.song.name, meta.name);
|
||||
if (src.meta.background != null) {
|
||||
meta.cover = src.meta.background;
|
||||
}
|
||||
result.Add(new RawChartResource(chartName, chart, meta));
|
||||
return result;
|
||||
}
|
||||
|
||||
struct StartEventState {
|
||||
public float Time { get; set; }
|
||||
public double Time { get; set; }
|
||||
public ChartEvent Destination { get; set; }
|
||||
}
|
||||
|
||||
float bp(int[] beat) {
|
||||
return beat[0] + (float)beat[1] / beat[2];
|
||||
}
|
||||
}
|
||||
|
||||
#pragma warning disable IDE1006
|
||||
public struct MalodyChart {
|
||||
public interface IEvent {
|
||||
int[] beat { get; set; }
|
||||
int[] endbeat { get; set; }
|
||||
int Priority { get; }
|
||||
}
|
||||
public struct EndEvent : IEvent {
|
||||
public int[] beat { get; set; }
|
||||
public int[] endbeat { get; set; }
|
||||
public IEvent StartEvent { get; set; }
|
||||
public int Priority { get { return StartEvent.Priority - 1; } }
|
||||
}
|
||||
|
||||
public Meta meta;
|
||||
public struct Meta {
|
||||
public SongInfo song;
|
||||
public struct SongInfo {
|
||||
public string title;
|
||||
public string artist;
|
||||
public string titleorg;
|
||||
public string artistorg;
|
||||
struct MalodyChart {
|
||||
public interface IEvent {
|
||||
int[] beat { get; set; }
|
||||
int[] endbeat { get; set; }
|
||||
int Priority { get; }
|
||||
}
|
||||
public struct EndEvent : IEvent {
|
||||
public int[] beat { get; set; }
|
||||
public int[] endbeat { get; set; }
|
||||
public IEvent StartEvent { get; set; }
|
||||
public int Priority { get { return StartEvent.Priority - 1; } }
|
||||
}
|
||||
|
||||
public string background;
|
||||
public Meta meta;
|
||||
public struct Meta {
|
||||
public SongInfo song;
|
||||
public struct SongInfo {
|
||||
public string title;
|
||||
public string artist;
|
||||
public string titleorg;
|
||||
public string artistorg;
|
||||
}
|
||||
|
||||
public string creator;
|
||||
public string version;
|
||||
public string background;
|
||||
|
||||
public int mode;
|
||||
public ModeExt mode_ext;
|
||||
public struct ModeExt {
|
||||
public string creator;
|
||||
public string version;
|
||||
|
||||
public int mode;
|
||||
public ModeExt mode_ext;
|
||||
public struct ModeExt {
|
||||
public int column;
|
||||
}
|
||||
}
|
||||
|
||||
public List<Time> time;
|
||||
public struct Time : IEvent {
|
||||
public int[] beat { get; set; }
|
||||
public int[] endbeat { get; set; }
|
||||
public float bpm;
|
||||
public int Priority { get { return -2; } }
|
||||
}
|
||||
|
||||
public List<Effect> effect;
|
||||
public struct Effect : IEvent {
|
||||
public int[] beat { get; set; }
|
||||
public int[] endbeat { get; set; }
|
||||
public float? scroll;
|
||||
public int Priority { get { return 0; } }
|
||||
}
|
||||
|
||||
public List<Note> note;
|
||||
public struct Note : IEvent {
|
||||
public int[] beat { get; set; }
|
||||
public int[] endbeat { get; set; }
|
||||
public int column;
|
||||
public string sound;
|
||||
public int offset;
|
||||
public int type;
|
||||
public int Priority { get { return 0; } }
|
||||
}
|
||||
}
|
||||
|
||||
public List<Time> time;
|
||||
public struct Time : IEvent {
|
||||
public int[] beat { get; set; }
|
||||
public int[] endbeat { get; set; }
|
||||
public float bpm;
|
||||
public int Priority { get { return -2; } }
|
||||
}
|
||||
|
||||
public List<Effect> effect;
|
||||
public struct Effect : IEvent {
|
||||
public int[] beat { get; set; }
|
||||
public int[] endbeat { get; set; }
|
||||
public float? scroll;
|
||||
public int Priority { get { return 0; } }
|
||||
}
|
||||
|
||||
public List<Note> note;
|
||||
public struct Note : IEvent {
|
||||
public int[] beat { get; set; }
|
||||
public int[] endbeat { get; set; }
|
||||
public int column;
|
||||
public string sound;
|
||||
public int offset;
|
||||
public int type;
|
||||
public int Priority { get { return 0; } }
|
||||
}
|
||||
}
|
||||
#pragma warning restore IDE1006
|
||||
}
|
||||
}
|
||||
|
26
Assets/Cryville/Crtr/Extensions/Malody/MalodyChartFinder.cs
Normal file
26
Assets/Cryville/Crtr/Extensions/Malody/MalodyChartFinder.cs
Normal file
@@ -0,0 +1,26 @@
|
||||
using Cryville.Common;
|
||||
using Cryville.Crtr.Browsing;
|
||||
using Microsoft.Win32;
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace Cryville.Crtr.Extensions.Malody {
|
||||
public class MalodyChartFinder : LocalResourceFinder {
|
||||
public override string Name { get { return "Malody beatmaps"; } }
|
||||
|
||||
public override string GetRootPath() {
|
||||
switch (Environment.OSVersion.Platform) {
|
||||
case PlatformID.Unix:
|
||||
return "/storage/emulated/0/data/malody/beatmap";
|
||||
case PlatformID.Win32NT:
|
||||
var reg = Registry.ClassesRoot.OpenSubKey(@"malody\Shell\Open\Command");
|
||||
if (reg == null) return null;
|
||||
var pathObj = reg.GetValue(null);
|
||||
if (pathObj == null) return null;
|
||||
var path = (string)pathObj;
|
||||
return Path.Combine(new FileInfo(StringUtils.GetProcessPathFromCommand(path)).Directory.FullName, "beatmap");
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3c9beaff62143a2468e18ad4642232c0
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
@@ -1,9 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: abad95983f1ca394a92bb061b76ebb2f
|
||||
guid: 6823ead66b33bc048bbad48719feb25d
|
||||
folderAsset: yes
|
||||
timeCreated: 1638411493
|
||||
licenseType: Free
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
153
Assets/Cryville/Crtr/Extensions/Quaver/QuaverChartConverter.cs
Normal file
153
Assets/Cryville/Crtr/Extensions/Quaver/QuaverChartConverter.cs
Normal file
@@ -0,0 +1,153 @@
|
||||
using Cryville.Crtr.Browsing;
|
||||
using Quaver.API.Maps;
|
||||
using Quaver.API.Maps.Structures;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
|
||||
namespace Cryville.Crtr.Extensions.Quaver {
|
||||
public class QuaverChartConverter : ResourceConverter {
|
||||
static readonly string[] SUPPORTED_FORMATS = { ".qua" };
|
||||
const double OFFSET = 0.05;
|
||||
|
||||
public override string[] GetSupportedFormats() {
|
||||
return SUPPORTED_FORMATS;
|
||||
}
|
||||
|
||||
public override IEnumerable<Resource> ConvertFrom(FileInfo file) {
|
||||
List<Resource> result = new List<Resource>();
|
||||
var src = Qua.Parse(file.FullName);
|
||||
var ruleset = "quaver!" + src.Mode.ToString().ToLower();
|
||||
var meta = new ChartMeta {
|
||||
name = src.DifficultyName,
|
||||
author = src.Creator,
|
||||
song = new SongMetaInfo {
|
||||
name = src.Title,
|
||||
author = src.Artist,
|
||||
},
|
||||
ruleset = ruleset,
|
||||
cover = src.BackgroundFile,
|
||||
note_count = src.HitObjects.Count,
|
||||
};
|
||||
var chart = new Chart {
|
||||
format = 2,
|
||||
time = new BeatTime(-4, 0, 1),
|
||||
ruleset = ruleset,
|
||||
sigs = new List<Chart.Signature>(),
|
||||
sounds = new List<Chart.Sound> {
|
||||
new Chart.Sound { time = new BeatTime(0, 0, 1), id = src.Title, offset = (float)(src.TimingPoints[0].StartTime / 1e3 + OFFSET) }
|
||||
},
|
||||
motions = new List<Chart.Motion>(),
|
||||
groups = new List<Chart.Group>(),
|
||||
};
|
||||
var group = new Chart.Group() {
|
||||
tracks = new List<Chart.Track>(),
|
||||
notes = new List<Chart.Note>(),
|
||||
motions = new List<Chart.Motion>(),
|
||||
};
|
||||
chart.groups.Add(group);
|
||||
result.Add(new RawChartResource(string.Format("{0} - {1}", meta.song.name, meta.name), chart, meta));
|
||||
result.Add(new SongResource(meta.song.name, new FileInfo(Path.Combine(file.DirectoryName, src.AudioFile))));
|
||||
|
||||
var evs = new List<EventWrapper>();
|
||||
foreach (var e in src.HitObjects) evs.Add(new EventWrapper.HitObject(e));
|
||||
foreach (var e in src.SliderVelocities) evs.Add(new EventWrapper.SliderVelocity(e));
|
||||
foreach (var e in src.SoundEffects) evs.Add(new EventWrapper.SoundEffect(e));
|
||||
foreach (var e in src.TimingPoints) evs.Add(new EventWrapper.TimingPoint(e));
|
||||
var evc = evs.Count;
|
||||
for (int i = 0; i < evc; i++) if (evs[i].IsLong) evs.Add(new EventWrapper.EndEvent(evs[i]));
|
||||
evs.Sort();
|
||||
|
||||
var longevs = new Dictionary<EventWrapper, ChartEvent>();
|
||||
var tm = new TimeTimingModel(src.TimingPoints[0].StartTime / 1e3);
|
||||
foreach (var ev in evs) {
|
||||
tm.ForwardTo(ev.StartTime / 1e3);
|
||||
if (ev is EventWrapper.HitObject) {
|
||||
var tev = (EventWrapper.HitObject)ev;
|
||||
var rn = new Chart.Note {
|
||||
time = tm.FractionalBeatTime,
|
||||
motions = new List<Chart.Motion> {
|
||||
new Chart.Motion { motion = string.Format(CultureInfo.InvariantCulture, "track:{0}", tev.Event.Lane - 1) }
|
||||
},
|
||||
};
|
||||
if (ev.IsLong) longevs.Add(ev, rn);
|
||||
group.notes.Add(rn);
|
||||
}
|
||||
else if (ev is EventWrapper.SliderVelocity) {
|
||||
var tev = (EventWrapper.SliderVelocity)ev;
|
||||
group.motions.Add(new Chart.Motion {
|
||||
time = tm.FractionalBeatTime,
|
||||
motion = string.Format(CultureInfo.InvariantCulture, "svm:{0}", tev.Event.Multiplier),
|
||||
});
|
||||
}
|
||||
else if (ev is EventWrapper.TimingPoint) {
|
||||
var tev = (EventWrapper.TimingPoint)ev;
|
||||
tm.BPM = tev.Event.Bpm;
|
||||
chart.sigs.Add(new Chart.Signature {
|
||||
time = tm.FractionalBeatTime,
|
||||
tempo = tev.Event.Bpm,
|
||||
});
|
||||
}
|
||||
else if (ev is EventWrapper.EndEvent) {
|
||||
var tev = (EventWrapper.EndEvent)ev;
|
||||
var oev = tev.Original;
|
||||
longevs[oev].endtime = tm.FractionalBeatTime;
|
||||
}
|
||||
else throw new NotSupportedException("Sound effects are not supported yet");
|
||||
}
|
||||
var endbeat = tm.FractionalBeatTime;
|
||||
endbeat.b += 4;
|
||||
chart.endtime = endbeat;
|
||||
meta.length = (float)tm.Time;
|
||||
return result;
|
||||
}
|
||||
|
||||
abstract class EventWrapper : IComparable<EventWrapper> {
|
||||
public abstract int StartTime { get; }
|
||||
public abstract int EndTime { get; }
|
||||
public bool IsLong { get { return EndTime > 0; } }
|
||||
public abstract int Priority { get; }
|
||||
public int CompareTo(EventWrapper other) {
|
||||
var c = StartTime.CompareTo(other.StartTime);
|
||||
if (c != 0) return c;
|
||||
return Priority.CompareTo(other.Priority);
|
||||
}
|
||||
public class HitObject : EventWrapper {
|
||||
public HitObjectInfo Event;
|
||||
public HitObject(HitObjectInfo ev) { Event = ev; }
|
||||
public override int StartTime { get { return Event.StartTime; } }
|
||||
public override int EndTime { get { return Event.EndTime; } }
|
||||
public override int Priority { get { return 0; } }
|
||||
}
|
||||
public class SliderVelocity : EventWrapper {
|
||||
public SliderVelocityInfo Event;
|
||||
public SliderVelocity(SliderVelocityInfo ev) { Event = ev; }
|
||||
public override int StartTime { get { return (int)Event.StartTime; } }
|
||||
public override int EndTime { get { return 0; } }
|
||||
public override int Priority { get { return 0; } }
|
||||
}
|
||||
public class SoundEffect : EventWrapper {
|
||||
public SoundEffectInfo Event;
|
||||
public SoundEffect(SoundEffectInfo ev) { Event = ev; }
|
||||
public override int StartTime { get { return (int)Event.StartTime; } }
|
||||
public override int EndTime { get { return 0; } }
|
||||
public override int Priority { get { return 0; } }
|
||||
}
|
||||
public class TimingPoint : EventWrapper {
|
||||
public TimingPointInfo Event;
|
||||
public TimingPoint(TimingPointInfo ev) { Event = ev; }
|
||||
public override int StartTime { get { return (int)Event.StartTime; } }
|
||||
public override int EndTime { get { return 0; } }
|
||||
public override int Priority { get { return -2; } }
|
||||
}
|
||||
public class EndEvent : EventWrapper {
|
||||
public EventWrapper Original;
|
||||
public EndEvent(EventWrapper ev) { if (!ev.IsLong) throw new ArgumentException("Event is not long"); Original = ev; }
|
||||
public override int StartTime { get { return Original.EndTime; } }
|
||||
public override int EndTime { get { return 0; } }
|
||||
public override int Priority { get { return Original.Priority - 1; } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b073cac7ce0d41a4f8ca589845678aa2
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
24
Assets/Cryville/Crtr/Extensions/Quaver/QuaverChartFinder.cs
Normal file
24
Assets/Cryville/Crtr/Extensions/Quaver/QuaverChartFinder.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using Cryville.Common;
|
||||
using Cryville.Crtr.Browsing;
|
||||
using Microsoft.Win32;
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace Cryville.Crtr.Extensions.Quaver {
|
||||
public class QuaverChartFinder : LocalResourceFinder {
|
||||
public override string Name { get { return "Quaver beatmaps"; } }
|
||||
|
||||
public override string GetRootPath() {
|
||||
switch (Environment.OSVersion.Platform) {
|
||||
case PlatformID.Win32NT:
|
||||
var reg = Registry.ClassesRoot.OpenSubKey(@"quaver\Shell\Open\Command");
|
||||
if (reg == null) return null;
|
||||
var pathObj = reg.GetValue(null);
|
||||
if (pathObj == null) return null;
|
||||
var path = (string)pathObj;
|
||||
return Path.Combine(new FileInfo(StringUtils.GetProcessPathFromCommand(path)).Directory.FullName, "Songs");
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 68bacf7746cbeea42a78a7d55cfdbea0
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user