上传YomovSDK

This commit is contained in:
Sora丶kong
2026-03-03 03:15:46 +08:00
parent 9096da7e6c
commit eb97f31065
6477 changed files with 1932208 additions and 3 deletions

View File

@@ -0,0 +1,259 @@
# Unity Converters for Newtonsoft.Json changelog
## 1.6.3 (2024-03-01)
- Fixed converter lookups collisions when multiple assemblies converters
with the same name, as it was not resolving assemblies in an exact way
nor deterministic order:
- Added assembly name field to `ConverterConfig` for each converter.
- Changed TypeCache to sort assemblies based on `FullName`
and some heuristics.
- Changed TypeCache to lookup type in correct assembly,
based on the assembly's name.
Thanks [@Erifirin](https://github.com/Erifirin) for the pull request ([#90](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/pull/90))
## 1.6.2 (2024-01-08)
- Fixed typo in the new Unity.Mathematics QuaternionConverter's namespace:
from `Newtonsoft.Json.UnityConverters.Math.QuaternionConverter`
to `Newtonsoft.Json.UnityConverters.Mathematics.QuaternionConverter`
(`Math` → `Mathematics`).
([#87](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/pull/87))
- Fixed compilation error when using Unity.Mathematics with Newtonsoft.JSON v10.
([#87](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/pull/87))
## 1.6.1 (2023-12-23)
- Fixed UnityConvertersConfigEditor scriptable object asset throwing error after
recompiling scripts in Unity 2022.3.0 when selected and shown in inspector.
([#82](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/pull/82))
Thanks [@EpsilonD3lta](https://github.com/EpsilonD3lta) for the implementation ([#83](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/pull/83))
## 1.6.0 (2023-12-03)
- Added converters for [Unity.Mathematics](https://docs.unity3d.com/Packages/com.unity.mathematics@1.3/manual/index.html).
This includes all the `float2`, `double3`, `int4`, `bool4`, and similar types.
([#80](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/pull/80))
There are no custom converters for the matrix types
(`float2x2`, `float2x3`, etc), as they currently work out-of-the-box.
- Added `ResolutionConverter` to be able to read JSON from older Unity
versions. ([#79](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/pull/79))
- Fixed compilation errors when targeting .NET Standard 2.1.
([#79](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/pull/79))
- Fixed converter types taking long time to load, sometimes causing lag spikes
each time assembly got reloaded (especially when entering play-mode).
The issue was that this package tries to find all converters by looping
through all types in all assemblies.
You should see better performance now, as we are using more optimized code
paths and making use of Unity's [TypeCache](https://docs.unity3d.com/2023.3/Documentation/ScriptReference/TypeCache.html).
If your project still suffers from big lag spikes, then you can opt-out
completely of the "auto type scanning" code via the settings found at
"Edit > Json.NET converters settings..." ([#79](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/pull/79))
- Thanks [@tomkail](https://github.com/tomkail) for the excellent issue ([#77](https://github.com/applejag/Newtonsoft.Json-for-Unity.Converters/issues/77)).
- Thanks [@Mefodei](https://github.com/Mefodei) for the inspiration ([#78](https://github.com/applejag/Newtonsoft.Json-for-Unity.Converters/pull/78))
## 1.5.1 (2023-04-19)
- Fixed converters being stripped when Managed Stripping Level is set to
anything higher than "minimal", by adding `[Preserve]` attribute
to the entire assemblies. ([#73](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/pull/73))
## 1.5.0 (2022-08-16)
- Added support for `UnityEngine.AddressableAssets.AssetReferenceT<T>`, in
addition to the existing support for the non-generic `AssetReference` version
introduced in v1.4.0.
Thanks [@kyverr](https://github.com/kyverr) for the implementation ([#71](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/pull/71))
## 1.4.0 (2022-02-05)
- Added support for `UnityEngine.AddressableAssets.AssetReference`.
The new `AssetReferenceConverter` is only included in the build if your
project contains the `com.unity.addressables` package.
([#67](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/pull/67))
This automatic inclusion relies on AssemblyDefinition version defines, which
was introduced in Unity 2019.1.x. To enable the `AssetReferenceConverter` in
earlier versions of Unity, please add `HAVE_MODULE_ADDRESSABLES` to your
project's "Scripting Define Symbols" found in the
"Project Settings" -> "Player" -> "Other Settings" panel.
## 1.3.0 (2021-10-21)
- Changed the following modules to be automatically excluded from compilation
if they are not used in the project:
- `com.unity.modules.ai` via new define `HAVE_MODULE_AI`
- `com.unity.modules.physics` via new define `HAVE_MODULE_PHYSICS`
- `com.unity.modules.physics2d` via new define `HAVE_MODULE_PHYSICS2D`
This is active starting with Unity 2019.1.x. The regarded modules are always
active in prior Unity versions.
Thanks [@SolidAlloy](https://github.com/SolidAlloy) for the implementation ([#60](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/pull/60))
## 1.2.0 (2021-09-11)
- Changed `UnityConverterInitializer` from `internal` to `public`.
([#58](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/issues/58))
## 1.1.1 (2021-05-30)
- Fixed Newtonsoft.Json converters (ex: `StringEnumConverter` &
`VersionConverter`) not being loaded even if you had then enabled in the
Newtonsoft.Json-for-Unity.Converters config.
([#55](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/issues/55))
## 1.1.0 (2021-04-05)
- Added configurability to enable/disable any converter that was all previously
inserted automatically. Access the settings via the menu at
"Edit > Json .NET converters settings..."
([#40](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/pull/40))
- Added custom contract resolver to look for the
`UnityEngine.SerializeFieldAttribute` and include attributed fields and
properties appropriately.
([#39](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/issues/39))
- Added `UnityEngine.ScriptableObject` deserialization support by using the
`ScriptableObject.Create(Type type)` method when reading the JSON.
([#39](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/issues/39))
- Fixed IL2CPP builds failing due to usage of `__makeref` in
`CullingGroupEventConverter`, `ColliderDistance2DConverter`, and
`RandomStateConverter`
([#35](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/issues/35))
- Fixed `float` precision error when reading/prasing. ([#46](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/issues/46),
[#51](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/issues/51))
- Added support for populating using `JsonConvert.PopulateObject` when using
any of the custom converters. ([#49](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/issues/49))
- Removed the array passing and reflection in the PartialConverter and removed
all partial converters except `PartialConverter.cs`, simplifying the code a
lot. This should lead to a minor performance boost as well.
([#48](https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/pull/48))
## 1.0.0 (2020-05-10)
- ✨ Initial release
- ❤ Big love from these authors allowing me to take inspiration from their
converters packages:
- ParentElement <https://github.com/ianmacgillivray/Json-NET-for-Unity>
- Wanzyee Studio <http://wanzyeestudio.blogspot.com/2017/03/jsonnet-converters.html>
- UnityConverterInitializer that registers converters on load
- Ensured via tests to work in Unity version:
- 2018.4
- 2019.2
- 2020.1
- Ensured via tests to work with API compatibility:
- .NET Standard 2.0
- Ensured via tests to work with Newtonsoft.Json version:
- 12.0.3
- Added custom converters for following types:
- [x] (AI/NavMesh) UnityEngine.AI.NavMeshQueryFilter
- [x] (AI/NavMesh) UnityEngine.AI.NavMeshTriangulation
- [x] (Camera) CullingGroupEvent
- [x] (Geometry) UnityEngine.Bounds
- [x] (Geometry) UnityEngine.BoundsInt
- [x] (Geometry) UnityEngine.Plane
- [x] (Geometry) UnityEngine.Rect
- [x] (Geometry) UnityEngine.RectInt
- [x] (Geometry) UnityEngine.RectOffset
- [x] (Hashing) UnityEngine.Hash128
- [x] (Math) UnityEngine.Color
- [x] (Math) UnityEngine.Color32
- [x] (Math) UnityEngine.Quaternion
- [x] (Math) UnityEngine.Rendering.SphericalHarmonicsL2
- [x] (Math) UnityEngine.Vector2
- [x] (Math) UnityEngine.Vector2Int
- [x] (Math) UnityEngine.Vector3
- [x] (Math) UnityEngine.Vector3Int
- [x] (Math) UnityEngine.Vector4
- [x] (Physics) UnityEngine.JointDrive
- [x] (Physics) UnityEngine.JointLimits
- [x] (Physics) UnityEngine.SoftJointLimit
- [x] (Physics2D) UnityEngine.ColliderDistance2D
- [x] (Physics2D) UnityEngine.ContactFilter2D
- [x] (Random) UnityEngine.Random.State
- [x] (Scripting) UnityEngine.LayerMask
- [x] (Scripting) UnityEngine.RangeInt
- Known to work, but no custom converter needed:
- [x] (AI/NavMesh) UnityEngine.AI.NavMeshHit
- [x] (AI/NavMesh) UnityEngine.AI.NavMeshLinkData
- [x] (Animation) UnityEngine.Keyframe
- [x] (Camera) BoundingSphere
- [x] (GameCenter) UnityEngine.SocialPlatforms.Range
- [x] (Geometry) UnityEngine.Ray
- [x] (Geometry) UnityEngine.Ray2D
- [x] (Graphics) UnityEngine.Resolution
- [x] (Math) UnityEngine.FrustumPlanes
- [x] (Math) UnityEngine.Gradient
- [x] (Math) UnityEngine.GradientAlphaKey
- [x] (Math) UnityEngine.GradientColorKey
- [x] (Physics) UnityEngine.BoxcastCommand
- [x] (Physics) UnityEngine.CapsulecastCommand
- [x] (Physics) UnityEngine.JointMotor
- [x] (Physics) UnityEngine.JointSpring
- [x] (Physics) UnityEngine.RaycastCommand
- [x] (Physics) UnityEngine.SoftJointLimitSpring
- [x] (Physics) UnityEngine.SpherecastCommand
- [x] (Physics) UnityEngine.WheelFrictionCurve
- [x] (Physics2D) UnityEngine.JointAngleLimits2D
- [x] (Physics2D) UnityEngine.JointMotor2D
- [x] (Physics2D) UnityEngine.JointSuspension2D
- [x] (Physics2D) UnityEngine.JointTranslationLimits2D
- [x] (Physics2D) UnityEngine.PhysicsJobOptions2D
- [x] (RenderPipeline) UnityEngine.Rendering.FilteringSettings
- [x] (RenderPipeline) UnityEngine.Rendering.RenderQueueRange
- [x] (RenderPipeline) UnityEngine.Rendering.SortingLayerRange
- [x] (SpriteShape) UnityEngine.U2D.AngleRangeInfo
- [x] (SpriteShape) UnityEngine.U2D.ShapeControlPoint
- [x] (SpriteShape) UnityEngine.U2D.SpriteShapeMetaData
- ❌ KNOWN NOT TO WORK (contains ID or reference to UnityEngine.Object):
- (AI/NavMesh) UnityEngine.AI.NavMeshDataInstance
- (AI/NavMesh) UnityEngine.AI.NavMeshLinkInstance
- (Physics) UnityEngine.ContactPoint
- (Physics) UnityEngine.PhysicsScene
- (Physics) UnityEngine.RaycastHit
- (Physics2D) UnityEngine.ContactPoint2D
- (Physics2D) UnityEngine.PhysicsScene2D
- (Physics2D) UnityEngine.RaycastHit2D
- (RenderPipeline) UnityEngine.Rendering.VisibleLight
- ❌ KNOWN NOT TO WORK (contains NativeArray/NativeSlice):
- (NativeArray) Unity.Collections.NativeArray<>
- (NativeArray) Unity.Collections.NativeSlice<>
- (ParticleSystem) UnityEngine.ParticleSystemJobs.ParticleSystemJobData
- (ParticleSystem) UnityEngine.ParticleSystemJobs.ParticleSystemNativeArray3
- (ParticleSystem) UnityEngine.ParticleSystemJobs.ParticleSystemNativeArray4
- (Rendering) UnityEngine.Rendering.BatchCullingContext
- ❌ KNOWN NOT TO WORK (contains readonly fields):
- (Rendering) UnityEngine.Rendering.BatchVisibility

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 41cf9e3fc74e5dfd9ade71a29b5f5405
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 931526329deb21f4c95264363c07cc4c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,10 @@
namespace Newtonsoft.Json.UnityConverters.Configuration
{
public enum ConfigType
{
Boolean,
Integer,
Number,
Text,
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1ce9e326b060ce44aa786589489ee7a5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
namespace Newtonsoft.Json.UnityConverters.Configuration
{
#pragma warning disable CA2235 // Mark all non-serializable fields
[Serializable]
[System.Diagnostics.DebuggerDisplay("{converterName}, enabled={enabled}")]
public struct ConverterConfig : IEquatable<ConverterConfig>
{
public bool enabled;
public string converterName;
public string converterAssembly;
public List<KeyedConfig> settings;
public override string ToString()
{
return $"{{enabled={enabled}, converterName={converterName}, assembly={converterAssembly}, settings=[{settings?.Count ?? 0}]}}";
}
public override bool Equals(object obj)
{
return obj is ConverterConfig config && Equals(config);
}
public bool Equals(ConverterConfig other)
{
return enabled == other.enabled &&
converterName == other.converterName &&
converterAssembly == other.converterAssembly &&
EqualityComparer<List<KeyedConfig>>.Default.Equals(settings, other.settings);
}
#pragma warning disable S2328 // "GetHashCode" should not reference mutable fields
public override int GetHashCode()
#pragma warning restore S2328 // "GetHashCode" should not reference mutable fields
{
int hashCode = 913629501;
hashCode = hashCode * -1521134295 + enabled.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(converterName);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(converterAssembly);
hashCode = hashCode * -1521134295 + EqualityComparer<List<KeyedConfig>>.Default.GetHashCode(settings);
return hashCode;
}
public static bool operator ==(ConverterConfig left, ConverterConfig right)
{
return left.Equals(right);
}
public static bool operator !=(ConverterConfig left, ConverterConfig right)
{
return !(left == right);
}
}
#pragma warning restore CA2235 // Mark all non-serializable fields
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 350f8e6a924e9204093fe7f43a7d3d52
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Configuration
{
#pragma warning disable CA2235 // Mark all non-serializable fields
[Serializable]
public struct KeyedConfig : IEquatable<KeyedConfig>
{
public string key;
public ConfigType type;
public bool boolean;
public int integer;
public float number;
public string text;
public override bool Equals(object obj)
{
return obj is KeyedConfig config && Equals(config);
}
public bool Equals(KeyedConfig other)
{
if (type != other.type)
{
return false;
}
switch (type)
{
case ConfigType.Boolean:
return boolean == other.boolean;
case ConfigType.Integer:
return integer == other.integer;
case ConfigType.Number:
return Mathf.Approximately(number, other.number);
case ConfigType.Text:
return text == other.text;
default:
return false;
}
}
#pragma warning disable S2328 // "GetHashCode" should not reference mutable fields
public override int GetHashCode()
#pragma warning restore S2328 // "GetHashCode" should not reference mutable fields
{
int hashCode = 910641971;
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(key);
hashCode = hashCode * -1521134295 + type.GetHashCode();
hashCode = hashCode * -1521134295 + boolean.GetHashCode();
hashCode = hashCode * -1521134295 + integer.GetHashCode();
hashCode = hashCode * -1521134295 + number.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(text);
return hashCode;
}
public static bool operator ==(KeyedConfig left, KeyedConfig right)
{
return left.Equals(right);
}
public static bool operator !=(KeyedConfig left, KeyedConfig right)
{
return !(left == right);
}
}
#pragma warning restore CA2235 // Mark all non-serializable fields
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2b1b9bbba08d40c46a4e29422663b731
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Converters;
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Configuration
{
#pragma warning disable CA2235 // Mark all non-serializable fields
[Serializable]
public sealed class UnityConvertersConfig : ScriptableObject
{
internal const string PATH = "Assets/Resources/Newtonsoft.Json-for-Unity.Converters.asset";
internal const string PATH_FOR_RESOURCES_LOAD = "Newtonsoft.Json-for-Unity.Converters";
public bool useUnityContractResolver = true;
public bool useAllOutsideConverters = true;
public List<ConverterConfig> outsideConverters = new List<ConverterConfig>();
public bool useAllUnityConverters = true;
public List<ConverterConfig> unityConverters = new List<ConverterConfig>();
public bool useAllJsonNetConverters;
public List<ConverterConfig> jsonNetConverters = new List<ConverterConfig> {
new ConverterConfig { converterName = typeof(StringEnumConverter).FullName, enabled = true },
new ConverterConfig { converterName = typeof(VersionConverter).FullName, enabled = true },
};
public bool autoSyncConverters = true;
}
#pragma warning restore CA2235 // Mark all non-serializable fields
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ce56e4dbb13e1644aa983b6dd170e4a7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: bf73be3e75baadd4fa7ef8f2d68f530a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,16 @@
{
"name": "Newtonsoft.Json.UnityConverters.Editor",
"references": [
"Newtonsoft.Json.UnityConverters"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": true,
"precompiledReferences": [
"Newtonsoft.Json.dll"
],
"autoReferenced": false
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 5bfce4977ee27f942abc10cf3f3bfee7
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,343 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.UnityConverters.Configuration;
using UnityEditor;
using UnityEditor.AnimatedValues;
using UnityEngine;
// Unity 2020 also has a type cache: UnityEditor.TypeCache:
// https://docs.unity3d.com/2019.2/Documentation/ScriptReference/TypeCache.html
using TypeCache = Newtonsoft.Json.UnityConverters.Utility.TypeCache;
namespace Newtonsoft.Json.UnityConverters.Editor
{
using Editor = UnityEditor.Editor;
[CustomEditor(typeof(UnityConvertersConfig))]
public class UnityConvertersConfigEditor : Editor
{
private SerializedProperty _useUnityContractResolver;
private SerializedProperty _useAllOutsideConverters;
private SerializedProperty _outsideConverters;
private SerializedProperty _useAllUnityConverters;
private SerializedProperty _unityConverters;
private SerializedProperty _useAllJsonNetConverters;
private SerializedProperty _jsonNetConverters;
private SerializedProperty _autoSyncConverters;
private AnimBool _outsideConvertersShow;
private AnimBool _unityConvertersShow;
private AnimBool _jsonNetConvertersShow;
private AnimBool _autoSyncConvertersShow;
private bool _isDirty;
private static class Styles
{
public static GUIStyle headerStyle;
public static GUIStyle boldHeaderStyle;
static Styles()
{
headerStyle = new GUIStyle { fontSize = 20, wordWrap = true, normal = EditorStyles.label.normal };
boldHeaderStyle = new GUIStyle { fontSize = 20, fontStyle = FontStyle.Bold, wordWrap = true, normal = EditorStyles.label.normal };
}
}
private void OnEnable()
{
var config = (UnityConvertersConfig)target;
var grouped = UnityConverterInitializer.FindGroupedConverters(config);
// Hack around the "SerializedObjectNotCreatableException: Object at index 0 is null"
// error message
try
{
_ = serializedObject;
}
catch (Exception)
{
return;
}
_useUnityContractResolver = serializedObject.FindProperty(nameof(UnityConvertersConfig.useUnityContractResolver));
_useAllOutsideConverters = serializedObject.FindProperty(nameof(UnityConvertersConfig.useAllOutsideConverters));
_outsideConverters = serializedObject.FindProperty(nameof(UnityConvertersConfig.outsideConverters));
_useAllUnityConverters = serializedObject.FindProperty(nameof(UnityConvertersConfig.useAllUnityConverters));
_unityConverters = serializedObject.FindProperty(nameof(UnityConvertersConfig.unityConverters));
_useAllJsonNetConverters = serializedObject.FindProperty(nameof(UnityConvertersConfig.useAllJsonNetConverters));
_jsonNetConverters = serializedObject.FindProperty(nameof(UnityConvertersConfig.jsonNetConverters));
_autoSyncConverters = serializedObject.FindProperty(nameof(UnityConvertersConfig.autoSyncConverters));
_outsideConvertersShow = new AnimBool(_outsideConverters.isExpanded);
_unityConvertersShow = new AnimBool(_unityConverters.isExpanded);
_jsonNetConvertersShow = new AnimBool(_jsonNetConverters.isExpanded);
_autoSyncConvertersShow = new AnimBool(!_autoSyncConverters.boolValue);
_outsideConvertersShow.valueChanged.AddListener(Repaint);
_unityConvertersShow.valueChanged.AddListener(Repaint);
_jsonNetConvertersShow.valueChanged.AddListener(Repaint);
serializedObject.Update();
AddAndSetupConverters(_outsideConverters, grouped.outsideConverters, _useAllOutsideConverters.boolValue);
AddAndSetupConverters(_unityConverters, grouped.unityConverters, _useAllUnityConverters.boolValue);
AddAndSetupConverters(_jsonNetConverters, grouped.jsonNetConverters, _useAllJsonNetConverters.boolValue);
serializedObject.ApplyModifiedProperties();
}
public override void OnInspectorGUI()
{
_isDirty = false;
EditorGUILayout.LabelField("Settings for the converters of", Styles.headerStyle);
EditorGUILayout.LabelField("Newtonsoft.Json-for-Unity.Converters", Styles.boldHeaderStyle);
serializedObject.Update();
EditorGUILayout.Space();
ToggleLeft(_useUnityContractResolver, "Custom 'Newtonsoft.Json.Serialization.IContractResolver' defined to" +
" properly handle the 'UnityEngine.SerializeFieldAttribute' attribute and correctly creates" +
" 'UnityEngine.ScriptableObject' via 'ScriptableObject.Create()' instead of the default" +
" 'new ScriptableObject()'.");
EditorGUILayout.Space();
FoldedConverters(_useAllOutsideConverters, _outsideConverters, _outsideConvertersShow,
"Registers all classes outside of the 'Newtonsoft.Json.*' namespace" +
" that derive from 'Newtonsoft.Json.JsonConverter' that has a default constructor.");
EditorGUILayout.Space();
FoldedConverters(_useAllUnityConverters, _unityConverters, _unityConvertersShow,
"Registers all classes inside of the 'Newtonsoft.Json.UnityConverters.*' namespace.");
EditorGUILayout.Space();
FoldedConverters(_useAllJsonNetConverters, _jsonNetConverters, _jsonNetConvertersShow,
"Registers all classes inside of the 'Newtonsoft.Json.UnityConverters.*' namespace.");
EditorGUILayout.Space();
ToggleLeft(_autoSyncConverters,
"Automatic synchronization of JsonConverter types is enabled by default," +
" but can induce a heavy spike on each assembly reload (such as when entering play mode) on bigger projects.");
_autoSyncConvertersShow.target = !_autoSyncConverters.boolValue;
if (EditorGUILayout.BeginFadeGroup(_autoSyncConvertersShow.faded))
{
EditorGUILayout.HelpBox("The Newtonsoft.Json-for-Unity.Converters package will no longer automatically" +
" look for new JsonConverters.\n\n" +
"Having this automatic scan disabled reduces the load spike caused on larger projects every time you enter play mode," +
" but you must instead remember to press the sync button below every time you add a new JsonConverter.",
MessageType.Warning);
if (GUILayout.Button("Manual Converter Sync Now"))
{
var grouped = ConverterGrouping.Create(UnityConverterInitializer.FindConverters());
AddAndSetupConverters(_outsideConverters, grouped.outsideConverters, _useAllOutsideConverters.boolValue);
AddAndSetupConverters(_unityConverters, grouped.unityConverters, _useAllUnityConverters.boolValue);
AddAndSetupConverters(_jsonNetConverters, grouped.jsonNetConverters, _useAllJsonNetConverters.boolValue);
}
}
EditorGUILayout.EndFadeGroup();
serializedObject.ApplyModifiedProperties();
if (_isDirty)
{
UnityConverterInitializer.RefreshSettingsFromConfig();
}
}
private void AddAndSetupConverters(SerializedProperty arrayProperty, IList<Type> converterTypes, bool newAreEnabledByDefault)
{
var elements = EnumerateArrayElements(arrayProperty).ToArray();
var elementTypes = elements
.Select(e => TypeCache.FindType(
name: e.FindPropertyRelative(nameof(ConverterConfig.converterName)).stringValue,
assemblyName: e.FindPropertyRelative(nameof(ConverterConfig.converterAssembly)).stringValue
))
.ToArray();
// Refresh missing fields on existing types
for (int i = 0; i < elements.Length; i++)
{
SerializedProperty elem = elements[i];
Type type = elementTypes[i];
var assemblyNameProp = elem.FindPropertyRelative(nameof(ConverterConfig.converterAssembly));
if (string.IsNullOrEmpty(assemblyNameProp.stringValue))
{
assemblyNameProp.stringValue = type.Assembly.GetName().Name;
}
}
Type[] missingConverters = converterTypes
.Where(type => !elementTypes.Contains(type))
.ToArray();
// Cleanup excess types
for (int i = elementTypes.Length - 1; i >= 0; i--)
{
if (converterTypes.Contains(elementTypes[i]))
{
continue;
}
string typeName = arrayProperty.GetArrayElementAtIndex(i).FindPropertyRelative(nameof(ConverterConfig.converterName)).stringValue;
Debug.Log($"Removed type from JsonConverter list: \"{typeName}\"", target);
arrayProperty.DeleteArrayElementAtIndex(i);
}
foreach (Type converterType in missingConverters)
{
int nextIndex = arrayProperty.arraySize;
arrayProperty.InsertArrayElementAtIndex(nextIndex);
SerializedProperty elemProp = arrayProperty.GetArrayElementAtIndex(nextIndex);
SerializedProperty enabledProp = elemProp.FindPropertyRelative(nameof(ConverterConfig.enabled));
SerializedProperty converterNameProp = elemProp.FindPropertyRelative(nameof(ConverterConfig.converterName));
SerializedProperty assemblyNameProp = elemProp.FindPropertyRelative(nameof(ConverterConfig.converterAssembly));
enabledProp.boolValue = newAreEnabledByDefault;
converterNameProp.stringValue = converterType.FullName;
assemblyNameProp.stringValue = converterType.Assembly.GetName().Name;
}
}
private static IEnumerable<SerializedProperty> EnumerateArrayElements(SerializedProperty arrayProperty)
{
for (int i = 0; i < arrayProperty.arraySize; i++)
{
yield return arrayProperty.GetArrayElementAtIndex(i);
}
}
private void FoldedConverters(
SerializedProperty useAllBoolProperty,
SerializedProperty convertersArrayProperty,
AnimBool foldoutAnim,
string tooltip)
{
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
ToggleLeft(useAllBoolProperty, tooltip);
EditorGUI.BeginDisabledGroup(useAllBoolProperty.boolValue || convertersArrayProperty.arraySize == 0);
FoldoutConvertersList(convertersArrayProperty, foldoutAnim);
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndVertical();
EditorGUILayout.Space();
}
private static void ToggleLeft(SerializedProperty property, string tooltip)
{
var content = new GUIContent {
text = property.displayName,
tooltip = tooltip,
};
property.boolValue = EditorGUILayout.ToggleLeft(content, property.boolValue);
}
private void FoldoutConvertersList(SerializedProperty property, AnimBool fadedAnim)
{
string displayName = $"{property.displayName} ({(property.arraySize == 0 ? "none found" : property.arraySize.ToString())})";
EditorGUI.indentLevel++;
property.isExpanded = EditorGUILayout.Foldout(property.isExpanded, displayName, true);
EditorGUI.indentLevel--;
fadedAnim.target = property.isExpanded;
if (EditorGUILayout.BeginFadeGroup(fadedAnim.faded))
{
EditorGUI.indentLevel++;
var allConfigsWithType = EnumerateArrayElements(property)
.Select(o => (
serializedProperty: o,
type: TypeCache.FindType(
name: o.FindPropertyRelative(nameof(ConverterConfig.converterName)).stringValue,
assemblyName: o.FindPropertyRelative(nameof(ConverterConfig.converterAssembly)).stringValue
)
))
.Where(o => o.type != null)
.OrderBy(o => o.type.FullName);
foreach (var namespaceGroup in allConfigsWithType.GroupBy(o => GetTypeNamespace(o.type)))
{
var groupLabel = new GUIContent {
tooltip = GetNamespaceTooltip(namespaceGroup),
text = GetNamespaceHeader(namespaceGroup),
};
EditorGUILayout.LabelField(groupLabel, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
foreach (var configWithType in namespaceGroup.OrderBy(o => o.type?.Name))
{
SerializedProperty enabledProp = configWithType.serializedProperty.FindPropertyRelative(nameof(ConverterConfig.enabled));
if (configWithType.type != null)
{
var toggleContent = new GUIContent {
text = configWithType.type.Name,
tooltip = configWithType.type.AssemblyQualifiedName,
};
bool oldValue = enabledProp.boolValue;
enabledProp.boolValue = EditorGUILayout.ToggleLeft(toggleContent, enabledProp.boolValue);
if (oldValue != enabledProp.boolValue)
{
_isDirty = true;
}
}
else
{
if (enabledProp.boolValue)
{
enabledProp.boolValue = false;
}
SerializedProperty converterNameProp = configWithType.serializedProperty.FindPropertyRelative(nameof(ConverterConfig.converterName));
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.ToggleLeft($"Unknown type: {converterNameProp.stringValue}", false);
EditorGUI.EndDisabledGroup();
}
}
EditorGUI.indentLevel--;
EditorGUILayout.Space();
}
EditorGUI.indentLevel--;
}
EditorGUILayout.EndFadeGroup();
}
private static string GetNamespaceHeader(IGrouping<string, (SerializedProperty serializedProperty, Type type)> namespaceGroup)
{
return $"{namespaceGroup.Key ?? "<Misconfigured converters>"} ({namespaceGroup.Count()})";
}
private static string GetNamespaceTooltip(IGrouping<string, (SerializedProperty serializedProperty, Type type)> namespaceGroup)
{
switch (namespaceGroup.Key)
{
case "global::":
return "Converters found with a default constructor from the global namespace.";
case null:
return "Converters that was found in the configuration but was" +
" unable to map them to existing types. Maybe the type got renamed, or moved to a different" +
" namespace?";
default:
return $"Converters found with a default constructor from the namespace '{namespaceGroup.Key}'.";
}
}
private static string GetTypeNamespace(Type type)
{
return type is null ? null : (type.Namespace ?? "global::");
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 756271e7f53946f49910eea19d887e13
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,46 @@
using System.IO;
using Newtonsoft.Json.UnityConverters.Configuration;
using UnityEditor;
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Editor
{
public static class UnityConvertersConfigMenu
{
[MenuItem("Edit/Json.NET converters settings...", false, 250)]
public static void OpenOrCreateConfig()
{
var config = GetOrCreateConfig();
EditorUtility.FocusProjectWindow();
EditorWindow inspectorWindow = EditorWindow.GetWindow(typeof(UnityEditor.Editor).Assembly.GetType("UnityEditor.InspectorWindow"));
inspectorWindow.Focus();
Selection.activeObject = config;
}
private static UnityConvertersConfig GetOrCreateConfig()
{
var config = Resources.Load<UnityConvertersConfig>(UnityConvertersConfig.PATH_FOR_RESOURCES_LOAD);
if (config)
{
return config;
}
config = ScriptableObject.CreateInstance<UnityConvertersConfig>();
string directory = Path.GetDirectoryName(UnityConvertersConfig.PATH);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
AssetDatabase.CreateAsset(config, UnityConvertersConfig.PATH);
AssetDatabase.SaveAssets();
return config;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 08ee7026bef0aaa45bc56f1d4cf3f303
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2019 Kalle Fagerberg (jilleJr)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 16d181ae4e75538ea4ddb067f42ecd6b
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,37 @@
{
"name": "Newtonsoft.Json.UnityConverters",
"rootNamespace": "Newtonsoft.Json",
"references": [],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": true,
"precompiledReferences": [
"Newtonsoft.Json.dll"
],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [
{
"name": "com.unity.modules.ai",
"expression": "",
"define": "HAVE_MODULE_AI"
},
{
"name": "com.unity.modules.physics",
"expression": "",
"define": "HAVE_MODULE_PHYSICS"
},
{
"name": "com.unity.modules.physics2d",
"expression": "",
"define": "HAVE_MODULE_PHYSICS2D"
},
{
"name": "com.unity.mathematics",
"expression": "",
"define": "HAVE_MODULE_MATHEMATICS"
}
],
"noEngineReferences": false
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: c55d28459d9c4444ebb4788be912e1f1
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 68cb0d886e404ce22bf516baa70cc565
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,11 @@
using System.Runtime.CompilerServices;
using UnityEngine.Scripting;
[assembly: Preserve]
[assembly: InternalsVisibleTo("Newtonsoft.Json.UnityConverters.Addressables")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.UnityConverters.Mathematics")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.UnityConverters.Editor")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.UnityConverters.Tests")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.UnityConverters.Tests.Addressables")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.UnityConverters.Tests.Mathematics")]

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: bb2756b550ea8855987f5b4f536aa544
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,44 @@
# Unity Converters for Newtonsoft.Json
This package contains converters to and from common Unity types. Types such as
**Vector2, Vector3, Matrix4x4, Quaternions, Color, even ScriptableObject,**
*and many, many more.*
(See the [full compatibility table of all +50 supported Unity types][
doc-compatability-table])
## Prerequisites
The Newtonsoft.Json library must be added to your project beforehand.
Recommended to use the
[jillejr.newtonsoft.json-for-unity][main-repo] package.
## Installation via Unity Package Manager
Visit the jilleJr/Newtonsoft.Json-for-Unity/wiki for installation
- [Installation via <abbr title="UPM: Unity Package Manager, included in Unity since 2018.1+">UPM</abbr>][wiki-install-converters-via-upm]
- [Installation via <abbr title="OpenUPM: A very popular open source Unity package registry for UPM packages">OpenUPM</abbr> ![OpenUPM icon][openupm-icon]][wiki-install-converters-via-openupm]
- [Installation via <abbr title="Git: Git is a free and open source distributed version control system.">Git</abbr> in UPM][wiki-install-converters-via-git-in-upm]
## Changelog
Please see the [CHANGELOG.md][package-changelog] file inside this package.
---
This package is licensed under The MIT License (MIT)
Copyright (c) 2019 Kalle Fagerberg (jilleJr)
<https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters>
See full copyrights in [LICENSE.md][package-license] inside repository
[main-repo]: https://github.com/jilleJr/Newtonsoft.Json-for-Unity#readme
[repo-compatability-table]: https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/blob/master/Doc/Compatability-table.md
[package-changelog]: https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/blob/master/CHANGELOG.md
[package-license]: https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/blob/master/LICENSE.md
[wiki-install-converters-via-git-in-upm]: https://github.com/jilleJr/Newtonsoft.Json-for-Unity/wiki/Install-Converters-via-Git-in-UPM
[wiki-install-converters-via-openupm]: https://github.com/jilleJr/Newtonsoft.Json-for-Unity/wiki/Install-Converters-via-OpenUPM
[wiki-install-converters-via-upm]: https://github.com/jilleJr/Newtonsoft.Json-for-Unity/wiki/Install-Converters-via-UPM
[openupm-icon]: https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/raw/326b8e4c9b4fd9c583808dd1c66381ed8d206b1c/Doc/images/openupm-icon-16.png

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: a65719f99e2b5137bc29cef23482dd7b
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,96 @@
This repository ([jilleJr/Newtonsoft.Json-for-Unity.Converters][repo-url])
contains code from many glorious other open source projects.
Without those this repository would never been created. ❤ Much love.
---
<details>
<summary>Json.NET Converters &copy; 2020 Wanzyee Studio</summary>
<http://wanzyeestudio.blogspot.com/2017/03/jsonnet-converters.html>
The MIT License (MIT)
Copyright (c) 2020 Wanzyee Studio
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
</details>
<details>
<summary>Json-NET-for-Unity &copy; 2017 parentelement</summary>
<https://github.com/ianmacgillivray/Json-NET-for-Unity>
The MIT License (MIT)
Copyright (c) 2017 parentelement
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
</details>
<details>
<summary>.NET Runtime &copy; 2017 .NET Foundation and Contributors</summary>
<https://github.com/dotnet/runtime>
The MIT License (MIT)
Copyright (c) .NET Foundation and Contributors
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
</details>
[repo-url]: https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 5dcea90cff4856b18e507dfd207c659f
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 715cd970403959c49a9b81a44ab18aa4
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 082e757dc436e2841b1e51ff251b917a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: bed4e3969067d914294db2e83b32787f
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,55 @@
#if HAVE_MODULE_AI || !UNITY_2019_1_OR_NEWER
using System;
using Newtonsoft.Json.UnityConverters.Helpers;
using UnityEngine;
using UnityEngine.AI;
namespace Newtonsoft.Json.UnityConverters.AI.NavMesh
{
public class NavMeshQueryFilterConverter : PartialConverter<NavMeshQueryFilter>
{
// Magic number taken from /Modules/AI/NavMesh/NavMesh.bindings.cs
// inside Unitys open source repo
// https://github.com/Unity-Technologies/UnityCsReference/blob/2019.2/Modules/AI/NavMesh/NavMesh.bindings.cs#L149
private const int AREA_COST_ELEMENT_COUNT = 32;
protected override void ReadValue(ref NavMeshQueryFilter value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case "costs":
var costs = reader.ReadViaSerializer<float[]>(serializer);
if (costs != null)
{
for (int i = Mathf.Min(costs.Length, AREA_COST_ELEMENT_COUNT) - 1; i >= 0; i--)
{
value.SetAreaCost(i, costs[i]);
}
}
break;
case nameof(value.areaMask):
value.areaMask = reader.ReadAsInt32() ?? 0;
break;
case "agentTypeId": // camelCased the ID->Id
value.agentTypeID = reader.ReadAsInt32() ?? 0;
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, NavMeshQueryFilter value, JsonSerializer serializer)
{
writer.WritePropertyName("costs");
writer.WriteStartArray();
for (int i = 0; i < AREA_COST_ELEMENT_COUNT; i++)
{
writer.WriteValue(value.GetAreaCost(i));
}
writer.WriteEndArray();
writer.WritePropertyName(nameof(value.areaMask));
writer.WriteValue(value.areaMask);
writer.WritePropertyName("agentTypeId"); // camelCased the ID->id
writer.WriteValue(value.agentTypeID);
}
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9b3e95150c60e5646a91827a4ec40452
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,39 @@
#if HAVE_MODULE_AI || !UNITY_2019_1_OR_NEWER
using System;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json.UnityConverters.Helpers;
using UnityEngine;
using UnityEngine.AI;
namespace Newtonsoft.Json.UnityConverters.AI.NavMesh
{
public class NavMeshTriangulationConverter : PartialConverter<NavMeshTriangulation>
{
protected override void ReadValue(ref NavMeshTriangulation value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.vertices):
value.vertices = reader.ReadViaSerializer<Vector3[]>(serializer);
break;
case nameof(value.indices):
value.indices = reader.ReadViaSerializer<int[]>(serializer);
break;
case nameof(value.areas):
value.areas = reader.ReadViaSerializer<int[]>(serializer);
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, NavMeshTriangulation value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.vertices));
serializer.Serialize(writer, value.vertices, typeof(Vector3[]));
writer.WritePropertyName(nameof(value.indices));
serializer.Serialize(writer, value.indices, typeof(int[]));
writer.WritePropertyName(nameof(value.areas));
serializer.Serialize(writer, value.areas, typeof(int[]));
}
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d84da7b6e96913a4588d123bcfd10833
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1d3d6db2520f0b14da096b76a6cd8827
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,52 @@
using System;
using Newtonsoft.Json.UnityConverters.Helpers;
using UnityEngine.AddressableAssets;
using UnityEngine.Scripting;
[assembly: Preserve]
namespace Newtonsoft.Json.UnityConverters.Addressables
{
public class AssetReferenceConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(AssetReference) || (objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(AssetReferenceT<>));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
if (reader.TokenType == JsonToken.String && reader.Value is string stringValue)
{
if (objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(AssetReferenceT<>))
{
return Activator.CreateInstance(objectType, stringValue);
} else
{
return new AssetReference(stringValue);
}
}
else
{
throw reader.CreateSerializationException($"Expected string when reading UnityEngine.Addressables.AssetReference type, got '{reader.TokenType}' <{reader.Value}>.");
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is null || string.IsNullOrEmpty(((AssetReference)value).AssetGUID))
{
writer.WriteNull();
}
else
{
writer.WriteValue(((AssetReference)value).AssetGUID);
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 599e3e9b08862c44db7fb4ba60611b38
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,24 @@
{
"name": "Newtonsoft.Json.UnityConverters.Addressables",
"references": [
"Unity.Addressables",
"Newtonsoft.Json.UnityConverters"
],
"optionalUnityReferences": [],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [
"HAVE_MODULE_ADDRESSABLES"
],
"versionDefines": [
{
"name": "com.unity.addressables",
"expression": "",
"define": "HAVE_MODULE_ADDRESSABLES"
}
]
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 54b32bbb6d015da4881a30377f540d42
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 4ad78b849f7b0564b9b9e2ad9b5d1b38
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,63 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Newtonsoft.Json.UnityConverters.Helpers;
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Camera
{
public class CullingGroupEventConverter : PartialConverter<CullingGroupEvent>
{
private const byte DISTANCE_MASK = (1 << 7) - 1;
[MaybeNull]
private static readonly FieldInfo _indexField = typeof(CullingGroupEvent).GetFieldInfoOrThrow("m_Index");
[MaybeNull]
private static readonly FieldInfo _prevStateField = typeof(CullingGroupEvent).GetFieldInfoOrThrow("m_PrevState");
[MaybeNull]
private static readonly FieldInfo _thisStateField = typeof(CullingGroupEvent).GetFieldInfoOrThrow("m_ThisState");
protected override void ReadValue(ref CullingGroupEvent value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.index):
_indexField.SetValueDirectRef(ref value, reader.ReadAsInt32() ?? 0);
break;
case nameof(value.isVisible):
SetStateField(_thisStateField, ref value, value.currentDistance, reader.ReadAsBoolean() ?? false);
break;
case nameof(value.wasVisible):
SetStateField(_prevStateField, ref value, value.previousDistance, reader.ReadAsBoolean() ?? false);
break;
case nameof(value.currentDistance):
SetStateField(_thisStateField, ref value, reader.ReadAsInt32() ?? 0, value.isVisible);
break;
case nameof(value.previousDistance):
SetStateField(_prevStateField, ref value, reader.ReadAsInt32() ?? 0, value.wasVisible);
break;
}
}
private static void SetStateField(FieldInfo field, ref CullingGroupEvent value, int distance, bool isVisible)
{
byte isVisibleByte = isVisible ? (byte)0x80 : (byte)0;
byte stateByte = (byte)(isVisibleByte | (distance & DISTANCE_MASK));
field.SetValueDirectRef(ref value, stateByte);
}
protected override void WriteJsonProperties(JsonWriter writer, CullingGroupEvent value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.index));
writer.WriteValue(value.index);
writer.WritePropertyName(nameof(value.isVisible));
writer.WriteValue(value.isVisible);
writer.WritePropertyName(nameof(value.wasVisible));
writer.WriteValue(value.wasVisible);
writer.WritePropertyName(nameof(value.currentDistance));
writer.WriteValue(value.currentDistance);
writer.WritePropertyName(nameof(value.previousDistance));
writer.WriteValue(value.previousDistance);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4d200ebb4554cb544b32181686e1d75e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,65 @@
#region License
// The MIT License (MIT)
//
// Copyright (c) 2020 Wanzyee Studio
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
#if UNITY_EDITOR
#endif
namespace Newtonsoft.Json.UnityConverters
{
internal class ConverterGrouping
{
public List<Type> outsideConverters { get; set; }
public List<Type> unityConverters { get; set; }
public List<Type> jsonNetConverters { get; set; }
public static ConverterGrouping Create(IEnumerable<Type> types)
{
var grouping = new ConverterGrouping {
outsideConverters = new List<Type>(),
unityConverters = new List<Type>(),
jsonNetConverters = new List<Type>(),
};
foreach (var converter in types)
{
if (converter.Namespace?.StartsWith("Newtonsoft.Json.UnityConverters") == true)
{
grouping.unityConverters.Add(converter);
}
else if (converter.Namespace?.StartsWith("Newtonsoft.Json.Converters") == true)
{
grouping.jsonNetConverters.Add(converter);
}
else
{
grouping.outsideConverters.Add(converter);
}
}
return grouping;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d8df7670f2ef36e4d8a1222c390b28e0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 150539deb4f4a4440a1f5eda0a28349a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,56 @@
#region License
// The MIT License (MIT)
//
// Copyright (c) 2020 Wanzyee Studio
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
using Newtonsoft.Json.UnityConverters.Helpers;
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Geometry
{
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity Bounds type <see cref="Bounds"/>.
/// </summary>
public class BoundsConverter : PartialConverter<Bounds>
{
protected override void ReadValue(ref Bounds value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.center):
value.center = reader.ReadViaSerializer<Vector3>(serializer);
break;
case nameof(value.size):
value.size = reader.ReadViaSerializer<Vector3>(serializer);
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, Bounds value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.center));
serializer.Serialize(writer, value.center, typeof(Vector3));
writer.WritePropertyName(nameof(value.size));
serializer.Serialize(writer, value.size, typeof(Vector3));
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0d2729e9ff28c004bbda58b6ecffe053
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,58 @@
#region License
// The MIT License (MIT)
//
// Copyright (c) 2020 Wanzyee Studio
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
using Newtonsoft.Json.UnityConverters.Helpers;
using UnityEngine;
using UnityEngine.Scripting;
namespace Newtonsoft.Json.UnityConverters.Geometry
{
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity integer Bounds type <see cref="BoundsInt"/>.
/// </summary>
public class BoundsIntConverter : PartialConverter<BoundsInt>
{
protected override void ReadValue(ref BoundsInt value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.position):
value.position = reader.ReadViaSerializer<Vector3Int>(serializer);
break;
case nameof(value.size):
value.size = reader.ReadViaSerializer<Vector3Int>(serializer);
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, BoundsInt value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.position));
serializer.Serialize(writer, value.position, typeof(Vector3Int));
writer.WritePropertyName(nameof(value.size));
serializer.Serialize(writer, value.size, typeof(Vector3Int));
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5463600b4a29b4746a12c3f686329b0e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,29 @@
using Newtonsoft.Json.UnityConverters.Helpers;
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Geometry
{
public class PlaneConverter : PartialConverter<Plane>
{
protected override void ReadValue(ref Plane value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.normal):
value.normal = reader.ReadViaSerializer<Vector3>(serializer);
break;
case nameof(value.distance):
value.distance = reader.ReadAsFloat() ?? 0;
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, Plane value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.normal));
serializer.Serialize(writer, value.normal, typeof(Vector3));
writer.WritePropertyName(nameof(value.distance));
writer.WriteValue(value.distance);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d4b26647e991900499216051e41994df
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,66 @@
#region License
// The MIT License (MIT)
//
// Copyright (c) 2020 Wanzyee Studio
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
using Newtonsoft.Json.UnityConverters.Helpers;
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Geometry
{
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity Rect type <see cref="Rect"/>.
/// </summary>
public class RectConverter : PartialConverter<Rect>
{
protected override void ReadValue(ref Rect value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.x):
value.x = reader.ReadAsFloat() ?? 0;
break;
case nameof(value.y):
value.y = reader.ReadAsFloat() ?? 0;
break;
case nameof(value.width):
value.width = reader.ReadAsFloat() ?? 0;
break;
case nameof(value.height):
value.height = reader.ReadAsFloat() ?? 0;
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, Rect value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.x));
writer.WriteValue(value.x);
writer.WritePropertyName(nameof(value.y));
writer.WriteValue(value.y);
writer.WritePropertyName(nameof(value.width));
writer.WriteValue(value.width);
writer.WritePropertyName(nameof(value.height));
writer.WriteValue(value.height);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fbec5ae23d2fad244a30539e92987dd6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,65 @@
#region License
// The MIT License (MIT)
//
// Copyright (c) 2020 Wanzyee Studio
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Geometry
{
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity RectInt type <see cref="RectInt"/>.
/// </summary>
public class RectIntConverter : PartialConverter<RectInt>
{
protected override void ReadValue(ref RectInt value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.x):
value.x = reader.ReadAsInt32() ?? 0;
break;
case nameof(value.y):
value.y = reader.ReadAsInt32() ?? 0;
break;
case nameof(value.width):
value.width = reader.ReadAsInt32() ?? 0;
break;
case nameof(value.height):
value.height = reader.ReadAsInt32() ?? 0;
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, RectInt value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.x));
writer.WriteValue(value.x);
writer.WritePropertyName(nameof(value.y));
writer.WriteValue(value.y);
writer.WritePropertyName(nameof(value.width));
writer.WriteValue(value.width);
writer.WritePropertyName(nameof(value.height));
writer.WriteValue(value.height);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 155a28c5745d7b5478f93f445facaf01
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,65 @@
#region License
// The MIT License (MIT)
//
// Copyright (c) 2020 Wanzyee Studio
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Geometry
{
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity RectOffset type <see cref="RectOffset"/>.
/// </summary>
public class RectOffsetConverter : PartialConverter<RectOffset>
{
protected override void ReadValue(ref RectOffset value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.left):
value.left = reader.ReadAsInt32() ?? 0;
break;
case nameof(value.right):
value.right = reader.ReadAsInt32() ?? 0;
break;
case nameof(value.top):
value.top = reader.ReadAsInt32() ?? 0;
break;
case nameof(value.bottom):
value.bottom = reader.ReadAsInt32() ?? 0;
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, RectOffset value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.left));
writer.WriteValue(value.left);
writer.WritePropertyName(nameof(value.right));
writer.WriteValue(value.right);
writer.WritePropertyName(nameof(value.top));
writer.WriteValue(value.top);
writer.WritePropertyName(nameof(value.bottom));
writer.WriteValue(value.bottom);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3a20aa434de15584a84137fea1e06814
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 83cc1315150ccd948ba38f1d831f7daa
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,61 @@
using Newtonsoft.Json.UnityConverters.Helpers;
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Graphics
{
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity Color type <see cref="Color"/>.
/// </summary>
public class ResolutionConverter : PartialConverter<Resolution>
{
protected override void ReadValue(ref Resolution value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.width):
value.width = reader.ReadAsInt32() ?? 0;
break;
case nameof(value.height):
value.height = reader.ReadAsInt32() ?? 0;
break;
#pragma warning disable CS0618 // Type or member is obsolete
case nameof(value.refreshRate):
value.refreshRate = reader.ReadAsInt32() ?? 0;
break;
#pragma warning restore CS0618 // Type or member is obsolete
#if UNITY_2022_2_OR_NEWER
case nameof(value.refreshRateRatio):
value.refreshRateRatio = reader.ReadViaSerializer<RefreshRate>(serializer);
break;
#endif
}
}
protected override void WriteJsonProperties(JsonWriter writer, Resolution value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.width));
writer.WriteValue(value.width);
writer.WritePropertyName(nameof(value.height));
writer.WriteValue(value.height);
#pragma warning disable CS0618 // Type or member is obsolete
writer.WritePropertyName(nameof(value.refreshRate));
#if UNITY_2022_2_OR_NEWER
if (double.IsNaN(value.refreshRateRatio.value))
{
writer.WriteValue(0);
}
else
{
writer.WriteValue(value.refreshRate);
}
#else
writer.WriteValue(value.refreshRate);
#endif
#pragma warning restore CS0618 // Type or member is obsolete
#if UNITY_2022_2_OR_NEWER
writer.WritePropertyName(nameof(value.refreshRateRatio));
serializer.Serialize(writer, value.refreshRateRatio);
#endif
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 70e05895d45a929479175438ea0ccf75
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: f5fb3bf05a311ec4a9cdbce753a0a301
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,47 @@
using System;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json.UnityConverters.Helpers;
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Hashing
{
public class Hash128Converter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Hash128) || objectType == typeof(Hash128?);
}
[return: MaybeNull]
public override object ReadJson(JsonReader reader, Type objectType, [AllowNull] object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return objectType == typeof(Hash128?)
? (Hash128?)null
: new Hash128();
}
if (reader.TokenType == JsonToken.String && reader.Value is string stringValue)
{
return Hash128.Parse(stringValue);
}
else
{
throw reader.CreateSerializationException($"Expected string when reading UnityEngine.Hash128 type, got '{reader.TokenType}' <{reader.Value}>.");
}
}
public override void WriteJson(JsonWriter writer, [AllowNull] object value, JsonSerializer serializer)
{
if (value is null)
{
writer.WriteNull();
}
else
{
writer.WriteValue(((Hash128)value).ToString());
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 77addc2936b2fb348a7f74fd1df32279
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ba4b6b37589b8af46b903f94d7645acd
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,31 @@
using System.Collections.Generic;
namespace Newtonsoft.Json.UnityConverters.Helpers
{
internal static class EnumerableExtensions
{
public static IEnumerable<T> WhereNotNullRef<T>(this IEnumerable<T> values)
where T : class
{
foreach (T item in values)
{
if (item != null)
{
yield return item;
}
}
}
public static IEnumerable<T> WhereNotNullValue<T>(this IEnumerable<T?> values)
where T : struct
{
foreach (T? item in values)
{
if (item.HasValue)
{
yield return item.Value;
}
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 57e9831fc3d74a4449704a100f5b9ded
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,117 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Text;
namespace Newtonsoft.Json.UnityConverters.Helpers
{
internal static class JsonHelperExtensions
{
/// <summary>
/// This refers to the ctor that lets you specify the line number and
/// position that was introduced in Json.NET v12.0.1.
/// <see cref="JsonSerializationException.JsonSerializationException(string, string, int, int, Exception)"/>
/// <see href="https://github.com/JamesNK/Newtonsoft.Json/blob/12.0.1/Src/Newtonsoft.Json/JsonSerializationException.cs#L110"/>
/// </summary>
internal static readonly ConstructorInfo _JsonSerializationExceptionPositionalCtor
= typeof(JsonSerializationException).GetConstructor(new[] {
typeof(string), typeof(string), typeof(int), typeof(int), typeof(Exception)
});
private static JsonSerializationException NewJsonSerializationException(string message, string path, int lineNumber, int linePosition, [AllowNull] Exception innerException)
{
if (_JsonSerializationExceptionPositionalCtor != null)
{
return (JsonSerializationException)_JsonSerializationExceptionPositionalCtor.Invoke(new object[] {
message, path, lineNumber, linePosition, innerException
});
}
else
{
return new JsonSerializationException(message, innerException);
}
}
public static JsonSerializationException CreateSerializationException(this JsonReader reader, string message, [AllowNull] Exception innerException = null)
{
StringBuilder builder = CreateStringBuilderWithSpaceAfter(message);
builder.AppendFormat(CultureInfo.InvariantCulture, "Path '{0}'", reader.Path);
var lineInfo = reader as IJsonLineInfo;
int lineNumber = default;
int linePosition = default;
if (lineInfo?.HasLineInfo() == true)
{
lineNumber = lineInfo.LineNumber;
linePosition = lineInfo.LinePosition;
builder.AppendFormat(CultureInfo.InvariantCulture, ", line {0}, position {1}", lineNumber, linePosition);
}
builder.Append('.');
return NewJsonSerializationException(
message: builder.ToString(), reader.Path, lineNumber, linePosition, innerException);
}
public static JsonWriterException CreateWriterException(this JsonWriter writer, string message, [AllowNull] Exception innerException = null)
{
StringBuilder builder = CreateStringBuilderWithSpaceAfter(message);
builder.AppendFormat(CultureInfo.InvariantCulture, "Path '{0}'.", writer.Path);
return new JsonWriterException(
message: builder.ToString(), writer.Path, innerException);
}
private static StringBuilder CreateStringBuilderWithSpaceAfter(string message)
{
var builder = new StringBuilder(message);
if (message.EndsWith("."))
{
builder.Append(' ');
}
else if (!message.EndsWith(". "))
{
builder.Append(". ");
}
return builder;
}
[return: MaybeNull]
public static T ReadViaSerializer<T>(this JsonReader reader, JsonSerializer serializer)
{
reader.Read();
return serializer.Deserialize<T>(reader);
}
public static float? ReadAsFloat(this JsonReader reader)
{
// https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters/issues/46
var str = reader.ReadAsString();
if (string.IsNullOrEmpty(str))
{
return null;
}
else if (float.TryParse(str, NumberStyles.Any, CultureInfo.InvariantCulture, out var valueParsed))
{
return valueParsed;
}
else
{
return 0f;
}
}
public static byte? ReadAsInt8(this JsonReader reader)
{
return checked((byte)(reader.ReadAsInt32() ?? 0));
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 14d81b4b9fea2f8459dfdf3a02459316
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,152 @@
#pragma warning disable MA0048 // File name must match type name
#define INTERNAL_NULLABLE_ATTRIBUTES
#if (NET_STANDARD_2_0 || NET_4_6 || NET_2_0 || NET_2_0_SUBSET || NET_LEGACY) && !NET_STANDARD_2_1
// https://github.com/dotnet/corefx/blob/48363ac826ccf66fbe31a5dcb1dc2aab9a7dd768/src/Common/src/CoreLib/System/Diagnostics/CodeAnalysis/NullableAttributes.cs
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Diagnostics.CodeAnalysis
{
/// <summary>Specifies that null is allowed as an input even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]
#if INTERNAL_NULLABLE_ATTRIBUTES
internal
#else
public
#endif
sealed class AllowNullAttribute : Attribute
{ }
/// <summary>Specifies that null is disallowed as an input even if the corresponding type allows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]
#if INTERNAL_NULLABLE_ATTRIBUTES
internal
#else
public
#endif
sealed class DisallowNullAttribute : Attribute
{ }
/// <summary>Specifies that an output may be null even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]
#if INTERNAL_NULLABLE_ATTRIBUTES
internal
#else
public
#endif
sealed class MaybeNullAttribute : Attribute
{ }
/// <summary>Specifies that an output will not be null even if the corresponding type allows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]
#if INTERNAL_NULLABLE_ATTRIBUTES
internal
#else
public
#endif
sealed class NotNullAttribute : Attribute
{ }
/// <summary>Specifies that when a method returns <see cref="ReturnValue"/>, the parameter may be null even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
#if INTERNAL_NULLABLE_ATTRIBUTES
internal
#else
public
#endif
sealed class MaybeNullWhenAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified return value condition.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter may be null.
/// </param>
public MaybeNullWhenAttribute(bool returnValue)
{
ReturnValue = returnValue;
}
/// <summary>Gets the return value condition.</summary>
public bool ReturnValue { get; }
}
/// <summary>Specifies that when a method returns <see cref="ReturnValue"/>, the parameter will not be null even if the corresponding type allows it.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
#if INTERNAL_NULLABLE_ATTRIBUTES
internal
#else
public
#endif
sealed class NotNullWhenAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified return value condition.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter will not be null.
/// </param>
public NotNullWhenAttribute(bool returnValue)
{
ReturnValue = returnValue;
}
/// <summary>Gets the return value condition.</summary>
public bool ReturnValue { get; }
}
/// <summary>Specifies that the output will be non-null if the named parameter is non-null.</summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
#if INTERNAL_NULLABLE_ATTRIBUTES
internal
#else
public
#endif
sealed class NotNullIfNotNullAttribute : Attribute
{
/// <summary>Initializes the attribute with the associated parameter name.</summary>
/// <param name="parameterName">
/// The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null.
/// </param>
public NotNullIfNotNullAttribute(string parameterName)
{
ParameterName = parameterName;
}
/// <summary>Gets the associated parameter name.</summary>
public string ParameterName { get; }
}
/// <summary>Applied to a method that will never return under any circumstance.</summary>
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
#if INTERNAL_NULLABLE_ATTRIBUTES
internal
#else
public
#endif
sealed class DoesNotReturnAttribute : Attribute
{ }
/// <summary>Specifies that the method will not return if the associated Boolean parameter is passed the specified value.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
#if INTERNAL_NULLABLE_ATTRIBUTES
internal
#else
public
#endif
sealed class DoesNotReturnIfAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified parameter value.</summary>
/// <param name="parameterValue">
/// The condition parameter value. Code after the method will be considered unreachable by diagnostics if the argument to
/// the associated parameter matches this value.
/// </param>
public DoesNotReturnIfAttribute(bool parameterValue)
{
ParameterValue = parameterValue;
}
/// <summary>Gets the condition parameter value.</summary>
public bool ParameterValue { get; }
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6d204313f888a2e4d9ce61192bb09b2c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Newtonsoft.Json.UnityConverters.Helpers
{
internal static class TypeExtensions
{
public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly)
{
try
{
return assembly.GetTypes();
}
catch (ReflectionTypeLoadException ex)
{
#if DEBUG
Console.WriteLine("Newtonsoft.Json.UnityConverters.Helpers.TypeExtensions: "
+ "Failed to load some types from assembly '{assembly.FullName}'. Maybe assembly is not fully loaded yet?\n"
+ ex.ToString());
#endif
return ex.Types.Where(t => t != null);
}
}
/// <summary>
/// Gets the non-public instance field info <see cref="FieldInfo"/> for the converted type
/// <typeparamref name="T"/>.
/// If not found then will throw a missing member exception <see cref="MissingMemberException"/>.
/// </summary>
/// <remarks>
/// If used in static initialization (ex: inside static constructor,
/// static field, or static property backing field initialization)
/// and the field does not exist it would invalidate the type for
/// the entirety of the programs lifetime.
/// </remarks>
/// <param name="name">Name of the non-public instance field.</param>
public static FieldInfo GetFieldInfoOrThrow(this Type type, string name)
{
return type.GetField(name, BindingFlags.NonPublic | BindingFlags.Instance)
?? throw new MissingMemberException(type.FullName, name);
}
public static void SetValueDirectRef<T1, T2>(this FieldInfo field, ref T1 state, T2 value)
{
#if ENABLE_IL2CPP
object boxed = state;
field.SetValue(boxed, value);
state = (T1)boxed;
#else
TypedReference reference = __makeref(state);
field.SetValueDirect(reference, value);
#endif
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d5943f790b4af094da5f0d24b12c1ad5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ccdb4f36c1c027244944b7bdbcca3e33
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,66 @@
#region License
// The MIT License (MIT)
//
// Copyright (c) 2020 Wanzyee Studio
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
using Newtonsoft.Json.UnityConverters.Helpers;
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Math
{
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity byte based Color type <see cref="Color32"/>.
/// </summary>
public class Color32Converter : PartialConverter<Color32>
{
protected override void ReadValue(ref Color32 value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.r):
value.r = reader.ReadAsInt8() ?? 0;
break;
case nameof(value.g):
value.g = reader.ReadAsInt8() ?? 0;
break;
case nameof(value.b):
value.b = reader.ReadAsInt8() ?? 0;
break;
case nameof(value.a):
value.a = reader.ReadAsInt8() ?? 0;
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, Color32 value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.r));
writer.WriteValue(value.r);
writer.WritePropertyName(nameof(value.g));
writer.WriteValue(value.g);
writer.WritePropertyName(nameof(value.b));
writer.WriteValue(value.b);
writer.WritePropertyName(nameof(value.a));
writer.WriteValue(value.a);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: bc4991667e8a84f4dba7eadfc16fd5a9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,66 @@
#region License
// The MIT License (MIT)
//
// Copyright (c) 2020 Wanzyee Studio
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
using Newtonsoft.Json.UnityConverters.Helpers;
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Math
{
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity Color type <see cref="Color"/>.
/// </summary>
public class ColorConverter : PartialConverter<Color>
{
protected override void ReadValue(ref Color value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.r):
value.r = reader.ReadAsFloat() ?? 0f;
break;
case nameof(value.g):
value.g = reader.ReadAsFloat() ?? 0f;
break;
case nameof(value.b):
value.b = reader.ReadAsFloat() ?? 0f;
break;
case nameof(value.a):
value.a = reader.ReadAsFloat() ?? 0f;
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, Color value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.r));
writer.WriteValue(value.r);
writer.WritePropertyName(nameof(value.g));
writer.WriteValue(value.g);
writer.WritePropertyName(nameof(value.b));
writer.WriteValue(value.b);
writer.WritePropertyName(nameof(value.a));
writer.WriteValue(value.a);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 21096ef1f0a311e44ae8cf99f1add03b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,79 @@
#region License
// The MIT License (MIT)
//
// Copyright (c) 2020 Wanzyee Studio
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.UnityConverters.Helpers;
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Math
{
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity Matrix4x4 type <see cref="Matrix4x4"/>.
/// </summary>
public class Matrix4x4Converter : PartialConverter<Matrix4x4>
{
// https://github.com/Unity-Technologies/UnityCsReference/blob/2019.2/Runtime/Export/Math/Matrix4x4.cs#L21-L29
private static readonly string[] _names = GetMemberNames();
private static readonly Dictionary<string, int> _namesToIndex = GetNamesToIndex(_names);
/// <summary>
/// Get the property names include from <c>m00</c> to <c>m33</c>.
/// </summary>
/// <returns>The property names.</returns>
private static string[] GetMemberNames()
{
string[] indexes = new[] { "0", "1", "2", "3" };
return indexes.SelectMany((row) => indexes.Select((column) => "m" + column + row)).ToArray();
}
// Reusing the same strings here instead of creating new ones. Tiny bit lower memory footprint
private static Dictionary<string, int> GetNamesToIndex(string[] names)
{
var dict = new Dictionary<string, int>();
for (int i = 0; i < names.Length; i++)
{
dict[names[i]] = i;
}
return dict;
}
protected override void ReadValue(ref Matrix4x4 value, string name, JsonReader reader, JsonSerializer serializer)
{
if (_namesToIndex.TryGetValue(name, out var index))
{
value[index] = reader.ReadAsFloat() ?? 0;
}
}
protected override void WriteJsonProperties(JsonWriter writer, Matrix4x4 value, JsonSerializer serializer)
{
for (int i = 0; i < _names.Length; i++)
{
writer.WritePropertyName(_names[i]);
writer.WriteValue(value[i]);
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d5145ef279cfb6f459ce307dfafd796a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,66 @@
#region License
// The MIT License (MIT)
//
// Copyright (c) 2020 Wanzyee Studio
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
using Newtonsoft.Json.UnityConverters.Helpers;
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Math
{
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity Quaternion type <see cref="Quaternion"/>.
/// </summary>
public class QuaternionConverter : PartialConverter<Quaternion>
{
protected override void ReadValue(ref Quaternion value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.x):
value.x = reader.ReadAsFloat() ?? 0f;
break;
case nameof(value.y):
value.y = reader.ReadAsFloat() ?? 0f;
break;
case nameof(value.z):
value.z = reader.ReadAsFloat() ?? 0f;
break;
case nameof(value.w):
value.w = reader.ReadAsFloat() ?? 0f;
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, Quaternion value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.x));
writer.WriteValue(value.x);
writer.WritePropertyName(nameof(value.y));
writer.WriteValue(value.y);
writer.WritePropertyName(nameof(value.z));
writer.WriteValue(value.z);
writer.WritePropertyName(nameof(value.w));
writer.WriteValue(value.w);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 915d1dc587bb37f49b42d57c1b4e2688
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,69 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json.UnityConverters.Helpers;
using UnityEngine.Rendering;
namespace Newtonsoft.Json.UnityConverters.Math
{
public class SphericalHarmonicsL2Converter : PartialConverter<SphericalHarmonicsL2>
{
// Magic numbers taken from /Runtime/Export/Math/SphericalHarmonicsL2.bindings.cs
// inside Unitys open source repo
// https://github.com/Unity-Technologies/UnityCsReference/blob/2019.2/Runtime/Export/Math/SphericalHarmonicsL2.bindings.cs#L59
private const int COEFFICIENT_COUNT = 9;
private const int ARRAY_SIZE = 3 * COEFFICIENT_COUNT;
private static readonly (string name, int rgb, int coefficient)[] _indices = GetMemberNames();
private static readonly Dictionary<string, (int color, int coefficient)> _nameToIndex = GetNamesToIndexDictionary(_indices);
private static (string name, int rgb, int coefficient)[] GetMemberNames()
{
var array = new (string name, int rgb, int coefficient)[ARRAY_SIZE];
for (int i = 0; i < COEFFICIENT_COUNT; i++)
{
array[i] = ('r' + i.ToString(), 0, i);
}
for (int i = 0; i < COEFFICIENT_COUNT; i++)
{
array[COEFFICIENT_COUNT + i] = ('g' + i.ToString(), 1, i);
}
for (int i = 0; i < COEFFICIENT_COUNT; i++)
{
array[COEFFICIENT_COUNT + COEFFICIENT_COUNT + i] = ('b' + i.ToString(), 2, i);
}
return array;
}
// Reusing the same strings here instead of creating new ones. Tiny bit lower memory footprint
private static Dictionary<string, (int color, int coefficient)> GetNamesToIndexDictionary((string name, int rgb, int coefficient)[] indices)
{
var dict = new Dictionary<string, (int color, int coefficient)>();
for (int i = 0; i < indices.Length; i++)
{
(string name, int rgb, int coefficient) = indices[i];
dict[name] = (rgb, coefficient);
}
return dict;
}
protected override void ReadValue(ref SphericalHarmonicsL2 value, string name, JsonReader reader, JsonSerializer serializer)
{
if (_nameToIndex.TryGetValue(name, out var index))
{
value[index.color, index.coefficient] = reader.ReadAsFloat() ?? 0f;
}
}
protected override void WriteJsonProperties(JsonWriter writer, SphericalHarmonicsL2 value, JsonSerializer serializer)
{
foreach (var (name, rgb, coefficient) in _indices)
{
writer.WritePropertyName(name);
writer.WriteValue(value[rgb, coefficient]);
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 168d3269f6c4db14d8755f2c26b6f767
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,56 @@
#region License
// The MIT License (MIT)
//
// Copyright (c) 2020 Wanzyee Studio
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
using Newtonsoft.Json.UnityConverters.Helpers;
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Math
{
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity Vector2 type <see cref="Vector2"/>.
/// </summary>
public class Vector2Converter : PartialConverter<Vector2>
{
protected override void ReadValue(ref Vector2 value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.x):
value.x = reader.ReadAsFloat() ?? 0f;
break;
case nameof(value.y):
value.y = reader.ReadAsFloat() ?? 0f;
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, Vector2 value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.x));
writer.WriteValue(value.x);
writer.WritePropertyName(nameof(value.y));
writer.WriteValue(value.y);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7aaf0269bdd21d44db597cae952fc7f2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,55 @@
#region License
// The MIT License (MIT)
//
// Copyright (c) 2020 Wanzyee Studio
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Math
{
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity integer Vector2 type <see cref="Vector2Int"/>.
/// </summary>
public class Vector2IntConverter : PartialConverter<Vector2Int>
{
protected override void ReadValue(ref Vector2Int value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.x):
value.x = reader.ReadAsInt32() ?? 0;
break;
case nameof(value.y):
value.y = reader.ReadAsInt32() ?? 0;
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, Vector2Int value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.x));
writer.WriteValue(value.x);
writer.WritePropertyName(nameof(value.y));
writer.WriteValue(value.y);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 160fce3550ff5d14ca68d1ca3127a074
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,61 @@
#region License
// The MIT License (MIT)
//
// Copyright (c) 2020 Wanzyee Studio
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
using Newtonsoft.Json.UnityConverters.Helpers;
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Math
{
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity Vector3 type <see cref="Vector3"/>.
/// </summary>
public class Vector3Converter : PartialConverter<Vector3>
{
protected override void ReadValue(ref Vector3 value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.x):
value.x = reader.ReadAsFloat() ?? 0f;
break;
case nameof(value.y):
value.y = reader.ReadAsFloat() ?? 0f;
break;
case nameof(value.z):
value.z = reader.ReadAsFloat() ?? 0f;
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, Vector3 value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.x));
writer.WriteValue(value.x);
writer.WritePropertyName(nameof(value.y));
writer.WriteValue(value.y);
writer.WritePropertyName(nameof(value.z));
writer.WriteValue(value.z);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 46a66d20df7340e459c3cd51e3a8b981
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,60 @@
#region License
// The MIT License (MIT)
//
// Copyright (c) 2020 Wanzyee Studio
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Math
{
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity integer Vector3 type <see cref="Vector3Int"/>.
/// </summary>
public class Vector3IntConverter : PartialConverter<Vector3Int>
{
protected override void ReadValue(ref Vector3Int value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.x):
value.x = reader.ReadAsInt32() ?? 0;
break;
case nameof(value.y):
value.y = reader.ReadAsInt32() ?? 0;
break;
case nameof(value.z):
value.z = reader.ReadAsInt32() ?? 0;
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, Vector3Int value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.x));
writer.WriteValue(value.x);
writer.WritePropertyName(nameof(value.y));
writer.WriteValue(value.y);
writer.WritePropertyName(nameof(value.z));
writer.WriteValue(value.z);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3aa261b7b6ba3684ca1259adb20d54c8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,66 @@
#region License
// The MIT License (MIT)
//
// Copyright (c) 2020 Wanzyee Studio
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
using Newtonsoft.Json.UnityConverters.Helpers;
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Math
{
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity Vector4 type <see cref="Vector4"/>.
/// </summary>
public class Vector4Converter : PartialConverter<Vector4>
{
protected override void ReadValue(ref Vector4 value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.x):
value.x = reader.ReadAsFloat() ?? 0f;
break;
case nameof(value.y):
value.y = reader.ReadAsFloat() ?? 0f;
break;
case nameof(value.z):
value.z = reader.ReadAsFloat() ?? 0f;
break;
case nameof(value.w):
value.w = reader.ReadAsFloat() ?? 0f;
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, Vector4 value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.x));
writer.WriteValue(value.x);
writer.WritePropertyName(nameof(value.y));
writer.WriteValue(value.y);
writer.WritePropertyName(nameof(value.z));
writer.WriteValue(value.z);
writer.WritePropertyName(nameof(value.w));
writer.WriteValue(value.w);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: de357adfe7b8e214986a440c88a576c9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 04f581c01bcb1174a9340241e0a686a7
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,100 @@
using Unity.Mathematics;
namespace Newtonsoft.Json.UnityConverters.Mathematics
{
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity.Mathematics <see cref="bool2"/> type.
/// </summary>
public class Bool2Converter : PartialConverter<bool2>
{
protected override void ReadValue(ref bool2 value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.x):
value.x = reader.ReadAsBoolean() ?? false;
break;
case nameof(value.y):
value.y = reader.ReadAsBoolean() ?? false;
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, bool2 value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.x));
writer.WriteValue(value.x);
writer.WritePropertyName(nameof(value.y));
writer.WriteValue(value.y);
}
}
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity.Mathematics <see cref="bool3"/> type.
/// </summary>
public class Bool3Converter : PartialConverter<bool3>
{
protected override void ReadValue(ref bool3 value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.x):
value.x = reader.ReadAsBoolean() ?? false;
break;
case nameof(value.y):
value.y = reader.ReadAsBoolean() ?? false;
break;
case nameof(value.z):
value.z = reader.ReadAsBoolean() ?? false;
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, bool3 value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.x));
writer.WriteValue(value.x);
writer.WritePropertyName(nameof(value.y));
writer.WriteValue(value.y);
writer.WritePropertyName(nameof(value.z));
writer.WriteValue(value.z);
}
}
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity.Mathematics <see cref="bool4"/> type.
/// </summary>
public class Bool4Converter : PartialConverter<bool4>
{
protected override void ReadValue(ref bool4 value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.x):
value.x = reader.ReadAsBoolean() ?? false;
break;
case nameof(value.y):
value.y = reader.ReadAsBoolean() ?? false;
break;
case nameof(value.z):
value.z = reader.ReadAsBoolean() ?? false;
break;
case nameof(value.w):
value.w = reader.ReadAsBoolean() ?? false;
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, bool4 value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.x));
writer.WriteValue(value.x);
writer.WritePropertyName(nameof(value.y));
writer.WriteValue(value.y);
writer.WritePropertyName(nameof(value.z));
writer.WriteValue(value.z);
writer.WritePropertyName(nameof(value.w));
writer.WriteValue(value.w);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b7192e0262f9ca74e8e40f149a39f587
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,101 @@
using Newtonsoft.Json.UnityConverters.Helpers;
using Unity.Mathematics;
namespace Newtonsoft.Json.UnityConverters.Mathematics
{
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity.Mathematics <see cref="double2"/> type.
/// </summary>
public class Double2Converter : PartialConverter<double2>
{
protected override void ReadValue(ref double2 value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.x):
value.x = reader.ReadAsDouble() ?? 0f;
break;
case nameof(value.y):
value.y = reader.ReadAsDouble() ?? 0f;
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, double2 value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.x));
writer.WriteValue(value.x);
writer.WritePropertyName(nameof(value.y));
writer.WriteValue(value.y);
}
}
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity.Mathematics <see cref="double3"/> type.
/// </summary>
public class Double3Converter : PartialConverter<double3>
{
protected override void ReadValue(ref double3 value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.x):
value.x = reader.ReadAsDouble() ?? 0f;
break;
case nameof(value.y):
value.y = reader.ReadAsDouble() ?? 0f;
break;
case nameof(value.z):
value.z = reader.ReadAsDouble() ?? 0f;
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, double3 value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.x));
writer.WriteValue(value.x);
writer.WritePropertyName(nameof(value.y));
writer.WriteValue(value.y);
writer.WritePropertyName(nameof(value.z));
writer.WriteValue(value.z);
}
}
/// <summary>
/// Custom Newtonsoft.Json converter <see cref="JsonConverter"/> for the Unity.Mathematics <see cref="double4"/> type.
/// </summary>
public class Double4Converter : PartialConverter<double4>
{
protected override void ReadValue(ref double4 value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name)
{
case nameof(value.x):
value.x = reader.ReadAsDouble() ?? 0f;
break;
case nameof(value.y):
value.y = reader.ReadAsDouble() ?? 0f;
break;
case nameof(value.z):
value.z = reader.ReadAsDouble() ?? 0f;
break;
case nameof(value.w):
value.w = reader.ReadAsDouble() ?? 0f;
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, double4 value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.x));
writer.WriteValue(value.x);
writer.WritePropertyName(nameof(value.y));
writer.WriteValue(value.y);
writer.WritePropertyName(nameof(value.z));
writer.WriteValue(value.z);
writer.WritePropertyName(nameof(value.w));
writer.WriteValue(value.w);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3cb272eb5ac884d45bc34c327bc74149
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