text
stringlengths
7
35.3M
id
stringlengths
11
185
metadata
dict
__index_level_0__
int64
0
2.14k
fileFormatVersion: 2 guid: 5999bd61b5ca4e5ba50b20b2e3a7f9b2 timeCreated: 1507865451
ET/Unity/Assets/Scripts/Editor/Helper.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/Helper.meta", "repo_id": "ET", "token_count": 44 }
113
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace ET { }
ET/Unity/Assets/Scripts/Editor/Plugins/Example/ExampleEditor.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/Plugins/Example/ExampleEditor.cs", "repo_id": "ET", "token_count": 30 }
114
fileFormatVersion: 2 guid: c38213e2fca6b8b489ffb3fee170c51f folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Client/Demo/Main/Login.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Demo/Main/Login.meta", "repo_id": "ET", "token_count": 70 }
115
fileFormatVersion: 2 guid: 0f70391ff9eb499db68bae992a9c85b6 timeCreated: 1688540041
ET/Unity/Assets/Scripts/Hotfix/Client/Demo/NetClient/A2NetClient_MessageHandler.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Demo/NetClient/A2NetClient_MessageHandler.cs.meta", "repo_id": "ET", "token_count": 37 }
116
fileFormatVersion: 2 guid: 567a551c7abf2fd4c9b592af991b609e MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Client/Demo/NetClient/Router/RouterAddressComponentSystem.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Demo/NetClient/Router/RouterAddressComponentSystem.cs.meta", "repo_id": "ET", "token_count": 96 }
117
using System; namespace ET.Client { [EntitySystemOf(typeof(LSReplayUpdater))] [FriendOf(typeof(LSReplayUpdater))] public static partial class LSReplayUpdaterSystem { [EntitySystem] private static void Awake(this LSReplayUpdater self) { } [EntitySystem] private static void Update(this LSReplayUpdater self) { Room room = self.GetParent<Room>(); Fiber fiber = self.Fiber(); long timeNow = TimeInfo.Instance.ServerNow(); int i = 0; while (true) { if (room.AuthorityFrame + 1 >= room.Replay.FrameInputs.Count) { break; } if (timeNow < room.FixedTimeCounter.FrameTime(room.AuthorityFrame + 1)) { break; } ++room.AuthorityFrame; OneFrameInputs oneFrameInputs = room.Replay.FrameInputs[room.AuthorityFrame]; room.Update(oneFrameInputs); room.SpeedMultiply = ++i; long timeNow2 = TimeInfo.Instance.ServerNow(); if (timeNow2 - timeNow > 5) { break; } } } public static void ChangeReplaySpeed(this LSReplayUpdater self) { Room room = self.Room(); LSReplayUpdater lsReplayUpdater = room.GetComponent<LSReplayUpdater>(); if (lsReplayUpdater.ReplaySpeed == 8) { lsReplayUpdater.ReplaySpeed = 1; } else { lsReplayUpdater.ReplaySpeed *= 2; } int updateInterval = LSConstValue.UpdateInterval / lsReplayUpdater.ReplaySpeed; room.FixedTimeCounter.ChangeInterval(updateInterval, room.AuthorityFrame); } } }
ET/Unity/Assets/Scripts/Hotfix/Client/LockStep/LSReplayUpdaterSystem.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/LockStep/LSReplayUpdaterSystem.cs", "repo_id": "ET", "token_count": 1050 }
118
using System; namespace ET.Client { [Invoke((long)SceneType.NetClient)] public class NetComponentOnReadInvoker_NetClient: AInvokeHandler<NetComponentOnRead> { public override void Handle(NetComponentOnRead args) { Session session = args.Session; object message = args.Message; Fiber fiber = session.Fiber(); // 根据消息接口判断是不是Actor消息,不同的接口做不同的处理,比如需要转发给Chat Scene,可以做一个IChatMessage接口 switch (message) { case IResponse response: { session.OnResponse(response); break; } case ISessionMessage: { MessageSessionDispatcher.Instance.Handle(session, message); break; } case IMessage iActorMessage: { // 扔到Main纤程队列中 int parentFiberId = fiber.Root.GetComponent<FiberParentComponent>().ParentFiberId; fiber.Root.GetComponent<ProcessInnerSender>().Send(new ActorId(fiber.Process, parentFiberId), iActorMessage); break; } default: { throw new Exception($"not found handler: {message}"); } } } } }
ET/Unity/Assets/Scripts/Hotfix/Client/Module/Message/NetComponentOnReadInvoker_NetClient.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Module/Message/NetComponentOnReadInvoker_NetClient.cs", "repo_id": "ET", "token_count": 831 }
119
using System.Net; using System.Net.Sockets; using ET.Client; namespace ET.Server { [Invoke((long)SceneType.BenchmarkServer)] public class FiberInit_BenchmarkServer: AInvokeHandler<FiberInit, ETTask> { public override async ETTask Handle(FiberInit fiberInit) { Scene root = fiberInit.Fiber.Root; //root.AddComponent<MailBoxComponent, MailBoxType>(MailBoxType.UnOrderedMessage); //root.AddComponent<TimerComponent>(); //root.AddComponent<CoroutineLockComponent>(); //root.AddComponent<ActorInnerComponent>(); //root.AddComponent<PlayerComponent>(); //root.AddComponent<GateSessionKeyComponent>(); //root.AddComponent<LocationProxyComponent>(); //root.AddComponent<ActorLocationSenderComponent>(); root.AddComponent<NetComponent, IPEndPoint, NetworkProtocol>(StartSceneConfigCategory.Instance.Benchmark.OuterIPPort, NetworkProtocol.UDP); root.AddComponent<BenchmarkServerComponent>(); await ETTask.CompletedTask; } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Benchmark/FiberInit_BenchmarkServer.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Benchmark/FiberInit_BenchmarkServer.cs", "repo_id": "ET", "token_count": 439 }
120
fileFormatVersion: 2 guid: 8679dc7d3ea6fe4478111d3d3948d6cc MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Gate/C2G_PingHandler.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Gate/C2G_PingHandler.cs.meta", "repo_id": "ET", "token_count": 95 }
121
 namespace ET.Server { [MessageLocationHandler(SceneType.Map)] public class C2M_PathfindingResultHandler : MessageLocationHandler<Unit, C2M_PathfindingResult> { protected override async ETTask Run(Unit unit, C2M_PathfindingResult message) { unit.FindPathMoveToAsync(message.Position).Coroutine(); await ETTask.CompletedTask; } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Map/Move/C2M_PathfindingResultHandler.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Map/Move/C2M_PathfindingResultHandler.cs", "repo_id": "ET", "token_count": 119 }
122
using System; using Unity.Mathematics; namespace ET.Server { public static partial class UnitFactory { public static Unit Create(Scene scene, long id, UnitType unitType) { UnitComponent unitComponent = scene.GetComponent<UnitComponent>(); switch (unitType) { case UnitType.Player: { Unit unit = unitComponent.AddChildWithId<Unit, int>(id, 1001); unit.AddComponent<MoveComponent>(); unit.Position = new float3(-10, 0, -10); NumericComponent numericComponent = unit.AddComponent<NumericComponent>(); numericComponent.Set(NumericType.Speed, 6f); // 速度是6米每秒 numericComponent.Set(NumericType.AOI, 15000); // 视野15米 unitComponent.Add(unit); // 加入aoi unit.AddComponent<AOIEntity, int, float3>(9 * 1000, unit.Position); return unit; } default: throw new Exception($"not such unit type: {unitType}"); } } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Map/Unit/UnitFactory.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Map/Unit/UnitFactory.cs", "repo_id": "ET", "token_count": 649 }
123
fileFormatVersion: 2 guid: 09a50e10da1069b4ca4863e50eb997fa folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Robot/Case.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Robot/Case.meta", "repo_id": "ET", "token_count": 68 }
124
fileFormatVersion: 2 guid: 74b099ff0f3523d47af0595ae8bf6b3f MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Watcher/WatcherComponentSystem.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Watcher/WatcherComponentSystem.cs.meta", "repo_id": "ET", "token_count": 96 }
125
using System; using System.Collections.Generic; namespace ET.Server { [MessageHandler(SceneType.Map)] public class Match2Map_GetRoomHandler : MessageHandler<Scene, Match2Map_GetRoom, Map2Match_GetRoom> { protected override async ETTask Run(Scene root, Match2Map_GetRoom request, Map2Match_GetRoom response) { //RoomManagerComponent roomManagerComponent = root.GetComponent<RoomManagerComponent>(); Fiber fiber = root.Fiber(); int fiberId = await FiberManager.Instance.Create(SchedulerType.ThreadPool, fiber.Zone, SceneType.RoomRoot, "RoomRoot"); ActorId roomRootActorId = new(fiber.Process, fiberId); // 发送消息给房间纤程,初始化 RoomManager2Room_Init roomManager2RoomInit = RoomManager2Room_Init.Create(); roomManager2RoomInit.PlayerIds.AddRange(request.PlayerIds); await root.GetComponent<MessageSender>().Call(roomRootActorId, roomManager2RoomInit); response.ActorId = roomRootActorId; await ETTask.CompletedTask; } } }
ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Map/Match2Map_GetRoomHandler.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Map/Match2Map_GetRoomHandler.cs", "repo_id": "ET", "token_count": 354 }
126
using System.Net; namespace ET.Server { [Invoke((long)SceneType.RoomRoot)] public class FiberInit_RoomRoot: AInvokeHandler<FiberInit, ETTask> { public override async ETTask Handle(FiberInit fiberInit) { Scene root = fiberInit.Fiber.Root; root.AddComponent<MailBoxComponent, MailBoxType>(MailBoxType.UnOrderedMessage); root.AddComponent<TimerComponent>(); root.AddComponent<CoroutineLockComponent>(); root.AddComponent<ProcessInnerSender>(); root.AddComponent<MessageSender>(); root.AddComponent<LocationProxyComponent>(); root.AddComponent<MessageLocationSenderComponent>(); await ETTask.CompletedTask; } } }
ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Room/FiberInit_RoomRoot.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Room/FiberInit_RoomRoot.cs", "repo_id": "ET", "token_count": 320 }
127
namespace ET.Server { public static partial class AOISeeCheckHelper { public static bool IsCanSee(AOIEntity a, AOIEntity b) { return true; } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Module/AOI/AOISeeCheckHelper.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Module/AOI/AOISeeCheckHelper.cs", "repo_id": "ET", "token_count": 98 }
128
fileFormatVersion: 2 guid: abf07b8e1c20b444fa7a5721d302d082 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/Module/ActorLocation/MessageLocationSenderSystem.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Module/ActorLocation/MessageLocationSenderSystem.cs.meta", "repo_id": "ET", "token_count": 96 }
129
fileFormatVersion: 2 guid: cd3c768fde72d464094ec6d867788cf7 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/Module/Http.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Module/Http.meta", "repo_id": "ET", "token_count": 69 }
130
namespace ET.Server { // 这里为什么能定义class呢?因为这里只有逻辑,热重载后新的handler替换旧的,仍然没有问题 public abstract class ARobotCase: AInvokeHandler<RobotInvokeArgs, ETTask> { protected abstract ETTask Run(RobotCase robotCase); public override async ETTask Handle(RobotInvokeArgs a) { using RobotCase robotCase = await a.Fiber.Root.GetComponent<RobotCaseComponent>().New(); try { await this.Run(robotCase); } catch (System.Exception e) { Log.Error($"{robotCase.Zone()} {e}"); Log.Console($"RobotCase Error {this.GetType().FullName}:\n\t{e}"); } } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Module/RobotCase/ARobotCase.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Module/RobotCase/ARobotCase.cs", "repo_id": "ET", "token_count": 413 }
131
fileFormatVersion: 2 guid: b4c6cd5890235a44586579650c6b4b20 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/Plugins/Example/HotfixServer.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Plugins/Example/HotfixServer.cs.meta", "repo_id": "ET", "token_count": 95 }
132
fileFormatVersion: 2 guid: 524c1cf3137abd64499ebf1a42a7f879 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Share/Module.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Share/Module.meta", "repo_id": "ET", "token_count": 71 }
133
namespace ET { [ConsoleHandler(ConsoleMode.ReloadDll)] public class ReloadDllConsoleHandler: IConsoleHandler { public async ETTask Run(Fiber fiber, ModeContex contex, string content) { await ETTask.CompletedTask; CodeLoader.Instance.Reload(); } } }
ET/Unity/Assets/Scripts/Hotfix/Share/Module/Console/ReloadDllConsoleHandler.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Share/Module/Console/ReloadDllConsoleHandler.cs", "repo_id": "ET", "token_count": 132 }
134
fileFormatVersion: 2 guid: e1215d410dbbdb144be73a6410148c59 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Share/Module/Numeric/NumericWatcher_Hp_ShowUI.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Share/Module/Numeric/NumericWatcher_Hp_ShowUI.cs.meta", "repo_id": "ET", "token_count": 92 }
135
{ "name": "Unity.Hotfix", "rootNamespace": "ET", "references": [ "Unity.ThirdParty", "Unity.Core", "Unity.Mathematics", "Unity.Loader", "MemoryPack", "Unity.Model" ], "includePlatforms": [], "excludePlatforms": [], "allowUnsafeCode": true, "overrideReferences": false, "precompiledReferences": [], "autoReferenced": true, "defineConstraints": [ "UNITY_COMPILE || UNITY_EDITOR" ], "versionDefines": [], "noEngineReferences": true }
ET/Unity/Assets/Scripts/Hotfix/Unity.Hotfix.asmdef/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Unity.Hotfix.asmdef", "repo_id": "ET", "token_count": 251 }
136
fileFormatVersion: 2 guid: a18b8a4c75ae1184c8e0ec3bfbbb6f3c folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/HotfixView/Client/Demo/UI/UILogin.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/Demo/UI/UILogin.meta", "repo_id": "ET", "token_count": 74 }
137
using UnityEngine; namespace ET.Client { [Event(SceneType.Current)] public class ChangeRotation_SyncGameObjectRotation: AEvent<Scene, ChangeRotation> { protected override async ETTask Run(Scene scene, ChangeRotation args) { Unit unit = args.Unit; GameObjectComponent gameObjectComponent = unit.GetComponent<GameObjectComponent>(); if (gameObjectComponent == null) { return; } Transform transform = gameObjectComponent.GameObject.transform; transform.rotation = unit.Rotation; await ETTask.CompletedTask; } } }
ET/Unity/Assets/Scripts/HotfixView/Client/Demo/Unit/ChangeRotation_SyncGameObjectRotation.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/Demo/Unit/ChangeRotation_SyncGameObjectRotation.cs", "repo_id": "ET", "token_count": 281 }
138
using UnityEngine; namespace ET.Client { [EntitySystemOf(typeof(LSUnitViewComponent))] public static partial class LSUnitViewComponentSystem { [EntitySystem] private static void Awake(this LSUnitViewComponent self) { } [EntitySystem] private static void Destroy(this LSUnitViewComponent self) { } public static async ETTask InitAsync(this LSUnitViewComponent self) { Room room = self.Room(); LSUnitComponent lsUnitComponent = room.LSWorld.GetComponent<LSUnitComponent>(); Scene root = self.Root(); foreach (long playerId in room.PlayerIds) { LSUnit lsUnit = lsUnitComponent.GetChild<LSUnit>(playerId); string assetsName = $"Assets/Bundles/Unit/Unit.prefab"; GameObject bundleGameObject = await room.GetComponent<ResourcesLoaderComponent>().LoadAssetAsync<GameObject>(assetsName); GameObject prefab = bundleGameObject.Get<GameObject>("Skeleton"); GlobalComponent globalComponent = root.GetComponent<GlobalComponent>(); GameObject unitGo = UnityEngine.Object.Instantiate(prefab, globalComponent.Unit, true); unitGo.transform.position = lsUnit.Position.ToVector(); LSUnitView lsUnitView = self.AddChildWithId<LSUnitView, GameObject>(lsUnit.Id, unitGo); lsUnitView.AddComponent<LSAnimatorComponent>(); } } } }
ET/Unity/Assets/Scripts/HotfixView/Client/LockStep/LSUnitViewComponentSystem.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/LockStep/LSUnitViewComponentSystem.cs", "repo_id": "ET", "token_count": 652 }
139
namespace ET.Client { [Event(SceneType.LockStep)] public class AppStartInitFinish_CreateUILSLogin: AEvent<Scene, AppStartInitFinish> { protected override async ETTask Run(Scene root, AppStartInitFinish args) { await UIHelper.Create(root, UIType.UILSLogin, UILayer.Mid); } } }
ET/Unity/Assets/Scripts/HotfixView/Client/LockStep/UI/UILSLogin/AppStartInitFinish_CreateUILSLogin.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/LockStep/UI/UILSLogin/AppStartInitFinish_CreateUILSLogin.cs", "repo_id": "ET", "token_count": 112 }
140
fileFormatVersion: 2 guid: 881672317f491394d973cb9950d5c146 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/HotfixView/Client/Module/Resource/GameObjectHelper.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/Module/Resource/GameObjectHelper.cs.meta", "repo_id": "ET", "token_count": 93 }
141
fileFormatVersion: 2 guid: 7d8c8789b4b09c048a09d38c44ad1d1f AssemblyDefinitionImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/HotfixView/Unity.HotfixView.asmdef.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Unity.HotfixView.asmdef.meta", "repo_id": "ET", "token_count": 69 }
142
fileFormatVersion: 2 guid: f3622259112f64aaeb03ea4c8e36cb92 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Loader/Plugins.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Loader/Plugins.meta", "repo_id": "ET", "token_count": 69 }
143
using System; using System.Collections.Generic; using UnityEngine; namespace ET { /// <summary> /// 内置资源清单 /// </summary> public class BuildinFileManifest : ScriptableObject { [Serializable] public class Element { public string PackageName; public string FileName; public string FileCRC32; } public List<Element> BuildinFiles = new(); } }
ET/Unity/Assets/Scripts/Loader/Resource/StreamingAssetsHelper/BuildinFileManifest.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Loader/Resource/StreamingAssetsHelper/BuildinFileManifest.cs", "repo_id": "ET", "token_count": 202 }
144
fileFormatVersion: 2 guid: c247787106f44a8f99a58bd0037a2c5e timeCreated: 1688537682
ET/Unity/Assets/Scripts/Model/Client/Demo/Main.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Client/Demo/Main.meta", "repo_id": "ET", "token_count": 38 }
145
fileFormatVersion: 2 guid: e50ffa067a184f40894c598dea0d7020 timeCreated: 1688538532
ET/Unity/Assets/Scripts/Model/Client/Demo/NetClient/A2NetClient_Message.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Client/Demo/NetClient/A2NetClient_Message.cs.meta", "repo_id": "ET", "token_count": 37 }
146
fileFormatVersion: 2 guid: 02de10d07ce524cb9bc79e666f460484 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Client/LockStep/EventType.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Client/LockStep/EventType.cs.meta", "repo_id": "ET", "token_count": 91 }
147
fileFormatVersion: 2 guid: 67d21a80f9f5d4a45823f7d0d16eb933 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Generate/Client.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Generate/Client.meta", "repo_id": "ET", "token_count": 73 }
148
fileFormatVersion: 2 guid: 027f4382299e1a7499130098fd865aa1 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Generate/ClientServer/Config.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Generate/ClientServer/Config.meta", "repo_id": "ET", "token_count": 69 }
149
fileFormatVersion: 2 guid: c68c60b0718e272488136d3e3e0672ec MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Server/Benchmark/BenchmarkClientComponent.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/Benchmark/BenchmarkClientComponent.cs.meta", "repo_id": "ET", "token_count": 95 }
150
namespace ET.Server { [ComponentOf(typeof(Session))] public class SessionPlayerComponent : Entity, IAwake, IDestroy { private EntityRef<Player> player; public Player Player { get { return this.player; } set { this.player = value; } } } }
ET/Unity/Assets/Scripts/Model/Server/Demo/Gate/SessionPlayerComponent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/Demo/Gate/SessionPlayerComponent.cs", "repo_id": "ET", "token_count": 123 }
151
using System.Collections.Generic; using System.Diagnostics; namespace ET.Server { [ComponentOf(typeof(Scene))] public class WatcherComponent: Entity, IAwake { public readonly Dictionary<int, System.Diagnostics.Process> Processes = new Dictionary<int, System.Diagnostics.Process>(); } }
ET/Unity/Assets/Scripts/Model/Server/Demo/Watcher/WatcherComponent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/Demo/Watcher/WatcherComponent.cs", "repo_id": "ET", "token_count": 106 }
152
fileFormatVersion: 2 guid: 78ca54cc32ca42a9861cd379ff3fc3e8 timeCreated: 1681817948
ET/Unity/Assets/Scripts/Model/Server/LockStep/Room.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/LockStep/Room.meta", "repo_id": "ET", "token_count": 35 }
153
using System; namespace ET.Server { [ComponentOf(typeof(Scene))] public class LocationProxyComponent: Entity, IAwake { } }
ET/Unity/Assets/Scripts/Model/Server/Module/ActorLocation/LocationProxyComponent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/Module/ActorLocation/LocationProxyComponent.cs", "repo_id": "ET", "token_count": 56 }
154
using System; using System.Collections.Generic; namespace ET.Server { [Code] public class HttpDispatcher: Singleton<HttpDispatcher>, ISingletonAwake { private readonly Dictionary<string, Dictionary<int, IHttpHandler>> dispatcher = new(); public void Awake() { HashSet<Type> types = CodeTypes.Instance.GetTypes(typeof (HttpHandlerAttribute)); foreach (Type type in types) { object[] attrs = type.GetCustomAttributes(typeof(HttpHandlerAttribute), false); if (attrs.Length == 0) { continue; } HttpHandlerAttribute httpHandlerAttribute = (HttpHandlerAttribute)attrs[0]; object obj = Activator.CreateInstance(type); IHttpHandler ihttpHandler = obj as IHttpHandler; if (ihttpHandler == null) { throw new Exception($"HttpHandler handler not inherit IHttpHandler class: {obj.GetType().FullName}"); } if (!this.dispatcher.TryGetValue(httpHandlerAttribute.Path, out var dict)) { dict = new Dictionary<int, IHttpHandler>(); this.dispatcher.Add(httpHandlerAttribute.Path, dict); } dict.Add((int)httpHandlerAttribute.SceneType, ihttpHandler); } } public IHttpHandler Get(SceneType sceneType, string path) { return this.dispatcher[path][(int)sceneType]; } } }
ET/Unity/Assets/Scripts/Model/Server/Module/Http/HttpDispatcher.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/Module/Http/HttpDispatcher.cs", "repo_id": "ET", "token_count": 799 }
155
fileFormatVersion: 2 guid: e9f8ce7fbba8b27458372ab3ff3c0e7f MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Server/Module/RobotCase/RobotCase.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/Module/RobotCase/RobotCase.cs.meta", "repo_id": "ET", "token_count": 97 }
156
fileFormatVersion: 2 guid: c62694a15545f4b599f146f8a44e417c MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Share/LockStep/LSUnit.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/LockStep/LSUnit.cs.meta", "repo_id": "ET", "token_count": 94 }
157
namespace ET { [EntitySystemOf(typeof(ModeContex))] [FriendOf(typeof(ModeContex))] public static partial class ModeContexSystem { [EntitySystem] private static void Awake(this ModeContex self) { self.Mode = ""; } [EntitySystem] private static void Destroy(this ModeContex self) { self.Mode = ""; } } [ComponentOf(typeof(ConsoleComponent))] public class ModeContex: Entity, IAwake, IDestroy { public string Mode = ""; } }
ET/Unity/Assets/Scripts/Model/Share/Module/Console/ModeContex.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/Console/ModeContex.cs", "repo_id": "ET", "token_count": 273 }
158
fileFormatVersion: 2 guid: 695ce9e84f2f8e14fa080f2624e5ee15 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Share/Module/Message/MessageSessionHandlerAttribute.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/Message/MessageSessionHandlerAttribute.cs.meta", "repo_id": "ET", "token_count": 96 }
159
fileFormatVersion: 2 guid: d25ba9800f0a922459d8287d76d224d7 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Share/Module/Numeric/INumericWatcher.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/Numeric/INumericWatcher.cs.meta", "repo_id": "ET", "token_count": 95 }
160
namespace ET { // 可以用来管理多个客户端场景,比如大世界会加载多块场景 [ComponentOf(typeof(Scene))] public class CurrentScenesComponent: Entity, IAwake { private EntityRef<Scene> scene; public Scene Scene { get { return this.scene; } set { this.scene = value; } } } }
ET/Unity/Assets/Scripts/Model/Share/Module/Scene/CurrentScenesComponent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/Scene/CurrentScenesComponent.cs", "repo_id": "ET", "token_count": 280 }
161
fileFormatVersion: 2 guid: d17793ff0cb5ec241826760444df27b3 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Share/Plugins/Example.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/Plugins/Example.meta", "repo_id": "ET", "token_count": 67 }
162
fileFormatVersion: 2 guid: a3fce04321ac7b049aa1eb95d9d8cfe6 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ModelView/Client/Demo/UI/UIHelp/UIHelpComponent.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ModelView/Client/Demo/UI/UIHelp/UIHelpComponent.cs.meta", "repo_id": "ET", "token_count": 97 }
163
fileFormatVersion: 2 guid: 4f4cf34e5e5ca4f779ba585cb3b0441d MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ModelView/Client/LockStep/UI/UILSLobby/UILSLobbyComponent.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ModelView/Client/LockStep/UI/UILSLobby/UILSLobbyComponent.cs.meta", "repo_id": "ET", "token_count": 96 }
164
using UnityEngine; namespace ET.Client { public static class LayerNames { /// <summary> /// UI层 /// </summary> public const string UI = "UI"; /// <summary> /// 游戏单位层 /// </summary> public const string UNIT = "Unit"; /// <summary> /// 地形层 /// </summary> public const string MAP = "Map"; /// <summary> /// 默认层 /// </summary> public const string DEFAULT = "Default"; public const string HIDDEN = "Hidden"; /// <summary> /// 通过Layers名字得到对应层 /// </summary> /// <param name="name"></param> /// <returns></returns> public static int GetLayerInt(string name) { return LayerMask.NameToLayer(name); } public static string GetLayerStr(int name) { return LayerMask.LayerToName(name); } } }
ET/Unity/Assets/Scripts/ModelView/Client/Module/UI/LayerNames.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ModelView/Client/Module/UI/LayerNames.cs", "repo_id": "ET", "token_count": 331 }
165
namespace DotRecast.Core { public interface IRcRand { float Next(); } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/IRcRand.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/IRcRand.cs", "repo_id": "ET", "token_count": 44 }
166
using System.Threading; namespace DotRecast.Core { public class RcAtomicLong { private long _location; public RcAtomicLong() : this(0) { } public RcAtomicLong(long location) { _location = location; } public long IncrementAndGet() { return Interlocked.Increment(ref _location); } public long DecrementAndGet() { return Interlocked.Decrement(ref _location); } public long Read() { return Interlocked.Read(ref _location); } public long Exchange(long exchange) { return Interlocked.Exchange(ref _location, exchange); } public long Decrease(long value) { return Interlocked.Add(ref _location, -value); } public long CompareExchange(long value, long comparand) { return Interlocked.CompareExchange(ref _location, value, comparand); } public long AddAndGet(long value) { return Interlocked.Add(ref _location, value); } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcAtomicLong.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcAtomicLong.cs", "repo_id": "ET", "token_count": 555 }
167
using System; using System.Collections.Generic; namespace DotRecast.Core { public readonly partial struct RcImmutableArray<T> : IList<T> { public int Count => Length; public bool IsReadOnly => true; T IList<T>.this[int index] { get { var self = this; return self[index]; } set => throw new NotSupportedException(); } public int IndexOf(T item) { for (int i = 0; i < Count; ++i) { if (_array![i].Equals(item)) return i; } return -1; } public bool Contains(T item) { return IndexOf(item) >= 0; } public void CopyTo(T[] array, int arrayIndex) { var self = this; Array.Copy(self._array!, 0, array, arrayIndex, self.Length); } public void Add(T item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Remove(T item) { throw new NotSupportedException(); } public void Insert(int index, T item) { throw new NotSupportedException(); } public void RemoveAt(int index) { throw new NotSupportedException(); } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcImmutableArray.Listable.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcImmutableArray.Listable.cs", "repo_id": "ET", "token_count": 780 }
168
using System; namespace DotRecast.Core { public readonly struct RcTelemetryTick { public readonly string Key; public readonly long Ticks; public long Millis => Ticks / TimeSpan.TicksPerMillisecond; public long Micros => Ticks / 10; // TimeSpan.TicksPerMicrosecond; public RcTelemetryTick(string key, long ticks) { Key = key; Ticks = ticks; } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcTelemetryTick.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcTelemetryTick.cs", "repo_id": "ET", "token_count": 201 }
169
fileFormatVersion: 2 guid: 076fc51ca6d09d14084b8f2d85ecaa65 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Crowd/DtCrowdAgentParams.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Crowd/DtCrowdAgentParams.cs.meta", "repo_id": "ET", "token_count": 96 }
170
/* recast4j copyright (c) 2021 Piotr Piastucki [email protected] DotRecast Copyright (c) 2023 Choi Ikpil [email protected] This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ using DotRecast.Recast; namespace DotRecast.Detour.Dynamic { public class DynamicNavMeshConfig { public readonly bool useTiles; public readonly int tileSizeX; public readonly int tileSizeZ; public readonly float cellSize; public int partition = RcPartitionType.WATERSHED.Value; public RcAreaModification walkableAreaModification = new RcAreaModification(1); public float walkableHeight; public float walkableSlopeAngle; public float walkableRadius; public float walkableClimb; public float minRegionArea; public float regionMergeArea; public float maxEdgeLen; public float maxSimplificationError; public int vertsPerPoly; public bool buildDetailMesh; public float detailSampleDistance; public float detailSampleMaxError; public bool filterLowHangingObstacles = true; public bool filterLedgeSpans = true; public bool filterWalkableLowHeightSpans = true; public bool enableCheckpoints = true; public bool keepIntermediateResults = false; public DynamicNavMeshConfig(bool useTiles, int tileSizeX, int tileSizeZ, float cellSize) { this.useTiles = useTiles; this.tileSizeX = tileSizeX; this.tileSizeZ = tileSizeZ; this.cellSize = cellSize; } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Dynamic/DynamicNavMeshConfig.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Dynamic/DynamicNavMeshConfig.cs", "repo_id": "ET", "token_count": 801 }
171
fileFormatVersion: 2 guid: 54d2fd379396a9544a3ca49054ed242e MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/JumpLinkBuilder.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/JumpLinkBuilder.cs.meta", "repo_id": "ET", "token_count": 93 }
172
using System.Collections.Generic; namespace DotRecast.Detour.TileCache { public class DtTempContour { public List<int> verts; public int nverts; public List<int> poly; public DtTempContour() { verts = new List<int>(); nverts = 0; poly = new List<int>(); } public int Npoly() { return poly.Count; } public void Clear() { nverts = 0; verts.Clear(); } }; }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.TileCache/DtTempContour.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.TileCache/DtTempContour.cs", "repo_id": "ET", "token_count": 296 }
173
fileFormatVersion: 2 guid: 78733f4864150c9459f45a098ac1b482 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtMeshHeader.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtMeshHeader.cs.meta", "repo_id": "ET", "token_count": 94 }
174
fileFormatVersion: 2 guid: 617ccd3ac956df942968e73a9d577c7e MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtQueryData.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtQueryData.cs.meta", "repo_id": "ET", "token_count": 95 }
175
/* Recast4J Copyright (c) 2015 Piotr Piastucki [email protected] This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ using System.IO; using DotRecast.Core; namespace DotRecast.Detour.Io { public class DtMeshDataReader { public const int DT_POLY_DETAIL_SIZE = 10; public DtMeshData Read(BinaryReader stream, int maxVertPerPoly) { RcByteBuffer buf = IOUtils.ToByteBuffer(stream); return Read(buf, maxVertPerPoly, false); } public DtMeshData Read(RcByteBuffer buf, int maxVertPerPoly) { return Read(buf, maxVertPerPoly, false); } public DtMeshData Read32Bit(BinaryReader stream, int maxVertPerPoly) { RcByteBuffer buf = IOUtils.ToByteBuffer(stream); return Read(buf, maxVertPerPoly, true); } public DtMeshData Read32Bit(RcByteBuffer buf, int maxVertPerPoly) { return Read(buf, maxVertPerPoly, true); } public DtMeshData Read(RcByteBuffer buf, int maxVertPerPoly, bool is32Bit) { DtMeshData data = new DtMeshData(); DtMeshHeader header = new DtMeshHeader(); data.header = header; header.magic = buf.GetInt(); if (header.magic != DtMeshHeader.DT_NAVMESH_MAGIC) { header.magic = IOUtils.SwapEndianness(header.magic); if (header.magic != DtMeshHeader.DT_NAVMESH_MAGIC) { throw new IOException("Invalid magic"); } buf.Order(buf.Order() == RcByteOrder.BIG_ENDIAN ? RcByteOrder.LITTLE_ENDIAN : RcByteOrder.BIG_ENDIAN); } header.version = buf.GetInt(); if (header.version != DtMeshHeader.DT_NAVMESH_VERSION) { if (header.version < DtMeshHeader.DT_NAVMESH_VERSION_RECAST4J_FIRST || header.version > DtMeshHeader.DT_NAVMESH_VERSION_RECAST4J_LAST) { throw new IOException("Invalid version " + header.version); } } bool cCompatibility = header.version == DtMeshHeader.DT_NAVMESH_VERSION; header.x = buf.GetInt(); header.y = buf.GetInt(); header.layer = buf.GetInt(); header.userId = buf.GetInt(); header.polyCount = buf.GetInt(); header.vertCount = buf.GetInt(); header.maxLinkCount = buf.GetInt(); header.detailMeshCount = buf.GetInt(); header.detailVertCount = buf.GetInt(); header.detailTriCount = buf.GetInt(); header.bvNodeCount = buf.GetInt(); header.offMeshConCount = buf.GetInt(); header.offMeshBase = buf.GetInt(); header.walkableHeight = buf.GetFloat(); header.walkableRadius = buf.GetFloat(); header.walkableClimb = buf.GetFloat(); header.bmin.x = buf.GetFloat(); header.bmin.y = buf.GetFloat(); header.bmin.z = buf.GetFloat(); header.bmax.x = buf.GetFloat(); header.bmax.y = buf.GetFloat(); header.bmax.z = buf.GetFloat(); header.bvQuantFactor = buf.GetFloat(); data.verts = ReadVerts(buf, header.vertCount); data.polys = ReadPolys(buf, header, maxVertPerPoly); if (cCompatibility) { buf.Position(buf.Position() + header.maxLinkCount * GetSizeofLink(is32Bit)); } data.detailMeshes = ReadPolyDetails(buf, header, cCompatibility); data.detailVerts = ReadVerts(buf, header.detailVertCount); data.detailTris = ReadDTris(buf, header); data.bvTree = ReadBVTree(buf, header); data.offMeshCons = ReadOffMeshCons(buf, header); return data; } public const int LINK_SIZEOF = 16; public const int LINK_SIZEOF32BIT = 12; public static int GetSizeofLink(bool is32Bit) { return is32Bit ? LINK_SIZEOF32BIT : LINK_SIZEOF; } private float[] ReadVerts(RcByteBuffer buf, int count) { float[] verts = new float[count * 3]; for (int i = 0; i < verts.Length; i++) { verts[i] = buf.GetFloat(); } return verts; } private DtPoly[] ReadPolys(RcByteBuffer buf, DtMeshHeader header, int maxVertPerPoly) { DtPoly[] polys = new DtPoly[header.polyCount]; for (int i = 0; i < polys.Length; i++) { polys[i] = new DtPoly(i, maxVertPerPoly); if (header.version < DtMeshHeader.DT_NAVMESH_VERSION_RECAST4J_NO_POLY_FIRSTLINK) { buf.GetInt(); // polys[i].firstLink } for (int j = 0; j < polys[i].verts.Length; j++) { polys[i].verts[j] = buf.GetShort() & 0xFFFF; } for (int j = 0; j < polys[i].neis.Length; j++) { polys[i].neis[j] = buf.GetShort() & 0xFFFF; } polys[i].flags = buf.GetShort() & 0xFFFF; polys[i].vertCount = buf.Get() & 0xFF; polys[i].areaAndtype = buf.Get() & 0xFF; } return polys; } private DtPolyDetail[] ReadPolyDetails(RcByteBuffer buf, DtMeshHeader header, bool cCompatibility) { DtPolyDetail[] polys = new DtPolyDetail[header.detailMeshCount]; for (int i = 0; i < polys.Length; i++) { polys[i] = new DtPolyDetail(); polys[i].vertBase = buf.GetInt(); polys[i].triBase = buf.GetInt(); polys[i].vertCount = buf.Get() & 0xFF; polys[i].triCount = buf.Get() & 0xFF; if (cCompatibility) { buf.GetShort(); // C struct padding } } return polys; } private int[] ReadDTris(RcByteBuffer buf, DtMeshHeader header) { int[] tris = new int[4 * header.detailTriCount]; for (int i = 0; i < tris.Length; i++) { tris[i] = buf.Get() & 0xFF; } return tris; } private DtBVNode[] ReadBVTree(RcByteBuffer buf, DtMeshHeader header) { DtBVNode[] nodes = new DtBVNode[header.bvNodeCount]; for (int i = 0; i < nodes.Length; i++) { nodes[i] = new DtBVNode(); if (header.version < DtMeshHeader.DT_NAVMESH_VERSION_RECAST4J_32BIT_BVTREE) { for (int j = 0; j < 3; j++) { nodes[i].bmin[j] = buf.GetShort() & 0xFFFF; } for (int j = 0; j < 3; j++) { nodes[i].bmax[j] = buf.GetShort() & 0xFFFF; } } else { for (int j = 0; j < 3; j++) { nodes[i].bmin[j] = buf.GetInt(); } for (int j = 0; j < 3; j++) { nodes[i].bmax[j] = buf.GetInt(); } } nodes[i].i = buf.GetInt(); } return nodes; } private DtOffMeshConnection[] ReadOffMeshCons(RcByteBuffer buf, DtMeshHeader header) { DtOffMeshConnection[] cons = new DtOffMeshConnection[header.offMeshConCount]; for (int i = 0; i < cons.Length; i++) { cons[i] = new DtOffMeshConnection(); for (int j = 0; j < 6; j++) { cons[i].pos[j] = buf.GetFloat(); } cons[i].rad = buf.GetFloat(); cons[i].poly = buf.GetShort() & 0xFFFF; cons[i].flags = buf.Get() & 0xFF; cons[i].side = buf.Get() & 0xFF; cons[i].userId = buf.GetInt(); } return cons; } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/Io/DtMeshDataReader.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/Io/DtMeshDataReader.cs", "repo_id": "ET", "token_count": 4817 }
176
using System.Collections.Generic; namespace DotRecast.Recast { public class ObjImporterContext { public List<float> vertexPositions = new List<float>(); public List<int> meshFaces = new List<int>(); } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/ObjImporterContext.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/ObjImporterContext.cs", "repo_id": "ET", "token_count": 91 }
177
/* Copyright (c) 2009-2010 Mikko Mononen [email protected] recast4j copyright (c) 2015-2019 Piotr Piastucki [email protected] DotRecast Copyright (c) 2023 Choi Ikpil [email protected] This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ namespace DotRecast.Recast { /** Represents a simple, non-overlapping contour in field space. */ public class RcContour { /** Simplified contour vertex and connection data. [Size: 4 * #nverts] */ public int[] verts; /** The number of vertices in the simplified contour. */ public int nverts; /** Raw contour vertex and connection data. [Size: 4 * #nrverts] */ public int[] rverts; /** The number of vertices in the raw contour. */ public int nrverts; /** The region id of the contour. */ public int area; /** The area id of the contour. */ public int reg; } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcContour.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcContour.cs", "repo_id": "ET", "token_count": 517 }
178
using DotRecast.Core; namespace DotRecast.Recast { /// Represents a heightfield layer within a layer set. /// @see rcHeightfieldLayerSet public class RcHeightfieldLayer { public RcVec3f bmin = new RcVec3f(); /// < The minimum bounds in world space. [(x, y, z)] public RcVec3f bmax = new RcVec3f(); /// < The maximum bounds in world space. [(x, y, z)] public float cs; /// < The size of each cell. (On the xz-plane.) public float ch; /// < The height of each cell. (The minimum increment along the y-axis.) public int width; /// < The width of the heightfield. (Along the x-axis in cell units.) public int height; /// < The height of the heightfield. (Along the z-axis in cell units.) public int minx; /// < The minimum x-bounds of usable data. public int maxx; /// < The maximum x-bounds of usable data. public int miny; /// < The minimum y-bounds of usable data. (Along the z-axis.) public int maxy; /// < The maximum y-bounds of usable data. (Along the z-axis.) public int hmin; /// < The minimum height bounds of usable data. (Along the y-axis.) public int hmax; /// < The maximum height bounds of usable data. (Along the y-axis.) public int[] heights; /// < The heightfield. [Size: width * height] public int[] areas; /// < Area ids. [Size: Same as #heights] public int[] cons; /// < Packed neighbor connection information. [Size: Same as #heights] } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcHeightfieldLayer.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcHeightfieldLayer.cs", "repo_id": "ET", "token_count": 647 }
179
namespace DotRecast.Recast { public class RcPotentialDiagonal { public int dist; public int vert; } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcPotentialDiagonal.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcPotentialDiagonal.cs", "repo_id": "ET", "token_count": 61 }
180
/* Copyright (c) 2009-2010 Mikko Mononen [email protected] recast4j copyright (c) 2015-2019 Piotr Piastucki [email protected] DotRecast Copyright (c) 2023 Choi Ikpil [email protected] This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ using DotRecast.Core; namespace DotRecast.Recast { public class RecastBuilderConfig { public readonly RcConfig cfg; public readonly int tileX; public readonly int tileZ; /** The width of the field along the x-axis. [Limit: >= 0] [Units: vx] **/ public readonly int width; /** The height of the field along the z-axis. [Limit: >= 0] [Units: vx] **/ public readonly int height; /** The minimum bounds of the field's AABB. [(x, y, z)] [Units: wu] **/ public readonly RcVec3f bmin = new RcVec3f(); /** The maximum bounds of the field's AABB. [(x, y, z)] [Units: wu] **/ public readonly RcVec3f bmax = new RcVec3f(); public RecastBuilderConfig(RcConfig cfg, RcVec3f bmin, RcVec3f bmax) : this(cfg, bmin, bmax, 0, 0) { } public RecastBuilderConfig(RcConfig cfg, RcVec3f bmin, RcVec3f bmax, int tileX, int tileZ) { this.tileX = tileX; this.tileZ = tileZ; this.cfg = cfg; this.bmin = bmin; this.bmax = bmax; if (cfg.UseTiles) { float tsx = cfg.TileSizeX * cfg.Cs; float tsz = cfg.TileSizeZ * cfg.Cs; this.bmin.x += tileX * tsx; this.bmin.z += tileZ * tsz; this.bmax.x = this.bmin.x + tsx; this.bmax.z = this.bmin.z + tsz; // Expand the heighfield bounding box by border size to find the extents of geometry we need to build this tile. // // This is done in order to make sure that the navmesh tiles connect correctly at the borders, // and the obstacles close to the border work correctly with the dilation process. // No polygons (or contours) will be created on the border area. // // IMPORTANT! // // :''''''''': // : +-----+ : // : | | : // : | |<--- tile to build // : | | : // : +-----+ :<-- geometry needed // :.........: // // You should use this bounding box to query your input geometry. // // For example if you build a navmesh for terrain, and want the navmesh tiles to match the terrain tile size // you will need to pass in data from neighbour terrain tiles too! In a simple case, just pass in all the 8 neighbours, // or use the bounding box below to only pass in a sliver of each of the 8 neighbours. this.bmin.x -= cfg.BorderSize * cfg.Cs; this.bmin.z -= cfg.BorderSize * cfg.Cs; this.bmax.x += cfg.BorderSize * cfg.Cs; this.bmax.z += cfg.BorderSize * cfg.Cs; width = cfg.TileSizeX + cfg.BorderSize * 2; height = cfg.TileSizeZ + cfg.BorderSize * 2; } else { RcUtils.CalcGridSize(this.bmin, this.bmax, cfg.Cs, out width, out height); } } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RecastBuilderConfig.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RecastBuilderConfig.cs", "repo_id": "ET", "token_count": 1942 }
181
/* Copyright (c) 2009-2010 Mikko Mononen [email protected] recast4j copyright (c) 2015-2019 Piotr Piastucki [email protected] DotRecast Copyright (c) 2023 Choi Ikpil [email protected] This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ using System; using DotRecast.Core; namespace DotRecast.Recast { using static RcConstants; public static class RecastMesh { public const int MAX_MESH_VERTS_POLY = 0xffff; public const int VERTEX_BUCKET_COUNT = (1 << 12); private static void BuildMeshAdjacency(int[] polys, int npolys, int nverts, int vertsPerPoly) { // Based on code by Eric Lengyel from: // http://www.terathon.com/code/edges.php int maxEdgeCount = npolys * vertsPerPoly; int[] firstEdge = new int[nverts + maxEdgeCount]; int nextEdge = nverts; int edgeCount = 0; RcEdge[] edges = new RcEdge[maxEdgeCount]; for (int i = 0; i < nverts; i++) firstEdge[i] = RC_MESH_NULL_IDX; for (int i = 0; i < npolys; ++i) { int t = i * vertsPerPoly * 2; for (int j = 0; j < vertsPerPoly; ++j) { if (polys[t + j] == RC_MESH_NULL_IDX) break; int v0 = polys[t + j]; int v1 = (j + 1 >= vertsPerPoly || polys[t + j + 1] == RC_MESH_NULL_IDX) ? polys[t + 0] : polys[t + j + 1]; if (v0 < v1) { RcEdge edge = new RcEdge(); edges[edgeCount] = edge; edge.vert[0] = v0; edge.vert[1] = v1; edge.poly[0] = i; edge.polyEdge[0] = j; edge.poly[1] = i; edge.polyEdge[1] = 0; // Insert edge firstEdge[nextEdge + edgeCount] = firstEdge[v0]; firstEdge[v0] = edgeCount; edgeCount++; } } } for (int i = 0; i < npolys; ++i) { int t = i * vertsPerPoly * 2; for (int j = 0; j < vertsPerPoly; ++j) { if (polys[t + j] == RC_MESH_NULL_IDX) break; int v0 = polys[t + j]; int v1 = (j + 1 >= vertsPerPoly || polys[t + j + 1] == RC_MESH_NULL_IDX) ? polys[t + 0] : polys[t + j + 1]; if (v0 > v1) { for (int e = firstEdge[v1]; e != RC_MESH_NULL_IDX; e = firstEdge[nextEdge + e]) { RcEdge edge = edges[e]; if (edge.vert[1] == v0 && edge.poly[0] == edge.poly[1]) { edge.poly[1] = i; edge.polyEdge[1] = j; break; } } } } } // Store adjacency for (int i = 0; i < edgeCount; ++i) { RcEdge e = edges[i]; if (e.poly[0] != e.poly[1]) { int p0 = e.poly[0] * vertsPerPoly * 2; int p1 = e.poly[1] * vertsPerPoly * 2; polys[p0 + vertsPerPoly + e.polyEdge[0]] = e.poly[1]; polys[p1 + vertsPerPoly + e.polyEdge[1]] = e.poly[0]; } } } private static int ComputeVertexHash(int x, int y, int z) { uint h1 = 0x8da6b343; // Large multiplicative constants; uint h2 = 0xd8163841; // here arbitrarily chosen primes uint h3 = 0xcb1ab31f; uint n = h1 * (uint)x + h2 * (uint)y + h3 * (uint)z; return (int)(n & (VERTEX_BUCKET_COUNT - 1)); } private static int AddVertex(int x, int y, int z, int[] verts, int[] firstVert, int[] nextVert, ref int nv) { int bucket = ComputeVertexHash(x, 0, z); int i = firstVert[bucket]; while (i != -1) { int v = i * 3; if (verts[v + 0] == x && (Math.Abs(verts[v + 1] - y) <= 2) && verts[v + 2] == z) return i; i = nextVert[i]; // next } // Could not find, create new. i = nv; nv++; int v2 = i * 3; verts[v2 + 0] = x; verts[v2 + 1] = y; verts[v2 + 2] = z; nextVert[i] = firstVert[bucket]; firstVert[bucket] = i; return i; } public static int Prev(int i, int n) { return i - 1 >= 0 ? i - 1 : n - 1; } public static int Next(int i, int n) { return i + 1 < n ? i + 1 : 0; } private static int Area2(int[] verts, int a, int b, int c) { return (verts[b + 0] - verts[a + 0]) * (verts[c + 2] - verts[a + 2]) - (verts[c + 0] - verts[a + 0]) * (verts[b + 2] - verts[a + 2]); } // Returns true iff c is strictly to the left of the directed // line through a to b. public static bool Left(int[] verts, int a, int b, int c) { return Area2(verts, a, b, c) < 0; } public static bool LeftOn(int[] verts, int a, int b, int c) { return Area2(verts, a, b, c) <= 0; } private static bool Collinear(int[] verts, int a, int b, int c) { return Area2(verts, a, b, c) == 0; } // Returns true iff ab properly intersects cd: they share // a point interior to both segments. The properness of the // intersection is ensured by using strict leftness. private static bool IntersectProp(int[] verts, int a, int b, int c, int d) { // Eliminate improper cases. if (Collinear(verts, a, b, c) || Collinear(verts, a, b, d) || Collinear(verts, c, d, a) || Collinear(verts, c, d, b)) return false; return (Left(verts, a, b, c) ^ Left(verts, a, b, d)) && (Left(verts, c, d, a) ^ Left(verts, c, d, b)); } // Returns T iff (a,b,c) are collinear and point c lies // on the closed segment ab. private static bool Between(int[] verts, int a, int b, int c) { if (!Collinear(verts, a, b, c)) return false; // If ab not vertical, check betweenness on x; else on y. if (verts[a + 0] != verts[b + 0]) return ((verts[a + 0] <= verts[c + 0]) && (verts[c + 0] <= verts[b + 0])) || ((verts[a + 0] >= verts[c + 0]) && (verts[c + 0] >= verts[b + 0])); return ((verts[a + 2] <= verts[c + 2]) && (verts[c + 2] <= verts[b + 2])) || ((verts[a + 2] >= verts[c + 2]) && (verts[c + 2] >= verts[b + 2])); } // Returns true iff segments ab and cd intersect, properly or improperly. public static bool Intersect(int[] verts, int a, int b, int c, int d) { if (IntersectProp(verts, a, b, c, d)) return true; if (Between(verts, a, b, c) || Between(verts, a, b, d) || Between(verts, c, d, a) || Between(verts, c, d, b)) return true; return false; } public static bool VEqual(int[] verts, int a, int b) { return verts[a + 0] == verts[b + 0] && verts[a + 2] == verts[b + 2]; } // Returns T iff (v_i, v_j) is a proper internal *or* external // diagonal of P, *ignoring edges incident to v_i and v_j*. private static bool Diagonalie(int i, int j, int n, int[] verts, int[] indices) { int d0 = (indices[i] & 0x0fffffff) * 4; int d1 = (indices[j] & 0x0fffffff) * 4; // For each edge (k,k+1) of P for (int k = 0; k < n; k++) { int k1 = Next(k, n); // Skip edges incident to i or j if (!((k == i) || (k1 == i) || (k == j) || (k1 == j))) { int p0 = (indices[k] & 0x0fffffff) * 4; int p1 = (indices[k1] & 0x0fffffff) * 4; if (VEqual(verts, d0, p0) || VEqual(verts, d1, p0) || VEqual(verts, d0, p1) || VEqual(verts, d1, p1)) continue; if (Intersect(verts, d0, d1, p0, p1)) return false; } } return true; } // Returns true iff the diagonal (i,j) is strictly internal to the // polygon P in the neighborhood of the i endpoint. private static bool InCone(int i, int j, int n, int[] verts, int[] indices) { int pi = (indices[i] & 0x0fffffff) * 4; int pj = (indices[j] & 0x0fffffff) * 4; int pi1 = (indices[Next(i, n)] & 0x0fffffff) * 4; int pin1 = (indices[Prev(i, n)] & 0x0fffffff) * 4; // If P[i] is a convex vertex [ i+1 left or on (i-1,i) ]. if (LeftOn(verts, pin1, pi, pi1)) { return Left(verts, pi, pj, pin1) && Left(verts, pj, pi, pi1); } // Assume (i-1,i,i+1) not collinear. // else P[i] is reflex. return !(LeftOn(verts, pi, pj, pi1) && LeftOn(verts, pj, pi, pin1)); } // Returns T iff (v_i, v_j) is a proper internal // diagonal of P. private static bool Diagonal(int i, int j, int n, int[] verts, int[] indices) { return InCone(i, j, n, verts, indices) && Diagonalie(i, j, n, verts, indices); } private static bool DiagonalieLoose(int i, int j, int n, int[] verts, int[] indices) { int d0 = (indices[i] & 0x0fffffff) * 4; int d1 = (indices[j] & 0x0fffffff) * 4; // For each edge (k,k+1) of P for (int k = 0; k < n; k++) { int k1 = Next(k, n); // Skip edges incident to i or j if (!((k == i) || (k1 == i) || (k == j) || (k1 == j))) { int p0 = (indices[k] & 0x0fffffff) * 4; int p1 = (indices[k1] & 0x0fffffff) * 4; if (VEqual(verts, d0, p0) || VEqual(verts, d1, p0) || VEqual(verts, d0, p1) || VEqual(verts, d1, p1)) continue; if (IntersectProp(verts, d0, d1, p0, p1)) return false; } } return true; } private static bool InConeLoose(int i, int j, int n, int[] verts, int[] indices) { int pi = (indices[i] & 0x0fffffff) * 4; int pj = (indices[j] & 0x0fffffff) * 4; int pi1 = (indices[Next(i, n)] & 0x0fffffff) * 4; int pin1 = (indices[Prev(i, n)] & 0x0fffffff) * 4; // If P[i] is a convex vertex [ i+1 left or on (i-1,i) ]. if (LeftOn(verts, pin1, pi, pi1)) return LeftOn(verts, pi, pj, pin1) && LeftOn(verts, pj, pi, pi1); // Assume (i-1,i,i+1) not collinear. // else P[i] is reflex. return !(LeftOn(verts, pi, pj, pi1) && LeftOn(verts, pj, pi, pin1)); } private static bool DiagonalLoose(int i, int j, int n, int[] verts, int[] indices) { return InConeLoose(i, j, n, verts, indices) && DiagonalieLoose(i, j, n, verts, indices); } private static int Triangulate(int n, int[] verts, int[] indices, int[] tris) { int ntris = 0; // The last bit of the index is used to indicate if the vertex can be removed. for (int i = 0; i < n; i++) { int i1 = Next(i, n); int i2 = Next(i1, n); if (Diagonal(i, i2, n, verts, indices)) { indices[i1] |= int.MinValue; // TODO : 체크 필요 } } while (n > 3) { int minLen = -1; int mini = -1; for (int minIdx = 0; minIdx < n; minIdx++) { int nextIdx1 = Next(minIdx, n); if ((indices[nextIdx1] & 0x80000000) != 0) { int p0 = (indices[minIdx] & 0x0fffffff) * 4; int p2 = (indices[Next(nextIdx1, n)] & 0x0fffffff) * 4; int dx = verts[p2 + 0] - verts[p0 + 0]; int dy = verts[p2 + 2] - verts[p0 + 2]; int len = dx * dx + dy * dy; if (minLen < 0 || len < minLen) { minLen = len; mini = minIdx; } } } if (mini == -1) { // We might get here because the contour has overlapping segments, like this: // // A o-o=====o---o B // / |C D| \ // o o o o // : : : : // We'll try to recover by loosing up the inCone test a bit so that a diagonal // like A-B or C-D can be found and we can continue. minLen = -1; mini = -1; for (int minIdx = 0; minIdx < n; minIdx++) { int nextIdx1 = Next(minIdx, n); int nextIdx2 = Next(nextIdx1, n); if (DiagonalLoose(minIdx, nextIdx2, n, verts, indices)) { int p0 = (indices[minIdx] & 0x0fffffff) * 4; int p2 = (indices[Next(nextIdx2, n)] & 0x0fffffff) * 4; int dx = verts[p2 + 0] - verts[p0 + 0]; int dy = verts[p2 + 2] - verts[p0 + 2]; int len = dx * dx + dy * dy; if (minLen < 0 || len < minLen) { minLen = len; mini = minIdx; } } } if (mini == -1) { // The contour is messed up. This sometimes happens // if the contour simplification is too aggressive. return -ntris; } } int i = mini; int i1 = Next(i, n); int i2 = Next(i1, n); tris[ntris * 3] = indices[i] & 0x0fffffff; tris[ntris * 3 + 1] = indices[i1] & 0x0fffffff; tris[ntris * 3 + 2] = indices[i2] & 0x0fffffff; ntris++; // Removes P[i1] by copying P[i+1]...P[n-1] left one index. n--; for (int k = i1; k < n; k++) indices[k] = indices[k + 1]; if (i1 >= n) i1 = 0; i = Prev(i1, n); // Update diagonal flags. if (Diagonal(Prev(i, n), i1, n, verts, indices)) indices[i] |= int.MinValue; else indices[i] &= 0x0fffffff; if (Diagonal(i, Next(i1, n), n, verts, indices)) indices[i1] |= int.MinValue; else indices[i1] &= 0x0fffffff; } // Append the remaining triangle. tris[ntris * 3] = indices[0] & 0x0fffffff; tris[ntris * 3 + 1] = indices[1] & 0x0fffffff; tris[ntris * 3 + 2] = indices[2] & 0x0fffffff; ntris++; return ntris; } private static int CountPolyVerts(int[] p, int j, int nvp) { for (int i = 0; i < nvp; ++i) if (p[i + j] == RC_MESH_NULL_IDX) return i; return nvp; } private static bool Uleft(int[] verts, int a, int b, int c) { return (verts[b + 0] - verts[a + 0]) * (verts[c + 2] - verts[a + 2]) - (verts[c + 0] - verts[a + 0]) * (verts[b + 2] - verts[a + 2]) < 0; } private static int GetPolyMergeValue(int[] polys, int pa, int pb, int[] verts, out int ea, out int eb, int nvp) { ea = 0; eb = 0; int na = CountPolyVerts(polys, pa, nvp); int nb = CountPolyVerts(polys, pb, nvp); // If the merged polygon would be too big, do not merge. if (na + nb - 2 > nvp) return -1; ea = -1; eb = -1; // Check if the polygons share an edge. for (int i = 0; i < na; ++i) { int va0 = polys[pa + i]; int va1 = polys[pa + (i + 1) % na]; if (va0 > va1) { (va0, va1) = (va1, va0); } for (int j = 0; j < nb; ++j) { int vb0 = polys[pb + j]; int vb1 = polys[pb + (j + 1) % nb]; if (vb0 > vb1) { (vb0, vb1) = (vb1, vb0); } if (va0 == vb0 && va1 == vb1) { ea = i; eb = j; break; } } } // No common edge, cannot merge. if (ea == -1 || eb == -1) return -1; // Check to see if the merged polygon would be convex. int va, vb, vc; va = polys[pa + (ea + na - 1) % na]; vb = polys[pa + ea]; vc = polys[pb + (eb + 2) % nb]; if (!Uleft(verts, va * 3, vb * 3, vc * 3)) return -1; va = polys[pb + (eb + nb - 1) % nb]; vb = polys[pb + eb]; vc = polys[pa + (ea + 2) % na]; if (!Uleft(verts, va * 3, vb * 3, vc * 3)) return -1; va = polys[pa + ea]; vb = polys[pa + (ea + 1) % na]; int dx = verts[va * 3 + 0] - verts[vb * 3 + 0]; int dy = verts[va * 3 + 2] - verts[vb * 3 + 2]; return (dx * dx) + (dy * dy); } private static void MergePolyVerts(int[] polys, int pa, int pb, int ea, int eb, int tmp, int nvp) { int na = CountPolyVerts(polys, pa, nvp); int nb = CountPolyVerts(polys, pb, nvp); // Merge polygons. Array.Fill(polys, RC_MESH_NULL_IDX, tmp, (tmp + nvp) - (tmp)); int n = 0; // Add pa for (int i = 0; i < na - 1; ++i) { polys[tmp + n] = polys[pa + (ea + 1 + i) % na]; n++; } // Add pb for (int i = 0; i < nb - 1; ++i) { polys[tmp + n] = polys[pb + (eb + 1 + i) % nb]; n++; } Array.Copy(polys, tmp, polys, pa, nvp); } private static int PushFront(int v, int[] arr, int an) { an++; for (int i = an - 1; i > 0; --i) arr[i] = arr[i - 1]; arr[0] = v; return an; } private static int PushBack(int v, int[] arr, int an) { arr[an] = v; an++; return an; } private static bool CanRemoveVertex(RcTelemetry ctx, RcPolyMesh mesh, int rem) { int nvp = mesh.nvp; // Count number of polygons to remove. int numTouchedVerts = 0; int numRemainingEdges = 0; for (int i = 0; i < mesh.npolys; ++i) { int p = i * nvp * 2; int nv = CountPolyVerts(mesh.polys, p, nvp); int numRemoved = 0; int numVerts = 0; for (int j = 0; j < nv; ++j) { if (mesh.polys[p + j] == rem) { numTouchedVerts++; numRemoved++; } numVerts++; } if (numRemoved != 0) { numRemainingEdges += numVerts - (numRemoved + 1); } } // There would be too few edges remaining to create a polygon. // This can happen for example when a tip of a triangle is marked // as deletion, but there are no other polys that share the vertex. // In this case, the vertex should not be removed. if (numRemainingEdges <= 2) return false; // Find edges which share the removed vertex. int maxEdges = numTouchedVerts * 2; int nedges = 0; int[] edges = new int[maxEdges * 3]; for (int i = 0; i < mesh.npolys; ++i) { int p = i * nvp * 2; int nv = CountPolyVerts(mesh.polys, p, nvp); // Collect edges which touches the removed vertex. for (int j = 0, k = nv - 1; j < nv; k = j++) { if (mesh.polys[p + j] == rem || mesh.polys[p + k] == rem) { // Arrange edge so that a=rem. int a = mesh.polys[p + j], b = mesh.polys[p + k]; if (b == rem) { int temp = a; a = b; b = temp; } // Check if the edge exists bool exists = false; for (int m = 0; m < nedges; ++m) { int e = m * 3; if (edges[e + 1] == b) { // Exists, increment vertex share count. edges[e + 2]++; exists = true; } } // Add new edge. if (!exists) { int e = nedges * 3; edges[e + 0] = a; edges[e + 1] = b; edges[e + 2] = 1; nedges++; } } } } // There should be no more than 2 open edges. // This catches the case that two non-adjacent polygons // share the removed vertex. In that case, do not remove the vertex. int numOpenEdges = 0; for (int i = 0; i < nedges; ++i) { if (edges[i * 3 + 2] < 2) numOpenEdges++; } if (numOpenEdges > 2) return false; return true; } private static void RemoveVertex(RcTelemetry ctx, RcPolyMesh mesh, int rem, int maxTris) { int nvp = mesh.nvp; // Count number of polygons to remove. int numRemovedVerts = 0; for (int i = 0; i < mesh.npolys; ++i) { int p = i * nvp * 2; int nv = CountPolyVerts(mesh.polys, p, nvp); for (int j = 0; j < nv; ++j) { if (mesh.polys[p + j] == rem) numRemovedVerts++; } } int nedges = 0; int[] edges = new int[numRemovedVerts * nvp * 4]; int nhole = 0; int[] hole = new int[numRemovedVerts * nvp]; int nhreg = 0; int[] hreg = new int[numRemovedVerts * nvp]; int nharea = 0; int[] harea = new int[numRemovedVerts * nvp]; for (int i = 0; i < mesh.npolys; ++i) { int p = i * nvp * 2; int nv = CountPolyVerts(mesh.polys, p, nvp); bool hasRem = false; for (int j = 0; j < nv; ++j) if (mesh.polys[p + j] == rem) hasRem = true; if (hasRem) { // Collect edges which does not touch the removed vertex. for (int j = 0, k = nv - 1; j < nv; k = j++) { if (mesh.polys[p + j] != rem && mesh.polys[p + k] != rem) { int e = nedges * 4; edges[e + 0] = mesh.polys[p + k]; edges[e + 1] = mesh.polys[p + j]; edges[e + 2] = mesh.regs[i]; edges[e + 3] = mesh.areas[i]; nedges++; } } // Remove the polygon. int p2 = (mesh.npolys - 1) * nvp * 2; if (p != p2) { Array.Copy(mesh.polys, p2, mesh.polys, p, nvp); } Array.Fill(mesh.polys, RC_MESH_NULL_IDX, p + nvp, (p + nvp + nvp) - (p + nvp)); mesh.regs[i] = mesh.regs[mesh.npolys - 1]; mesh.areas[i] = mesh.areas[mesh.npolys - 1]; mesh.npolys--; --i; } } // Remove vertex. for (int i = rem; i < mesh.nverts - 1; ++i) { mesh.verts[i * 3 + 0] = mesh.verts[(i + 1) * 3 + 0]; mesh.verts[i * 3 + 1] = mesh.verts[(i + 1) * 3 + 1]; mesh.verts[i * 3 + 2] = mesh.verts[(i + 1) * 3 + 2]; } mesh.nverts--; // Adjust indices to match the removed vertex layout. for (int i = 0; i < mesh.npolys; ++i) { int p = i * nvp * 2; int nv = CountPolyVerts(mesh.polys, p, nvp); for (int j = 0; j < nv; ++j) if (mesh.polys[p + j] > rem) mesh.polys[p + j]--; } for (int i = 0; i < nedges; ++i) { if (edges[i * 4 + 0] > rem) edges[i * 4 + 0]--; if (edges[i * 4 + 1] > rem) edges[i * 4 + 1]--; } if (nedges == 0) return; // Start with one vertex, keep appending connected // segments to the start and end of the hole. nhole = PushBack(edges[0], hole, nhole); nhreg = PushBack(edges[2], hreg, nhreg); nharea = PushBack(edges[3], harea, nharea); while (nedges != 0) { bool match = false; for (int i = 0; i < nedges; ++i) { int ea = edges[i * 4 + 0]; int eb = edges[i * 4 + 1]; int r = edges[i * 4 + 2]; int a = edges[i * 4 + 3]; bool add = false; if (hole[0] == eb) { // The segment matches the beginning of the hole boundary. nhole = PushFront(ea, hole, nhole); nhreg = PushFront(r, hreg, nhreg); nharea = PushFront(a, harea, nharea); add = true; } else if (hole[nhole - 1] == ea) { // The segment matches the end of the hole boundary. nhole = PushBack(eb, hole, nhole); nhreg = PushBack(r, hreg, nhreg); nharea = PushBack(a, harea, nharea); add = true; } if (add) { // The edge segment was added, remove it. edges[i * 4 + 0] = edges[(nedges - 1) * 4 + 0]; edges[i * 4 + 1] = edges[(nedges - 1) * 4 + 1]; edges[i * 4 + 2] = edges[(nedges - 1) * 4 + 2]; edges[i * 4 + 3] = edges[(nedges - 1) * 4 + 3]; --nedges; match = true; --i; } } if (!match) break; } int[] tris = new int[nhole * 3]; int[] tverts = new int[nhole * 4]; int[] thole = new int[nhole]; // Generate temp vertex array for triangulation. for (int i = 0; i < nhole; ++i) { int pi = hole[i]; tverts[i * 4 + 0] = mesh.verts[pi * 3 + 0]; tverts[i * 4 + 1] = mesh.verts[pi * 3 + 1]; tverts[i * 4 + 2] = mesh.verts[pi * 3 + 2]; tverts[i * 4 + 3] = 0; thole[i] = i; } // Triangulate the hole. int ntris = Triangulate(nhole, tverts, thole, tris); if (ntris < 0) { ntris = -ntris; ctx.Warn("removeVertex: Triangulate() returned bad results."); } // Merge the hole triangles back to polygons. int[] polys = new int[(ntris + 1) * nvp]; int[] pregs = new int[ntris]; int[] pareas = new int[ntris]; int tmpPoly = ntris * nvp; // Build initial polygons. int npolys = 0; Array.Fill(polys, RC_MESH_NULL_IDX, 0, (ntris * nvp) - (0)); for (int j = 0; j < ntris; ++j) { int t = j * 3; if (tris[t + 0] != tris[t + 1] && tris[t + 0] != tris[t + 2] && tris[t + 1] != tris[t + 2]) { polys[npolys * nvp + 0] = hole[tris[t + 0]]; polys[npolys * nvp + 1] = hole[tris[t + 1]]; polys[npolys * nvp + 2] = hole[tris[t + 2]]; // If this polygon covers multiple region types then // mark it as such if (hreg[tris[t + 0]] != hreg[tris[t + 1]] || hreg[tris[t + 1]] != hreg[tris[t + 2]]) pregs[npolys] = RC_MULTIPLE_REGS; else pregs[npolys] = hreg[tris[t + 0]]; pareas[npolys] = harea[tris[t + 0]]; npolys++; } } if (npolys == 0) return; // Merge polygons. if (nvp > 3) { for (;;) { // Find best polygons to merge. int bestMergeVal = 0; int bestPa = 0, bestPb = 0, bestEa = 0, bestEb = 0; for (int j = 0; j < npolys - 1; ++j) { int pj = j * nvp; for (int k = j + 1; k < npolys; ++k) { int pk = k * nvp; var v = GetPolyMergeValue(polys, pj, pk, mesh.verts, out var ea, out var eb, nvp); if (v > bestMergeVal) { bestMergeVal = v; bestPa = j; bestPb = k; bestEa = ea; bestEb = eb; } } } if (bestMergeVal > 0) { // Found best, merge. int pa = bestPa * nvp; int pb = bestPb * nvp; MergePolyVerts(polys, pa, pb, bestEa, bestEb, tmpPoly, nvp); if (pregs[bestPa] != pregs[bestPb]) pregs[bestPa] = RC_MULTIPLE_REGS; int last = (npolys - 1) * nvp; if (pb != last) { Array.Copy(polys, last, polys, pb, nvp); } pregs[bestPb] = pregs[npolys - 1]; pareas[bestPb] = pareas[npolys - 1]; npolys--; } else { // Could not merge any polygons, stop. break; } } } // Store polygons. for (int i = 0; i < npolys; ++i) { if (mesh.npolys >= maxTris) break; int p = mesh.npolys * nvp * 2; Array.Fill(mesh.polys, RC_MESH_NULL_IDX, p, (p + nvp * 2) - (p)); for (int j = 0; j < nvp; ++j) mesh.polys[p + j] = polys[i * nvp + j]; mesh.regs[mesh.npolys] = pregs[i]; mesh.areas[mesh.npolys] = pareas[i]; mesh.npolys++; if (mesh.npolys > maxTris) { throw new Exception("removeVertex: Too many polygons " + mesh.npolys + " (max:" + maxTris + "."); } } } /// @par /// /// @note If the mesh data is to be used to construct a Detour navigation mesh, then the upper /// limit must be restricted to <= #DT_VERTS_PER_POLYGON. /// /// @see rcAllocPolyMesh, rcContourSet, rcPolyMesh, rcConfig public static RcPolyMesh BuildPolyMesh(RcTelemetry ctx, RcContourSet cset, int nvp) { using var timer = ctx.ScopedTimer(RcTimerLabel.RC_TIMER_BUILD_POLYMESH); RcPolyMesh mesh = new RcPolyMesh(); mesh.bmin = cset.bmin; mesh.bmax = cset.bmax; mesh.cs = cset.cs; mesh.ch = cset.ch; mesh.borderSize = cset.borderSize; mesh.maxEdgeError = cset.maxError; int maxVertices = 0; int maxTris = 0; int maxVertsPerCont = 0; for (int i = 0; i < cset.conts.Count; ++i) { // Skip null contours. if (cset.conts[i].nverts < 3) continue; maxVertices += cset.conts[i].nverts; maxTris += cset.conts[i].nverts - 2; maxVertsPerCont = Math.Max(maxVertsPerCont, cset.conts[i].nverts); } if (maxVertices >= 0xfffe) { throw new Exception("rcBuildPolyMesh: Too many vertices " + maxVertices); } int[] vflags = new int[maxVertices]; mesh.verts = new int[maxVertices * 3]; mesh.polys = new int[maxTris * nvp * 2]; Array.Fill(mesh.polys, RC_MESH_NULL_IDX); mesh.regs = new int[maxTris]; mesh.areas = new int[maxTris]; mesh.nverts = 0; mesh.npolys = 0; mesh.nvp = nvp; mesh.maxpolys = maxTris; int[] nextVert = new int[maxVertices]; int[] firstVert = new int[VERTEX_BUCKET_COUNT]; for (int i = 0; i < VERTEX_BUCKET_COUNT; ++i) firstVert[i] = -1; int[] indices = new int[maxVertsPerCont]; int[] tris = new int[maxVertsPerCont * 3]; int[] polys = new int[(maxVertsPerCont + 1) * nvp]; int tmpPoly = maxVertsPerCont * nvp; for (int i = 0; i < cset.conts.Count; ++i) { RcContour cont = cset.conts[i]; // Skip null contours. if (cont.nverts < 3) continue; // Triangulate contour for (int j = 0; j < cont.nverts; ++j) indices[j] = j; int ntris = Triangulate(cont.nverts, cont.verts, indices, tris); if (ntris <= 0) { // Bad triangulation, should not happen. ctx.Warn("buildPolyMesh: Bad triangulation Contour " + i + "."); ntris = -ntris; } // Add and merge vertices. for (int j = 0; j < cont.nverts; ++j) { int v = j * 4; indices[j] = AddVertex(cont.verts[v + 0], cont.verts[v + 1], cont.verts[v + 2], mesh.verts, firstVert, nextVert, ref mesh.nverts); if ((cont.verts[v + 3] & RC_BORDER_VERTEX) != 0) { // This vertex should be removed. vflags[indices[j]] = 1; } } // Build initial polygons. int npolys = 0; Array.Fill(polys, RC_MESH_NULL_IDX); for (int j = 0; j < ntris; ++j) { int t = j * 3; if (tris[t + 0] != tris[t + 1] && tris[t + 0] != tris[t + 2] && tris[t + 1] != tris[t + 2]) { polys[npolys * nvp + 0] = indices[tris[t + 0]]; polys[npolys * nvp + 1] = indices[tris[t + 1]]; polys[npolys * nvp + 2] = indices[tris[t + 2]]; npolys++; } } if (npolys == 0) continue; // Merge polygons. if (nvp > 3) { for (;;) { // Find best polygons to merge. int bestMergeVal = 0; int bestPa = 0, bestPb = 0, bestEa = 0, bestEb = 0; for (int j = 0; j < npolys - 1; ++j) { int pj = j * nvp; for (int k = j + 1; k < npolys; ++k) { int pk = k * nvp; var v = GetPolyMergeValue(polys, pj, pk, mesh.verts, out var ea, out var eb, nvp); if (v > bestMergeVal) { bestMergeVal = v; bestPa = j; bestPb = k; bestEa = ea; bestEb = eb; } } } if (bestMergeVal > 0) { // Found best, merge. int pa = bestPa * nvp; int pb = bestPb * nvp; MergePolyVerts(polys, pa, pb, bestEa, bestEb, tmpPoly, nvp); int lastPoly = (npolys - 1) * nvp; if (pb != lastPoly) { Array.Copy(polys, lastPoly, polys, pb, nvp); } npolys--; } else { // Could not merge any polygons, stop. break; } } } // Store polygons. for (int j = 0; j < npolys; ++j) { int p = mesh.npolys * nvp * 2; int q = j * nvp; for (int k = 0; k < nvp; ++k) mesh.polys[p + k] = polys[q + k]; mesh.regs[mesh.npolys] = cont.reg; mesh.areas[mesh.npolys] = cont.area; mesh.npolys++; if (mesh.npolys > maxTris) { throw new Exception( "rcBuildPolyMesh: Too many polygons " + mesh.npolys + " (max:" + maxTris + ")."); } } } // Remove edge vertices. for (int i = 0; i < mesh.nverts; ++i) { if (vflags[i] != 0) { if (!CanRemoveVertex(ctx, mesh, i)) continue; RemoveVertex(ctx, mesh, i, maxTris); // Remove vertex // Note: mesh.nverts is already decremented inside RemoveVertex()! // Fixup vertex flags for (int j = i; j < mesh.nverts; ++j) vflags[j] = vflags[j + 1]; --i; } } // Calculate adjacency. BuildMeshAdjacency(mesh.polys, mesh.npolys, mesh.nverts, nvp); // Find portal edges if (mesh.borderSize > 0) { int w = cset.width; int h = cset.height; for (int i = 0; i < mesh.npolys; ++i) { int p = i * 2 * nvp; for (int j = 0; j < nvp; ++j) { if (mesh.polys[p + j] == RC_MESH_NULL_IDX) break; // Skip connected edges. if (mesh.polys[p + nvp + j] != RC_MESH_NULL_IDX) continue; int nj = j + 1; if (nj >= nvp || mesh.polys[p + nj] == RC_MESH_NULL_IDX) nj = 0; int va = mesh.polys[p + j] * 3; int vb = mesh.polys[p + nj] * 3; if (mesh.verts[va + 0] == 0 && mesh.verts[vb + 0] == 0) mesh.polys[p + nvp + j] = 0x8000 | 0; else if (mesh.verts[va + 2] == h && mesh.verts[vb + 2] == h) mesh.polys[p + nvp + j] = 0x8000 | 1; else if (mesh.verts[va + 0] == w && mesh.verts[vb + 0] == w) mesh.polys[p + nvp + j] = 0x8000 | 2; else if (mesh.verts[va + 2] == 0 && mesh.verts[vb + 2] == 0) mesh.polys[p + nvp + j] = 0x8000 | 3; } } } // Just allocate the mesh flags array. The user is resposible to fill it. mesh.flags = new int[mesh.npolys]; if (mesh.nverts > MAX_MESH_VERTS_POLY) { throw new Exception("rcBuildPolyMesh: The resulting mesh has too many vertices " + mesh.nverts + " (max " + MAX_MESH_VERTS_POLY + "). Data can be corrupted."); } if (mesh.npolys > MAX_MESH_VERTS_POLY) { throw new Exception("rcBuildPolyMesh: The resulting mesh has too many polygons " + mesh.npolys + " (max " + MAX_MESH_VERTS_POLY + "). Data can be corrupted."); } return mesh; } /// @see rcAllocPolyMesh, rcPolyMesh public static RcPolyMesh MergePolyMeshes(RcTelemetry ctx, RcPolyMesh[] meshes, int nmeshes) { if (nmeshes == 0 || meshes == null) return null; using var timer = ctx.ScopedTimer(RcTimerLabel.RC_TIMER_MERGE_POLYMESH); RcPolyMesh mesh = new RcPolyMesh(); mesh.nvp = meshes[0].nvp; mesh.cs = meshes[0].cs; mesh.ch = meshes[0].ch; mesh.bmin = meshes[0].bmin; mesh.bmax = meshes[0].bmax; int maxVerts = 0; int maxPolys = 0; int maxVertsPerMesh = 0; for (int i = 0; i < nmeshes; ++i) { mesh.bmin.Min(meshes[i].bmin); mesh.bmax.Max(meshes[i].bmax); maxVertsPerMesh = Math.Max(maxVertsPerMesh, meshes[i].nverts); maxVerts += meshes[i].nverts; maxPolys += meshes[i].npolys; } mesh.nverts = 0; mesh.verts = new int[maxVerts * 3]; mesh.npolys = 0; mesh.polys = new int[maxPolys * 2 * mesh.nvp]; Array.Fill(mesh.polys, RC_MESH_NULL_IDX, 0, (mesh.polys.Length) - (0)); mesh.regs = new int[maxPolys]; mesh.areas = new int[maxPolys]; mesh.flags = new int[maxPolys]; int[] nextVert = new int[maxVerts]; int[] firstVert = new int[VERTEX_BUCKET_COUNT]; for (int i = 0; i < VERTEX_BUCKET_COUNT; ++i) firstVert[i] = -1; int[] vremap = new int[maxVertsPerMesh]; for (int i = 0; i < nmeshes; ++i) { RcPolyMesh pmesh = meshes[i]; int ox = (int)Math.Floor((pmesh.bmin.x - mesh.bmin.x) / mesh.cs + 0.5f); int oz = (int)Math.Floor((pmesh.bmin.z - mesh.bmin.z) / mesh.cs + 0.5f); bool isMinX = (ox == 0); bool isMinZ = (oz == 0); bool isMaxX = (Math.Floor((mesh.bmax.x - pmesh.bmax.x) / mesh.cs + 0.5f)) == 0; bool isMaxZ = (Math.Floor((mesh.bmax.z - pmesh.bmax.z) / mesh.cs + 0.5f)) == 0; bool isOnBorder = (isMinX || isMinZ || isMaxX || isMaxZ); for (int j = 0; j < pmesh.nverts; ++j) { int v = j * 3; vremap[j] = AddVertex(pmesh.verts[v + 0] + ox, pmesh.verts[v + 1], pmesh.verts[v + 2] + oz, mesh.verts, firstVert, nextVert, ref mesh.nverts); } for (int j = 0; j < pmesh.npolys; ++j) { int tgt = mesh.npolys * 2 * mesh.nvp; int src = j * 2 * mesh.nvp; mesh.regs[mesh.npolys] = pmesh.regs[j]; mesh.areas[mesh.npolys] = pmesh.areas[j]; mesh.flags[mesh.npolys] = pmesh.flags[j]; mesh.npolys++; for (int k = 0; k < mesh.nvp; ++k) { if (pmesh.polys[src + k] == RC_MESH_NULL_IDX) break; mesh.polys[tgt + k] = vremap[pmesh.polys[src + k]]; } if (isOnBorder) { for (int k = mesh.nvp; k < mesh.nvp * 2; ++k) { if ((pmesh.polys[src + k] & 0x8000) != 0 && pmesh.polys[src + k] != 0xffff) { int dir = pmesh.polys[src + k] & 0xf; switch (dir) { case 0: // Portal x- if (isMinX) mesh.polys[tgt + k] = pmesh.polys[src + k]; break; case 1: // Portal z+ if (isMaxZ) mesh.polys[tgt + k] = pmesh.polys[src + k]; break; case 2: // Portal x+ if (isMaxX) mesh.polys[tgt + k] = pmesh.polys[src + k]; break; case 3: // Portal z- if (isMinZ) mesh.polys[tgt + k] = pmesh.polys[src + k]; break; } } } } } } // Calculate adjacency. BuildMeshAdjacency(mesh.polys, mesh.npolys, mesh.nverts, mesh.nvp); if (mesh.nverts > MAX_MESH_VERTS_POLY) { throw new Exception("rcBuildPolyMesh: The resulting mesh has too many vertices " + mesh.nverts + " (max " + MAX_MESH_VERTS_POLY + "). Data can be corrupted."); } if (mesh.npolys > MAX_MESH_VERTS_POLY) { throw new Exception("rcBuildPolyMesh: The resulting mesh has too many polygons " + mesh.npolys + " (max " + MAX_MESH_VERTS_POLY + "). Data can be corrupted."); } return mesh; } public static RcPolyMesh CopyPolyMesh(RcTelemetry ctx, RcPolyMesh src) { RcPolyMesh dst = new RcPolyMesh(); dst.nverts = src.nverts; dst.npolys = src.npolys; dst.maxpolys = src.npolys; dst.nvp = src.nvp; dst.bmin = src.bmin; dst.bmax = src.bmax; dst.cs = src.cs; dst.ch = src.ch; dst.borderSize = src.borderSize; dst.maxEdgeError = src.maxEdgeError; dst.verts = new int[src.nverts * 3]; Array.Copy(src.verts, 0, dst.verts, 0, dst.verts.Length); dst.polys = new int[src.npolys * 2 * src.nvp]; Array.Copy(src.polys, 0, dst.polys, 0, dst.polys.Length); dst.regs = new int[src.npolys]; Array.Copy(src.regs, 0, dst.regs, 0, dst.regs.Length); dst.areas = new int[src.npolys]; Array.Copy(src.areas, 0, dst.areas, 0, dst.areas.Length); dst.flags = new int[src.npolys]; Array.Copy(src.flags, 0, dst.flags, 0, dst.flags.Length); return dst; } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RecastMesh.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RecastMesh.cs", "repo_id": "ET", "token_count": 32748 }
182
namespace ET { internal struct AckItem { internal uint serialNumber; internal uint timestamp; } }
ET/Unity/Assets/Scripts/ThirdParty/Kcp/AckItem.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/Kcp/AckItem.cs", "repo_id": "ET", "token_count": 51 }
183
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace NativeCollection { public unsafe class HashSet<T>: ICollection<T>, INativeCollectionClass where T : unmanaged, IEquatable<T> { private UnsafeType.HashSet<T>* _hashSet; private const int _defaultCapacity = 10; public HashSet(int capacity = _defaultCapacity) { _hashSet = UnsafeType.HashSet<T>.Create(capacity); IsDisposed = false; } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public UnsafeType.HashSet<T>.Enumerator GetEnumerator() => new UnsafeType.HashSet<T>.Enumerator(_hashSet); [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Add(T item) { _hashSet->Add(item); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clear() { _hashSet->Clear(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Contains(T item) { return _hashSet->Contains(item); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void CopyTo(T[] array, int arrayIndex) { _hashSet->CopyTo(array, arrayIndex); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { return _hashSet->Remove(item); } public int Count => _hashSet->Count; public bool IsReadOnly => false; public void Dispose() { if (IsDisposed) { return; } if (_hashSet!=null) { _hashSet->Dispose(); NativeMemoryHelper.Free(_hashSet); NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<UnsafeType.HashSet<T>>()); IsDisposed = true; } } public void ReInit() { if (IsDisposed) { _hashSet = UnsafeType.HashSet<T>.Create(_defaultCapacity); IsDisposed = false; } } public bool IsDisposed { get; private set; } ~HashSet() { Dispose(); } } }
ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/HashSet.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/HashSet.cs", "repo_id": "ET", "token_count": 972 }
184
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace NativeCollection { public unsafe class SortedSet<T> : ICollection<T>, INativeCollectionClass where T : unmanaged, IEquatable<T>,IComparable<T> { private UnsafeType.SortedSet<T>* _sortedSet; private const int _defaultNodePoolBlockSize = 64; private int _poolBlockSize; public SortedSet(int nodePoolSize = _defaultNodePoolBlockSize) { _poolBlockSize = nodePoolSize; _sortedSet = UnsafeType.SortedSet<T>.Create(_poolBlockSize); IsDisposed = false; } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public UnsafeType.SortedSet<T>.Enumerator GetEnumerator() { return new UnsafeType.SortedSet<T>.Enumerator(_sortedSet); } void ICollection<T>.Add(T item) { _sortedSet->Add(item); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Add(T item) { return _sortedSet->Add(item); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clear() { _sortedSet->Clear(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Contains(T item) { return _sortedSet->Contains(item); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void CopyTo(T[] array, int arrayIndex) { _sortedSet->CopyTo(array,arrayIndex); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { return _sortedSet->Remove(item); } public T? Min => _sortedSet->Min; public T? Max => _sortedSet->Max; public int Count => _sortedSet->Count; public bool IsReadOnly => false; public void Dispose() { if (IsDisposed) { return; } if (_sortedSet!=null) { _sortedSet->Dispose(); NativeMemoryHelper.Free(_sortedSet); NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<UnsafeType.SortedSet<T>>()); IsDisposed = true; } } public void ReInit() { if (IsDisposed) { _sortedSet = UnsafeType.SortedSet<T>.Create(_poolBlockSize); IsDisposed = false; } } public bool IsDisposed { get; private set; } } }
ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/SortedSet.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/SortedSet.cs", "repo_id": "ET", "token_count": 1105 }
185
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace NativeCollection.UnsafeType { public unsafe struct Map<T,K> :IEnumerable<MapPair<T, K>>, IDisposable where T : unmanaged, IEquatable<T>, IComparable<T> where K : unmanaged, IEquatable<K> { private UnsafeType.SortedSet<MapPair<T, K>>* _sortedSet; public static Map<T, K>* Create(int poolBlockSize) { Map<T, K>* map = (Map<T, K>*)NativeMemoryHelper.Alloc((UIntPtr)Unsafe.SizeOf<Map<T, K>>()); map->_sortedSet = UnsafeType.SortedSet<MapPair<T, K>>.Create(poolBlockSize); return map; } public K this[T key] { get { var pair = new MapPair<T, K>(key); var node = _sortedSet->FindNode(pair); if (node!=null) { return node->Item.Value; } return default; } set { var pair = new MapPair<T, K>(key,value); var node = _sortedSet->FindNode(pair); if (node!=null) { node->Item._value = value; } else { _sortedSet->Add(pair); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Add(T key, K value) { var mapPair = new MapPair<T, K>(key,value); _sortedSet->Add(mapPair); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clear() { _sortedSet->Clear(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ContainsKey(T key) { return _sortedSet->Contains(new MapPair<T, K>(key)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Remove(T key) { return _sortedSet->Remove(new MapPair<T, K>(key)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryGetValue(T key, out K value) { var node = _sortedSet->FindNode(new MapPair<T, K>(key)); if (node==null) { value = default; return false; } value = node->Item.Value; return true; } public int Count => _sortedSet->Count; IEnumerator<MapPair<T, K>> IEnumerable<MapPair<T, K>>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public UnsafeType.SortedSet<MapPair<T, K>>.Enumerator GetEnumerator() { return new UnsafeType.SortedSet<MapPair<T, K>>.Enumerator(_sortedSet); } public void Dispose() { if (_sortedSet != null) { _sortedSet->Dispose(); NativeMemoryHelper.Free(_sortedSet); NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<UnsafeType.SortedSet<MapPair<T, K>>>()); } } } }
ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/Map/Map.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/Map/Map.cs", "repo_id": "ET", "token_count": 1473 }
186
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Numerics; using System.Runtime.CompilerServices; using System.Text; namespace NativeCollection.UnsafeType { public unsafe partial struct SortedSet<T> : ICollection<T>, IDisposable where T : unmanaged, IEquatable<T>,IComparable<T> { private SortedSet<T>* _self; private int _count; private Node* _root; private FixedSizeMemoryPool* _nodeMemoryPool; private NativeStackPool<Stack<IntPtr>>* _stackPool; private int _version; private const int _defaultNodePoolBlockSize = 64; public static SortedSet<T>* Create(int nodePoolBlockSize = _defaultNodePoolBlockSize) { var sortedSet = (SortedSet<T>*)NativeMemoryHelper.Alloc((UIntPtr)Unsafe.SizeOf<SortedSet<T>>()); sortedSet->_self = sortedSet; sortedSet->_root = null; sortedSet->_count = 0; sortedSet->_version = 0; sortedSet->_stackPool = NativeStackPool<Stack<IntPtr>>.Create(2); sortedSet->_nodeMemoryPool = FixedSizeMemoryPool.Create(nodePoolBlockSize, Unsafe.SizeOf<Node>()); return sortedSet; } public T? Min { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return MinInternal; } } internal T? MinInternal { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (_root == null) return default; var current = _root; while (current->Left != null) current = current->Left; return current->Item; } } public T? Max { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return MaxInternal; } } internal T? MaxInternal { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (_root == null) return default; var current = _root; while (current->Right != null) current = current->Right; return current->Item; } } public int Count { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { VersionCheck(true); return _count; } } bool ICollection<T>.IsReadOnly => false; [MethodImpl(MethodImplOptions.AggressiveInlining)] public void CopyTo(T[] array, int index) { CopyTo(array, index, Count); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { return DoRemove(item); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool RemoveRef(in T item) { return DoRemove(item); } [MethodImpl(MethodImplOptions.AggressiveInlining)] void ICollection<T>.Add(T item) { Add(item); } public void Clear() { using var enumerator = GetEnumerator(); do { if (enumerator.CurrentPointer != null) { _nodeMemoryPool->Free(enumerator.CurrentPointer); } } while (enumerator.MoveNext()); _root = null; _count = 0; ++_version; _stackPool->Clear(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Contains(T item) { return FindNode(item) != null; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ContainsRef(in T item) { return FindNode(item) != null; } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Dispose() { Clear(); if (_stackPool!=null) { _stackPool->Dispose(); NativeMemoryHelper.Free(_stackPool); NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<NativeStackPool<Stack<IntPtr>>>()); } if (_nodeMemoryPool!=null) { _nodeMemoryPool->Dispose(); _nodeMemoryPool = null; } _version = 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void CopyTo(T[] array) { CopyTo(array, 0, Count); } public void CopyTo(T[] array, int index, int count) { //ArgumentNullException.ThrowIfNull(array); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), index, "ArgumentOutOfRange_NeedNonNegNum"); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), "ArgumentOutOfRange_NeedNonNegNum"); if (count > array.Length - index) throw new ArgumentException("Arg_ArrayPlusOffTooSmall"); count += index; // Make `count` the upper bound. InOrderTreeWalk(node => { if (index >= count) return false; array[index++] = node->Item; return true; }); } /// <summary> /// Does an in-order tree walk and calls the delegate for each node. /// </summary> /// <param name="action"> /// The delegate to invoke on each node. /// If the delegate returns <c>false</c>, the walk is stopped. /// </param> /// <returns><c>true</c> if the entire tree has been walked; otherwise, <c>false</c>.</returns> internal bool InOrderTreeWalk(TreeWalkPredicate action) { if (_root == null) return true; // The maximum height of a red-black tree is 2 * log2(n+1). // See page 264 of "Introduction to algorithms" by Thomas H. Cormen // Note: It's not strictly necessary to provide the stack capacity, but we don't // want the stack to unnecessarily allocate arrays as it grows. var stack = UnsafeType.Stack<IntPtr>.Create(2 * Log2(Count + 1)); var current = _root; while (current != null) { stack->Push((IntPtr)current); current = current->Left; } while (stack->Count != 0) { current = (Node*)stack->Pop(); if (!action(current)) return false; var node = current->Right; while (node != null) { stack->Push((IntPtr)node); node = node->Left; } } stack->Dispose(); NativeMemoryHelper.Free(stack); NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<UnsafeType.Stack<IntPtr>>()); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void VersionCheck(bool updateCount = false) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal int TotalCount() { return Count; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool IsWithinRange(in T item) { return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Add(T item) { return AddIfNotPresent(item); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool AddRef(in T item) { return AddIfNotPresent(item); } internal bool AddIfNotPresent(in T item) { if (_root == null) { // The tree is empty and this is the first item. _root = Node.AllocFromMemoryPool(item, NodeColor.Black,_nodeMemoryPool); _count = 1; _version++; return true; } // Search for a node at bottom to insert the new node. // If we can guarantee the node we found is not a 4-node, it would be easy to do insertion. // We split 4-nodes along the search path. var current = _root; Node* parent = null; Node* grandParent = null; Node* greatGrandParent = null; // Even if we don't actually add to the set, we may be altering its structure (by doing rotations and such). // So update `_version` to disable any instances of Enumerator/TreeSubSet from working on it. _version++; var order = 0; while (current != null) { order = item.CompareTo(current->Item); if (order == 0) { // We could have changed root node to red during the search process. // We need to set it to black before we return. _root->ColorBlack(); return false; } // Split a 4-node into two 2-nodes. if (current->Is4Node) { current->Split4Node(); // We could have introduced two consecutive red nodes after split. Fix that by rotation. if (Node.IsNonNullRed(parent)) InsertionBalance(current, parent, grandParent, greatGrandParent); } greatGrandParent = grandParent; grandParent = parent; parent = current; current = order < 0 ? current->Left : current->Right; } Debug.Assert(parent != null); // We're ready to insert the new node. var node = Node.AllocFromMemoryPool(item, NodeColor.Red,_nodeMemoryPool); if (order > 0) parent->Right = node; else parent->Left = node; // The new node will be red, so we will need to adjust colors if its parent is also red. if (parent->IsRed) InsertionBalance(node, parent, grandParent, greatGrandParent); // The root node is always black. _root->ColorBlack(); ++_count; return true; } internal bool DoRemove(in T item) { if (_root == null) return false; // Search for a node and then find its successor. // Then copy the item from the successor to the matching node, and delete the successor. // If a node doesn't have a successor, we can replace it with its left child (if not empty), // or delete the matching node. // // In top-down implementation, it is important to make sure the node to be deleted is not a 2-node. // Following code will make sure the node on the path is not a 2-node. // Even if we don't actually remove from the set, we may be altering its structure (by doing rotations // and such). So update our version to disable any enumerators/subsets working on it. _version++; var current = _root; Node* parent = null; Node* grandParent = null; Node* match = null; Node* parentOfMatch = null; var foundMatch = false; while (current != null) { if (current->Is2Node) { // Fix up 2-node if (parent == null) { // `current` is the root. Mark it red. current->ColorRed(); } else { var sibling = parent->GetSibling(current); if (sibling->IsRed) { // If parent is a 3-node, flip the orientation of the red link. // We can achieve this by a single rotation. // This case is converted to one of the other cases below. Debug.Assert(parent->IsBlack); if (parent->Right == sibling) parent->RotateLeft(); else parent->RotateRight(); parent->ColorRed(); sibling->ColorBlack(); // The red parent can't have black children. // `sibling` becomes the child of `grandParent` or `root` after rotation. Update the link from that node. ReplaceChildOrRoot(grandParent, parent, sibling); // `sibling` will become the grandparent of `current`. grandParent = sibling; if (parent == match) parentOfMatch = sibling; sibling = parent->GetSibling(current); } Debug.Assert(Node.IsNonNullBlack(sibling)); if (sibling->Is2Node) { parent->Merge2Nodes(); } else { // `current` is a 2-node and `sibling` is either a 3-node or a 4-node. // We can change the color of `current` to red by some rotation. var newGrandParent = parent->Rotate(parent->GetRotation(current, sibling))!; newGrandParent->Color = parent->Color; parent->ColorBlack(); current->ColorRed(); ReplaceChildOrRoot(grandParent, parent, newGrandParent); if (parent == match) parentOfMatch = newGrandParent; } } } // We don't need to compare after we find the match. var order = foundMatch ? -1 : item.CompareTo(current->Item); if (order == 0) { // Save the matching node. foundMatch = true; match = current; parentOfMatch = parent; } grandParent = parent; parent = current; // If we found a match, continue the search in the right sub-tree. current = order < 0 ? current->Left : current->Right; } // Move successor to the matching node position and replace links. if (match != null) { ReplaceNode(match, parentOfMatch!, parent!, grandParent!); --_count; //_nodePool->Return(match); _nodeMemoryPool->Free(match); } if (_root != null) _root->ColorBlack(); return foundMatch; } // After calling InsertionBalance, we need to make sure `current` and `parent` are up-to-date. // It doesn't matter if we keep `grandParent` and `greatGrandParent` up-to-date, because we won't // need to split again in the next node. // By the time we need to split again, everything will be correctly set. private void InsertionBalance(Node* current, Node* parent, Node* grandParent, Node* greatGrandParent) { Debug.Assert(parent != null); Debug.Assert(grandParent != null); var parentIsOnRight = grandParent->Right == parent; var currentIsOnRight = parent->Right == current; Node* newChildOfGreatGrandParent; if (parentIsOnRight == currentIsOnRight) { // Same orientation, single rotation newChildOfGreatGrandParent = currentIsOnRight ? grandParent->RotateLeft() : grandParent->RotateRight(); } else { // Different orientation, double rotation newChildOfGreatGrandParent = currentIsOnRight ? grandParent->RotateLeftRight() : grandParent->RotateRightLeft(); // Current node now becomes the child of `greatGrandParent` parent = greatGrandParent; } // `grandParent` will become a child of either `parent` of `current`. grandParent->ColorRed(); newChildOfGreatGrandParent->ColorBlack(); ReplaceChildOrRoot(greatGrandParent, grandParent, newChildOfGreatGrandParent); } /// <summary> /// Replaces the child of a parent node, or replaces the root if the parent is <c>null</c>. /// </summary> /// <param name="parent">The (possibly <c>null</c>) parent.</param> /// <param name="child">The child node to replace.</param> /// <param name="newChild">The node to replace <paramref name="child" /> with.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ReplaceChildOrRoot(Node* parent, Node* child, Node* newChild) { if (parent != null) parent->ReplaceChild(child, newChild); else _root = newChild; } /// <summary> /// Replaces the matching node with its successor. /// </summary> private void ReplaceNode(Node* match, Node* parentOfMatch, Node* successor, Node* parentOfSuccessor) { Debug.Assert(match != null); if (successor == match) { // This node has no successor. This can only happen if the right child of the match is null. Debug.Assert(match->Right == null); successor = match->Left!; } else { Debug.Assert(parentOfSuccessor != null); Debug.Assert(successor->Left == null); Debug.Assert((successor->Right == null && successor->IsRed) || (successor->Right!->IsRed && successor->IsBlack)); if (successor->Right != null) successor->Right->ColorBlack(); if (parentOfSuccessor != match) { // Detach the successor from its parent and set its right child. parentOfSuccessor->Left = successor->Right; successor->Right = match->Right; } successor->Left = match->Left; } if (successor != null) successor->Color = match->Color; ReplaceChildOrRoot(parentOfMatch, match, successor!); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Node* FindNode(in T item) { var current = _root; while (current != null) { var order = item.CompareTo(current->Item); if (order == 0) return current; current = order < 0 ? current->Left : current->Right; } return null; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void UpdateVersion() { ++_version; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int Log2(int value) { #if NET6_0_OR_GREATER return BitOperations.Log2((uint)value); #else int num = 0; for (; value > 0; value >>= 1) ++num; return num; #endif } public Enumerator GetEnumerator() { return new Enumerator(_self); } internal delegate bool TreeWalkPredicate(Node* node); public struct Enumerator : IEnumerator<T> { private readonly SortedSet<T>* _tree; private readonly int _version; private readonly UnsafeType.Stack<IntPtr>* _stack; private readonly bool _reverse; internal Enumerator(SortedSet<T>* set) : this(set, false) { } internal Enumerator(SortedSet<T>* set, bool reverse) { _tree = set; set->VersionCheck(); _version = set->_version; // 2 log(n + 1) is the maximum height. _stack = set->_stackPool->Alloc(); if (_stack==null) { _stack = UnsafeType.Stack<IntPtr>.Create(2 * Log2(set->TotalCount() + 1)); } CurrentPointer = null; _reverse = reverse; Initialize(); } private void Initialize() { CurrentPointer = null; var node = _tree->_root; while (node != null) { var next = _reverse ? node->Right : node->Left; var other = _reverse ? node->Left : node->Right; if (_tree->IsWithinRange(node->Item)) { _stack->Push((IntPtr)node); node = next; } else if (next == null || !_tree->IsWithinRange(next->Item)) { node = other; } else { node = next; } } } public bool MoveNext() { // Make sure that the underlying subset has not been changed since //_tree->VersionCheck(); if (_version != _tree->_version) { ThrowHelper.SortedSetVersionChanged(); } if (_stack->Count == 0) { CurrentPointer = null; return false; } CurrentPointer = (Node*)_stack->Pop(); var node = _reverse ? CurrentPointer->Left : CurrentPointer->Right; while (node != null) { var next = _reverse ? node->Right : node->Left; var other = _reverse ? node->Left : node->Right; if (_tree->IsWithinRange(node->Item)) { _stack->Push((IntPtr)node); node = next; } else if (other == null || !_tree->IsWithinRange(other->Item)) { node = next; } else { node = other; } } return true; } public void Dispose() { //Console.WriteLine("Enumerator Dispose"); // _stack->Dispose(); // // NativeMemoryHelper.Free(_stack); // GC.RemoveMemoryPressure(Unsafe.SizeOf<NativeCollection.Stack<IntPtr>>()); _tree->_stackPool->Return(_stack); } public T Current { get { if (CurrentPointer != null) return CurrentPointer->Item; return default!; // Should only happen when accessing Current is undefined behavior } } internal Node* CurrentPointer { get; private set; } internal bool NotStartedOrEnded => CurrentPointer == null; internal void Reset() { if (_version != _tree->_version) throw new InvalidOperationException("_version != _tree.version"); _stack->Clear(); Initialize(); } object IEnumerator.Current { get { if (CurrentPointer == null) throw new InvalidOperationException("_current == null"); return CurrentPointer->Item; } } void IEnumerator.Reset() { Reset(); } } public override string ToString() { var sb = new StringBuilder(); foreach (var value in this) sb.Append($"{value} "); return sb.ToString(); } } }
ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/SortedSet/SortedSet.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/SortedSet/SortedSet.cs", "repo_id": "ET", "token_count": 10475 }
187
fileFormatVersion: 2 guid: 6e350d8bbf4dc4ebd9c40ab1fabe7735 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/TrueSync/Fix64TanLut.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/TrueSync/Fix64TanLut.cs.meta", "repo_id": "ET", "token_count": 96 }
188
fileFormatVersion: 2 guid: 873af7c334fcb4eb8b164e9bc4ae767d MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/TrueSync/TSVector4.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/TrueSync/TSVector4.cs.meta", "repo_id": "ET", "token_count": 95 }
189
{ "name": "Ignore.Hotfix.Server", "rootNamespace": "", "references": [], "includePlatforms": [], "excludePlatforms": [], "allowUnsafeCode": false, "overrideReferences": false, "precompiledReferences": [], "autoReferenced": true, "defineConstraints": [ "IGNORE" ], "versionDefines": [], "noEngineReferences": false }
ET/Unity/Assets/Settings/IgnoreAsmdef/Hotfix/Server/Ignore.asmdef.DISABLED/0
{ "file_path": "ET/Unity/Assets/Settings/IgnoreAsmdef/Hotfix/Server/Ignore.asmdef.DISABLED", "repo_id": "ET", "token_count": 159 }
190
fileFormatVersion: 2 guid: b6233ec7cb381bc46b469eacc1add3f6 AssemblyDefinitionImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Settings/IgnoreAsmdef/Model/Generate/ClientServer/Ignore.asmdef.DISABLED.meta/0
{ "file_path": "ET/Unity/Assets/Settings/IgnoreAsmdef/Model/Generate/ClientServer/Ignore.asmdef.DISABLED.meta", "repo_id": "ET", "token_count": 64 }
191
fileFormatVersion: 2 guid: 8a2f5b990568dc64583685ce952a3370 timeCreated: 1510222436 licenseType: Free TextScriptImporter: userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/link.xml.meta/0
{ "file_path": "ET/Unity/Assets/link.xml.meta", "repo_id": "ET", "token_count": 72 }
192
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!114 &1 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 0} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: e189374413a3f00468e49d51d8b27a09, type: 3} m_Name: m_EditorClassIdentifier: enable: 1 useGlobalIl2cpp: 0 hybridclrRepoURL: https://gitee.com/focus-creative-games/hybridclr il2cppPlusRepoURL: https://gitee.com/focus-creative-games/il2cpp_plus hotUpdateAssemblyDefinitions: [] hotUpdateAssemblies: - Unity.Model - Unity.Hotfix - Unity.ModelView - Unity.HotfixView preserveHotUpdateAssemblies: [] hotUpdateDllCompileOutputRootDir: HybridCLRData/HotUpdateDlls externalHotUpdateAssembliyDirs: - Temp/Bin/Debug strippedAOTDllOutputRootDir: HybridCLRData/AssembliesPostIl2CppStrip patchAOTAssemblies: - Unity.ThirdParty.dll - Unity.Loader.dll - Unity.Core.dll - MongoDB.Bson.dll - CommandLine.dll - NLog.dll - System.dll - System.Core.dll - mscorlib.dll - MemoryPack.dll - System.Runtime.CompilerServices.Unsafe.dll outputLinkFile: Scripts/Loader/Plugins/HybridCLR/Generated/link.xml outputAOTGenericReferenceFile: Scripts/Loader/Plugins/HybridCLR/Generated/AOTGenericReferences.cs maxGenericReferenceIteration: 10 maxMethodBridgeGenericIteration: 10
ET/Unity/ProjectSettings/HybridCLRSettings.asset/0
{ "file_path": "ET/Unity/ProjectSettings/HybridCLRSettings.asset", "repo_id": "ET", "token_count": 551 }
193
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!114 &1 MonoBehaviour: m_ObjectHideFlags: 61 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 0} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: a287be6c49135cd4f9b2b8666c39d999, type: 3} m_Name: m_EditorClassIdentifier: assetDefaultFramerate: 60 m_DefaultFrameRate: 60
ET/Unity/ProjectSettings/TimelineSettings.asset/0
{ "file_path": "ET/Unity/ProjectSettings/TimelineSettings.asset", "repo_id": "ET", "token_count": 194 }
194
/* Copyright (c) 2015 Ki 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. */ using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; namespace ICSharpCode.BamlDecompiler.Baml { internal class BamlBinaryReader : BinaryReader { public BamlBinaryReader(Stream stream) : base(stream) { } public int ReadEncodedInt() => Read7BitEncodedInt(); } internal class BamlReader { const string MSBAML_SIG = "MSBAML"; internal static bool IsBamlHeader(Stream str) { var pos = str.Position; try { var rdr = new BinaryReader(str, Encoding.Unicode); int len = (int)(rdr.ReadUInt32() >> 1); if (len != MSBAML_SIG.Length) return false; var sig = new string(rdr.ReadChars(len)); return sig == MSBAML_SIG; } finally { str.Position = pos; } } static string ReadSignature(Stream str) { var rdr = new BinaryReader(str, Encoding.Unicode); uint len = rdr.ReadUInt32(); var sig = new string(rdr.ReadChars((int)(len >> 1))); rdr.ReadBytes((int)(((len + 3) & ~3) - len)); return sig; } public static BamlDocument ReadDocument(Stream str, CancellationToken token) { var ret = new BamlDocument(); var reader = new BamlBinaryReader(str); ret.Signature = ReadSignature(str); if (ret.Signature != MSBAML_SIG) throw new NotSupportedException(); ret.ReaderVersion = new BamlDocument.BamlVersion { Major = reader.ReadUInt16(), Minor = reader.ReadUInt16() }; ret.UpdaterVersion = new BamlDocument.BamlVersion { Major = reader.ReadUInt16(), Minor = reader.ReadUInt16() }; ret.WriterVersion = new BamlDocument.BamlVersion { Major = reader.ReadUInt16(), Minor = reader.ReadUInt16() }; if (ret.ReaderVersion.Major != 0 || ret.ReaderVersion.Minor != 0x60 || ret.UpdaterVersion.Major != 0 || ret.UpdaterVersion.Minor != 0x60 || ret.WriterVersion.Major != 0 || ret.WriterVersion.Minor != 0x60) throw new NotSupportedException(); var recs = new Dictionary<long, BamlRecord>(); while (str.Position < str.Length) { token.ThrowIfCancellationRequested(); long pos = str.Position; var type = (BamlRecordType)reader.ReadByte(); BamlRecord rec = null; switch (type) { case BamlRecordType.AssemblyInfo: rec = new AssemblyInfoRecord(); break; case BamlRecordType.AttributeInfo: rec = new AttributeInfoRecord(); break; case BamlRecordType.ConstructorParametersStart: rec = new ConstructorParametersStartRecord(); break; case BamlRecordType.ConstructorParametersEnd: rec = new ConstructorParametersEndRecord(); break; case BamlRecordType.ConstructorParameterType: rec = new ConstructorParameterTypeRecord(); break; case BamlRecordType.ConnectionId: rec = new ConnectionIdRecord(); break; case BamlRecordType.ContentProperty: rec = new ContentPropertyRecord(); break; case BamlRecordType.DefAttribute: rec = new DefAttributeRecord(); break; case BamlRecordType.DefAttributeKeyString: rec = new DefAttributeKeyStringRecord(); break; case BamlRecordType.DefAttributeKeyType: rec = new DefAttributeKeyTypeRecord(); break; case BamlRecordType.DeferableContentStart: rec = new DeferableContentStartRecord(); break; case BamlRecordType.DocumentEnd: rec = new DocumentEndRecord(); break; case BamlRecordType.DocumentStart: rec = new DocumentStartRecord(); break; case BamlRecordType.ElementEnd: rec = new ElementEndRecord(); break; case BamlRecordType.ElementStart: rec = new ElementStartRecord(); break; case BamlRecordType.KeyElementEnd: rec = new KeyElementEndRecord(); break; case BamlRecordType.KeyElementStart: rec = new KeyElementStartRecord(); break; case BamlRecordType.LineNumberAndPosition: rec = new LineNumberAndPositionRecord(); break; case BamlRecordType.LinePosition: rec = new LinePositionRecord(); break; case BamlRecordType.LiteralContent: rec = new LiteralContentRecord(); break; case BamlRecordType.NamedElementStart: rec = new NamedElementStartRecord(); break; case BamlRecordType.OptimizedStaticResource: rec = new OptimizedStaticResourceRecord(); break; case BamlRecordType.PIMapping: rec = new PIMappingRecord(); break; case BamlRecordType.PresentationOptionsAttribute: rec = new PresentationOptionsAttributeRecord(); break; case BamlRecordType.Property: rec = new PropertyRecord(); break; case BamlRecordType.PropertyArrayEnd: rec = new PropertyArrayEndRecord(); break; case BamlRecordType.PropertyArrayStart: rec = new PropertyArrayStartRecord(); break; case BamlRecordType.PropertyComplexEnd: rec = new PropertyComplexEndRecord(); break; case BamlRecordType.PropertyComplexStart: rec = new PropertyComplexStartRecord(); break; case BamlRecordType.PropertyCustom: rec = new PropertyCustomRecord(); break; case BamlRecordType.PropertyDictionaryEnd: rec = new PropertyDictionaryEndRecord(); break; case BamlRecordType.PropertyDictionaryStart: rec = new PropertyDictionaryStartRecord(); break; case BamlRecordType.PropertyListEnd: rec = new PropertyListEndRecord(); break; case BamlRecordType.PropertyListStart: rec = new PropertyListStartRecord(); break; case BamlRecordType.PropertyStringReference: rec = new PropertyStringReferenceRecord(); break; case BamlRecordType.PropertyTypeReference: rec = new PropertyTypeReferenceRecord(); break; case BamlRecordType.PropertyWithConverter: rec = new PropertyWithConverterRecord(); break; case BamlRecordType.PropertyWithExtension: rec = new PropertyWithExtensionRecord(); break; case BamlRecordType.PropertyWithStaticResourceId: rec = new PropertyWithStaticResourceIdRecord(); break; case BamlRecordType.RoutedEvent: rec = new RoutedEventRecord(); break; case BamlRecordType.StaticResourceEnd: rec = new StaticResourceEndRecord(); break; case BamlRecordType.StaticResourceId: rec = new StaticResourceIdRecord(); break; case BamlRecordType.StaticResourceStart: rec = new StaticResourceStartRecord(); break; case BamlRecordType.StringInfo: rec = new StringInfoRecord(); break; case BamlRecordType.Text: rec = new TextRecord(); break; case BamlRecordType.TextWithConverter: rec = new TextWithConverterRecord(); break; case BamlRecordType.TextWithId: rec = new TextWithIdRecord(); break; case BamlRecordType.TypeInfo: rec = new TypeInfoRecord(); break; case BamlRecordType.TypeSerializerInfo: rec = new TypeSerializerInfoRecord(); break; case BamlRecordType.XmlnsProperty: rec = new XmlnsPropertyRecord(); break; case BamlRecordType.XmlAttribute: case BamlRecordType.ProcessingInstruction: case BamlRecordType.LastRecordType: case BamlRecordType.EndAttributes: case BamlRecordType.DefTag: case BamlRecordType.ClrEvent: case BamlRecordType.Comment: default: throw new NotSupportedException(); } rec.Position = pos; rec.Read(reader); ret.Add(rec); recs.Add(pos, rec); } for (int i = 0; i < ret.Count; i++) { if (ret[i] is IBamlDeferRecord defer) defer.ReadDefer(ret, i, _ => recs[_]); } return ret; } } }
ILSpy/ICSharpCode.BamlDecompiler/Baml/BamlReader.cs/0
{ "file_path": "ILSpy/ICSharpCode.BamlDecompiler/Baml/BamlReader.cs", "repo_id": "ILSpy", "token_count": 3428 }
195
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> <SignAssembly>True</SignAssembly> <AssemblyOriginatorKeyFile>..\ICSharpCode.Decompiler\ICSharpCode.Decompiler.snk</AssemblyOriginatorKeyFile> <NeutralLanguage>en-US</NeutralLanguage> <GenerateAssemblyVersionAttribute>False</GenerateAssemblyVersionAttribute> <GenerateAssemblyFileVersionAttribute>False</GenerateAssemblyFileVersionAttribute> <GenerateAssemblyInformationalVersionAttribute>False</GenerateAssemblyInformationalVersionAttribute> </PropertyGroup> <ItemGroup> <Compile Remove="Properties\AssemblyInfo.template.cs" /> </ItemGroup> <ItemGroup> <Compile Remove="Baml\KnownThings.gen.cs" /> </ItemGroup> <PropertyGroup Condition="'$(GITHUB_ACTIONS)' == 'true'"> <ContinuousIntegrationBuild>true</ContinuousIntegrationBuild> </PropertyGroup> <!-- Inject ILSpyUpdateAssemblyInfo as dependency of the GetPackageVersion target so Pack uses the generated version when evaluating project references. --> <PropertyGroup> <GetPackageVersionDependsOn> ILSpyUpdateAssemblyInfo; $(GetPackageVersionDependsOn) </GetPackageVersionDependsOn> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\ICSharpCode.Decompiler\ICSharpCode.Decompiler.csproj" /> </ItemGroup> <Target Name="ILSpyUpdateAssemblyInfo" AfterTargets="ResolveProjectReferences"> <ReadLinesFromFile ContinueOnError="true" File="..\VERSION"> <Output TaskParameter="Lines" PropertyName="PackageVersion" /> </ReadLinesFromFile> </Target> </Project>
ILSpy/ICSharpCode.BamlDecompiler/ICSharpCode.BamlDecompiler.csproj/0
{ "file_path": "ILSpy/ICSharpCode.BamlDecompiler/ICSharpCode.BamlDecompiler.csproj", "repo_id": "ILSpy", "token_count": 532 }
196
/* Copyright (c) 2015 Ki 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. */ using System; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Threading; using System.Xml.Linq; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.BamlDecompiler.Baml; using ICSharpCode.BamlDecompiler.Rewrite; namespace ICSharpCode.BamlDecompiler { public class XamlDecompiler { static readonly IRewritePass[] rewritePasses = new IRewritePass[] { new XClassRewritePass(), new MarkupExtensionRewritePass(), new AttributeRewritePass(), new ConnectionIdRewritePass(), new DocumentRewritePass(), }; private BamlDecompilerTypeSystem typeSystem; private BamlDecompilerSettings settings; private MetadataModule module; public BamlDecompilerSettings Settings { get { return settings; } set { settings = value; } } public CancellationToken CancellationToken { get; set; } public XamlDecompiler(string fileName, BamlDecompilerSettings settings) : this(CreateTypeSystemFromFile(fileName, settings), settings) { } public XamlDecompiler(string fileName, IAssemblyResolver assemblyResolver, BamlDecompilerSettings settings) : this(LoadPEFile(fileName, settings), assemblyResolver, settings) { } public XamlDecompiler(PEFile module, IAssemblyResolver assemblyResolver, BamlDecompilerSettings settings) : this(new BamlDecompilerTypeSystem(module, assemblyResolver), settings) { } public XamlDecompiler(BamlDecompilerTypeSystem typeSystem, BamlDecompilerSettings settings) { this.typeSystem = typeSystem ?? throw new ArgumentNullException(nameof(typeSystem)); this.settings = settings; this.module = typeSystem.MainModule; if (module.TypeSystemOptions.HasFlag(TypeSystemOptions.Uncached)) throw new ArgumentException("Cannot use an uncached type system in the decompiler."); } static PEFile LoadPEFile(string fileName, BamlDecompilerSettings settings) { return new PEFile( fileName, new FileStream(fileName, FileMode.Open, FileAccess.Read), streamOptions: PEStreamOptions.PrefetchEntireImage, metadataOptions: MetadataReaderOptions.None ); } static BamlDecompilerTypeSystem CreateTypeSystemFromFile(string fileName, BamlDecompilerSettings settings) { var file = LoadPEFile(fileName, settings); var resolver = new UniversalAssemblyResolver(fileName, settings.ThrowOnAssemblyResolveErrors, file.DetectTargetFrameworkId(), file.DetectRuntimePack(), PEStreamOptions.PrefetchMetadata, MetadataReaderOptions.None); return new BamlDecompilerTypeSystem(file, resolver); } public BamlDecompilationResult Decompile(Stream stream) { var ct = CancellationToken; var document = BamlReader.ReadDocument(stream, ct); var ctx = XamlContext.Construct(typeSystem, document, ct, settings); var handler = HandlerMap.LookupHandler(ctx.RootNode.Type); var elem = handler.Translate(ctx, ctx.RootNode, null); var xaml = new XDocument(); xaml.Add(elem.Xaml.Element); foreach (var pass in rewritePasses) { ct.ThrowIfCancellationRequested(); pass.Run(ctx, xaml); } var assemblyReferences = ctx.Baml.AssemblyIdMap.Select(a => a.Value.AssemblyFullName); var typeName = ctx.XClassNames.FirstOrDefault() is string s ? (FullTypeName?)new FullTypeName(s) : null; return new BamlDecompilationResult(xaml, typeName, assemblyReferences, ctx.GeneratedMembers); } } }
ILSpy/ICSharpCode.BamlDecompiler/XamlDecompiler.cs/0
{ "file_path": "ILSpy/ICSharpCode.BamlDecompiler/XamlDecompiler.cs", "repo_id": "ILSpy", "token_count": 1462 }
197
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team // // 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. using System; using System.CodeDom.Compiler; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using ICSharpCode.Decompiler.Tests.Helpers; using NUnit.Framework; namespace ICSharpCode.Decompiler.Tests { [TestFixture, Parallelizable(ParallelScope.All)] public class CorrectnessTestRunner { static readonly string TestCasePath = Tester.TestCasePath + "/Correctness"; [Test] public void AllFilesHaveTests() { var testNames = typeof(CorrectnessTestRunner).GetMethods() .Where(m => m.GetCustomAttributes(typeof(TestAttribute), false).Any()) .Select(m => m.Name) .ToArray(); foreach (var file in new DirectoryInfo(TestCasePath).EnumerateFiles()) { if (file.Extension == ".txt" || file.Extension == ".exe" || file.Extension == ".config") continue; var testName = Path.GetFileNameWithoutExtension(file.Name); Assert.That(testNames, Has.Member(testName)); } } static readonly CompilerOptions[] noMonoOptions = { CompilerOptions.None, CompilerOptions.Optimize, CompilerOptions.UseRoslyn1_3_2 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn1_3_2 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn2_10_0 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn3_11_0 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn1_3_2, CompilerOptions.Optimize | CompilerOptions.UseRoslyn1_3_2, CompilerOptions.UseRoslyn2_10_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0, CompilerOptions.UseRoslyn3_11_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0, CompilerOptions.UseRoslynLatest, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest, }; static readonly CompilerOptions[] net40OnlyOptions = { CompilerOptions.None, CompilerOptions.Optimize, CompilerOptions.UseRoslyn1_3_2 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn1_3_2 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn2_10_0 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn3_11_0 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40 }; static readonly CompilerOptions[] defaultOptions = { CompilerOptions.None, CompilerOptions.Optimize, CompilerOptions.UseRoslyn1_3_2 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn1_3_2 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn2_10_0 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn3_11_0 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn1_3_2, CompilerOptions.Optimize | CompilerOptions.UseRoslyn1_3_2, CompilerOptions.UseRoslyn2_10_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0, CompilerOptions.UseRoslyn3_11_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0, CompilerOptions.UseRoslynLatest, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest, CompilerOptions.UseMcs2_6_4, CompilerOptions.Optimize | CompilerOptions.UseMcs2_6_4, CompilerOptions.UseMcs5_23, CompilerOptions.Optimize | CompilerOptions.UseMcs5_23 }; static readonly CompilerOptions[] roslynOnlyOptions = { CompilerOptions.UseRoslyn1_3_2 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn1_3_2 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn2_10_0 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn3_11_0 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn1_3_2, CompilerOptions.Optimize | CompilerOptions.UseRoslyn1_3_2, CompilerOptions.UseRoslyn2_10_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0, CompilerOptions.UseRoslyn3_11_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0, CompilerOptions.UseRoslynLatest, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest, }; static readonly CompilerOptions[] roslyn2OrNewerOptions = { CompilerOptions.UseRoslyn2_10_0 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn3_11_0 | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0 | CompilerOptions.TargetNet40, CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.UseRoslyn2_10_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn2_10_0, CompilerOptions.UseRoslyn3_11_0, CompilerOptions.Optimize | CompilerOptions.UseRoslyn3_11_0, CompilerOptions.UseRoslynLatest, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest, }; static readonly CompilerOptions[] roslynLatestOnlyOptions = { CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest | CompilerOptions.TargetNet40, CompilerOptions.UseRoslynLatest, CompilerOptions.Optimize | CompilerOptions.UseRoslynLatest, }; [Test] public async Task Comparisons([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task Conversions([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task FloatingPointArithmetic([ValueSource(nameof(noMonoOptions))] CompilerOptions options, [Values(32, 64)] int bits) { // The behavior of the #1794 incorrect `(float)(double)val` cast only causes test failures // for some runtime+compiler combinations. if (bits == 32) options |= CompilerOptions.Force32Bit; // Mono is excluded because we never use it for the second pass, so the test ends up failing // due to some Mono vs. Roslyn compiler differences. await RunCS(options: options); } [Test] public async Task HelloWorld([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task ControlFlow([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task CompoundAssignment([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task PropertiesAndEvents([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task Switch([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task Using([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task Loops([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task NullableTests([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task Generics([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task ValueTypeCall([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task InitializerTests([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task DecimalFields([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task UndocumentedExpressions([ValueSource(nameof(noMonoOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task Uninit([ValueSource(nameof(noMonoOptions))] CompilerOptions options) { await RunVB(options: options); } [Test] public async Task MemberLookup([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task OverloadResolution([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task ExpressionTrees([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task NullPropagation([ValueSource(nameof(roslynOnlyOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task DeconstructionTests([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task BitNot([Values(false, true)] bool force32Bit) { CompilerOptions compiler = CompilerOptions.UseDebug; AssemblerOptions asm = AssemblerOptions.None; if (force32Bit) { compiler |= CompilerOptions.Force32Bit; asm |= AssemblerOptions.Force32Bit; } await RunIL("BitNot.il", compiler, asm); } [Test] public async Task Jmp() { await RunIL("Jmp.il"); } [Test] public async Task StackTests() { // IL contains .corflags = 32BITREQUIRED await RunIL("StackTests.il", CompilerOptions.Force32Bit, AssemblerOptions.Force32Bit); } [Test] public async Task StackTypes([Values(false, true)] bool force32Bit) { CompilerOptions compiler = CompilerOptions.UseRoslynLatest | CompilerOptions.UseDebug; AssemblerOptions asm = AssemblerOptions.None; if (force32Bit) { compiler |= CompilerOptions.Force32Bit; asm |= AssemblerOptions.Force32Bit; } await RunIL("StackTypes.il", compiler, asm); } [Test] public async Task UnsafeCode([ValueSource(nameof(defaultOptions))] CompilerOptions options) { if (options.HasFlag(CompilerOptions.UseMcs2_6_4)) { Assert.Ignore("Decompiler bug with mono!"); } await RunCS(options: options); } [Test] public async Task ConditionalAttr([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task TrickyTypes([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task Capturing([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task YieldReturn([ValueSource(nameof(defaultOptions))] CompilerOptions options) { if ((options & CompilerOptions.UseMcsMask) != 0) { Assert.Ignore("Decompiler bug with mono!"); } await RunCS(options: options); } [Test] public async Task Async([ValueSource(nameof(noMonoOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task LINQRaytracer([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task StringConcat([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task DynamicTests([ValueSource(nameof(noMonoOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task MiniJSON([ValueSource(nameof(defaultOptions))] CompilerOptions options) { await RunCS(options: options); } [Test] public async Task ComInterop([ValueSource(nameof(net40OnlyOptions))] CompilerOptions options) { await RunCS(options: options); } async Task RunCS([CallerMemberName] string testName = null, CompilerOptions options = CompilerOptions.UseDebug) { if ((options & CompilerOptions.UseRoslynMask) != 0 && (options & CompilerOptions.TargetNet40) == 0) options |= CompilerOptions.UseTestRunner; string testFileName = testName + ".cs"; string testOutputFileName = testName + Tester.GetSuffix(options) + ".exe"; CompilerResults outputFile = null, decompiledOutputFile = null; try { outputFile = await Tester.CompileCSharp(Path.Combine(TestCasePath, testFileName), options, outputFileName: Path.Combine(TestCasePath, testOutputFileName)).ConfigureAwait(false); string decompiledCodeFile = await Tester.DecompileCSharp(outputFile.PathToAssembly, Tester.GetSettings(options)).ConfigureAwait(false); if ((options & CompilerOptions.UseMcsMask) != 0) { // For second pass, use roslyn instead of mcs. // mcs has some compiler bugs that cause it to not accept ILSpy-generated code, // for example when there's unreachable code due to other compiler bugs in the first mcs run. options &= ~CompilerOptions.UseMcsMask; options |= CompilerOptions.UseRoslynLatest; // Also, add an .exe.config so that we consistently use the .NET 4.x runtime. File.WriteAllText(outputFile.PathToAssembly + ".config", @"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <startup> <supportedRuntime version=""v4.0"" sku="".NETFramework,Version=v4.0,Profile=Client"" /> </startup> </configuration>"); options |= CompilerOptions.TargetNet40; } decompiledOutputFile = await Tester.CompileCSharp(decompiledCodeFile, options).ConfigureAwait(false); await Tester.RunAndCompareOutput(testFileName, outputFile.PathToAssembly, decompiledOutputFile.PathToAssembly, decompiledCodeFile, (options & CompilerOptions.UseTestRunner) != 0, (options & CompilerOptions.Force32Bit) != 0); Tester.RepeatOnIOError(() => File.Delete(decompiledCodeFile)); } finally { if (outputFile != null) outputFile.DeleteTempFiles(); if (decompiledOutputFile != null) decompiledOutputFile.DeleteTempFiles(); } } async Task RunVB([CallerMemberName] string testName = null, CompilerOptions options = CompilerOptions.UseDebug) { options |= CompilerOptions.ReferenceVisualBasic; if ((options & CompilerOptions.UseRoslynMask) != 0) options |= CompilerOptions.UseTestRunner; string testFileName = testName + ".vb"; string testOutputFileName = testName + Tester.GetSuffix(options) + ".exe"; CompilerResults outputFile = null, decompiledOutputFile = null; try { outputFile = await Tester.CompileVB(Path.Combine(TestCasePath, testFileName), options, outputFileName: Path.Combine(TestCasePath, testOutputFileName)).ConfigureAwait(false); string decompiledCodeFile = await Tester.DecompileCSharp(outputFile.PathToAssembly, Tester.GetSettings(options)).ConfigureAwait(false); decompiledOutputFile = await Tester.CompileCSharp(decompiledCodeFile, options).ConfigureAwait(false); await Tester.RunAndCompareOutput(testFileName, outputFile.PathToAssembly, decompiledOutputFile.PathToAssembly, decompiledCodeFile, (options & CompilerOptions.UseTestRunner) != 0, (options & CompilerOptions.Force32Bit) != 0); Tester.RepeatOnIOError(() => File.Delete(decompiledCodeFile)); } finally { if (outputFile != null) outputFile.DeleteTempFiles(); if (decompiledOutputFile != null) decompiledOutputFile.DeleteTempFiles(); } } async Task RunIL(string testFileName, CompilerOptions options = CompilerOptions.UseDebug, AssemblerOptions asmOptions = AssemblerOptions.None) { string outputFile = null; CompilerResults decompiledOutputFile = null; bool optionsForce32Bit = options.HasFlag(CompilerOptions.Force32Bit); bool asmOptionsForce32Bit = asmOptions.HasFlag(AssemblerOptions.Force32Bit); Assert.That(asmOptionsForce32Bit, Is.EqualTo(optionsForce32Bit), "Inconsistent architecture."); try { options |= CompilerOptions.UseTestRunner; outputFile = await Tester.AssembleIL(Path.Combine(TestCasePath, testFileName), asmOptions).ConfigureAwait(false); string decompiledCodeFile = await Tester.DecompileCSharp(outputFile, Tester.GetSettings(options)).ConfigureAwait(false); decompiledOutputFile = await Tester.CompileCSharp(decompiledCodeFile, options).ConfigureAwait(false); await Tester.RunAndCompareOutput(testFileName, outputFile, decompiledOutputFile.PathToAssembly, decompiledCodeFile, (options & CompilerOptions.UseTestRunner) != 0, (options & CompilerOptions.Force32Bit) != 0).ConfigureAwait(false); Tester.RepeatOnIOError(() => File.Delete(decompiledCodeFile)); } finally { if (decompiledOutputFile != null) decompiledOutputFile.DeleteTempFiles(); } } } }
ILSpy/ICSharpCode.Decompiler.Tests/CorrectnessTestRunner.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/CorrectnessTestRunner.cs", "repo_id": "ILSpy", "token_count": 6655 }
198
// Copyright (c) 2016 Daniel Grunwald // // 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. using System; using System.Diagnostics; using System.IO; using System.Reflection.PortableExecutable; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using CliWrap; using ICSharpCode.Decompiler.CSharp; using ICSharpCode.Decompiler.CSharp.ProjectDecompiler; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.Tests.Helpers; using NUnit.Framework; namespace ICSharpCode.Decompiler.Tests { [TestFixture, Parallelizable(ParallelScope.All)] public class RoundtripAssembly { public static readonly string TestDir = Path.GetFullPath(Path.Combine(Tester.TestCasePath, "../../ILSpy-tests")); static readonly string nunit = Path.Combine(TestDir, "nunit", "nunit3-console.exe"); [Test] public async Task Cecil_net45() { await RunWithTest("Mono.Cecil-net45", "Mono.Cecil.dll", "Mono.Cecil.Tests.dll"); } [Test] public async Task NewtonsoftJson_net45() { await RunWithTest("Newtonsoft.Json-net45", "Newtonsoft.Json.dll", "Newtonsoft.Json.Tests.dll"); } [Test] public async Task NewtonsoftJson_pcl_debug() { try { await RunWithTest("Newtonsoft.Json-pcl-debug", "Newtonsoft.Json.dll", "Newtonsoft.Json.Tests.dll", useOldProjectFormat: true); } catch (CompilationFailedException) { Assert.Ignore("Cannot yet re-compile PCL projects."); } } [Test] public async Task NRefactory_CSharp() { await RunWithTest("NRefactory", "ICSharpCode.NRefactory.CSharp.dll", "ICSharpCode.NRefactory.Tests.dll"); } [Test] public async Task ICSharpCode_Decompiler() { await RunOnly("ICSharpCode.Decompiler", "ICSharpCode.Decompiler.dll"); } [Test] public async Task ImplicitConversions() { await RunWithOutput("Random Tests\\TestCases", "ImplicitConversions.exe"); } [Test] public async Task ImplicitConversions_32() { await RunWithOutput("Random Tests\\TestCases", "ImplicitConversions_32.exe"); } [Test] public async Task ExplicitConversions() { await RunWithOutput("Random Tests\\TestCases", "ExplicitConversions.exe", LanguageVersion.CSharp8_0); } [Test] public async Task ExplicitConversions_32() { await RunWithOutput("Random Tests\\TestCases", "ExplicitConversions_32.exe", LanguageVersion.CSharp8_0); } [Test] public async Task ExplicitConversions_With_NativeInts() { await RunWithOutput("Random Tests\\TestCases", "ExplicitConversions.exe", LanguageVersion.CSharp9_0); } [Test] public async Task ExplicitConversions_32_With_NativeInts() { await RunWithOutput("Random Tests\\TestCases", "ExplicitConversions_32.exe", LanguageVersion.CSharp9_0); } [Test] public async Task Random_TestCase_1() { await RunWithOutput("Random Tests\\TestCases", "TestCase-1.exe", LanguageVersion.CSharp8_0); } [Test] [Ignore("See https://github.com/icsharpcode/ILSpy/issues/2541 - Waiting for https://github.com/dotnet/roslyn/issues/45929")] public async Task Random_TestCase_1_With_NativeInts() { await RunWithOutput("Random Tests\\TestCases", "TestCase-1.exe", LanguageVersion.CSharp9_0); } // Let's limit the roundtrip tests to C# 8.0 for now; because 9.0 is still in preview // and the generated project doesn't build as-is. const LanguageVersion defaultLanguageVersion = LanguageVersion.CSharp8_0; async Task RunWithTest(string dir, string fileToRoundtrip, string fileToTest, LanguageVersion languageVersion = defaultLanguageVersion, string keyFile = null, bool useOldProjectFormat = false) { await RunInternal(dir, fileToRoundtrip, outputDir => RunTest(outputDir, fileToTest).GetAwaiter().GetResult(), languageVersion, snkFilePath: keyFile, useOldProjectFormat: useOldProjectFormat); } async Task RunWithOutput(string dir, string fileToRoundtrip, LanguageVersion languageVersion = defaultLanguageVersion) { string inputDir = Path.Combine(TestDir, dir); await RunInternal(dir, fileToRoundtrip, outputDir => Tester.RunAndCompareOutput(fileToRoundtrip, Path.Combine(inputDir, fileToRoundtrip), Path.Combine(outputDir, fileToRoundtrip)).GetAwaiter().GetResult(), languageVersion); } async Task RunOnly(string dir, string fileToRoundtrip, LanguageVersion languageVersion = defaultLanguageVersion) { await RunInternal(dir, fileToRoundtrip, outputDir => { }, languageVersion); } async Task RunInternal(string dir, string fileToRoundtrip, Action<string> testAction, LanguageVersion languageVersion, string snkFilePath = null, bool useOldProjectFormat = false) { if (!Directory.Exists(TestDir)) { Assert.Ignore($"Assembly-roundtrip test ignored: test directory '{TestDir}' needs to be checked out separately." + Environment.NewLine + $"git clone https://github.com/icsharpcode/ILSpy-tests \"{TestDir}\""); } string inputDir = Path.Combine(TestDir, dir); string decompiledDir = inputDir + "-decompiled"; string outputDir = inputDir + "-output"; if (inputDir.EndsWith("TestCases")) { // make sure output dir names are unique so that we don't get trouble due to parallel test execution decompiledDir += Path.GetFileNameWithoutExtension(fileToRoundtrip) + "_" + languageVersion.ToString(); outputDir += Path.GetFileNameWithoutExtension(fileToRoundtrip) + "_" + languageVersion.ToString(); } ClearDirectory(decompiledDir); ClearDirectory(outputDir); string projectFile = null; foreach (string file in Directory.EnumerateFiles(inputDir, "*", SearchOption.AllDirectories)) { if (!file.StartsWith(inputDir + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) { Assert.Fail($"Unexpected file name: {file}"); } string relFile = file.Substring(inputDir.Length + 1); Directory.CreateDirectory(Path.Combine(outputDir, Path.GetDirectoryName(relFile))); if (relFile.Equals(fileToRoundtrip, StringComparison.OrdinalIgnoreCase)) { Console.WriteLine($"Decompiling {fileToRoundtrip}..."); Stopwatch w = Stopwatch.StartNew(); using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read)) { PEFile module = new PEFile(file, fileStream, PEStreamOptions.PrefetchEntireImage); var resolver = new TestAssemblyResolver(file, inputDir, module.Metadata.DetectTargetFrameworkId()); resolver.AddSearchDirectory(inputDir); resolver.RemoveSearchDirectory("."); // use a fixed GUID so that we can diff the output between different ILSpy runs without spurious changes var projectGuid = Guid.Parse("{127C83E4-4587-4CF9-ADCA-799875F3DFE6}"); var settings = new DecompilerSettings(languageVersion); if (useOldProjectFormat) { settings.UseSdkStyleProjectFormat = false; } var decompiler = new TestProjectDecompiler(projectGuid, resolver, resolver, settings); if (snkFilePath != null) { decompiler.StrongNameKeyFile = Path.Combine(inputDir, snkFilePath); } decompiler.DecompileProject(module, decompiledDir); Console.WriteLine($"Decompiled {fileToRoundtrip} in {w.Elapsed.TotalSeconds:f2}"); projectFile = Path.Combine(decompiledDir, module.Name + ".csproj"); } } else { File.Copy(file, Path.Combine(outputDir, relFile)); } } Assert.That(projectFile, Is.Not.Null, $"Could not find {fileToRoundtrip}"); await Compile(projectFile, outputDir); testAction(outputDir); } static void ClearDirectory(string dir) { Directory.CreateDirectory(dir); foreach (string subdir in Directory.EnumerateDirectories(dir)) { for (int attempt = 0; ; attempt++) { try { Directory.Delete(subdir, true); break; } catch (IOException) { if (attempt >= 10) throw; Thread.Sleep(100); } } } foreach (string file in Directory.EnumerateFiles(dir)) { File.Delete(file); } } static async Task Compile(string projectFile, string outputDir) { Regex errorRegex = new Regex(@"^[\w\d.\\-]+\(\d+,\d+\):"); string suffix = $" [{projectFile}]"; var command = Cli.Wrap(await Tester.FindMSBuild()) .WithArguments($"/nologo /v:minimal /restore /p:OutputPath=\"{outputDir}\" \"{projectFile}\"") .WithValidation(CommandResultValidation.None) .WithStandardOutputPipe(PipeTarget.ToDelegate(PrintLine)); Console.WriteLine($"\"{command.TargetFilePath}\" {command.Arguments}"); var result = await command.ExecuteAsync().ConfigureAwait(false); if (result.ExitCode != 0) throw new CompilationFailedException($"Compilation of {Path.GetFileName(projectFile)} failed"); void PrintLine(string line) { if (line.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) { line = line.Substring(0, line.Length - suffix.Length); } Match m = errorRegex.Match(line); if (m.Success) { // Make path absolute so that it gets hyperlinked line = Path.GetDirectoryName(projectFile) + Path.DirectorySeparatorChar + line; } Console.WriteLine(line); } } static async Task RunTest(string outputDir, string fileToTest) { var command = Cli.Wrap(nunit) .WithWorkingDirectory(outputDir) .WithArguments($"\"{fileToTest}\"") .WithValidation(CommandResultValidation.None) .WithStandardOutputPipe(PipeTarget.ToDelegate(Console.WriteLine)); Console.WriteLine($"\"{command.TargetFilePath}\" {command.Arguments}"); var result = await command.ExecuteAsync().ConfigureAwait(false); if (result.ExitCode != 0) throw new TestRunFailedException($"Test execution of {Path.GetFileName(fileToTest)} failed"); } class TestProjectDecompiler : WholeProjectDecompiler { public TestProjectDecompiler(Guid projecGuid, IAssemblyResolver resolver, AssemblyReferenceClassifier assemblyReferenceClassifier, DecompilerSettings settings) : base(settings, projecGuid, resolver, assemblyReferenceClassifier, debugInfoProvider: null) { } } class CompilationFailedException : Exception { public CompilationFailedException(string message) : base(message) { } } class TestRunFailedException : Exception { public TestRunFailedException(string message) : base(message) { } } } }
ILSpy/ICSharpCode.Decompiler.Tests/RoundtripAssembly.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/RoundtripAssembly.cs", "repo_id": "ILSpy", "token_count": 4074 }
199
using System; namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness { class DynamicTests { delegate void RefAction<T>(ref T arg); static void Main(string[] args) { PrintResult((ref dynamic x) => x = x + 2.0, 5.0); PrintResult((ref dynamic x) => x = x + 2.0, 5); PrintResult((ref dynamic x) => x = x + 2, 5.0); PrintResult((ref dynamic x) => x = x + 2, 5); PrintResult((ref dynamic x) => x = x - 2.0, 5.0); PrintResult((ref dynamic x) => x = x - 2.0, 5); PrintResult((ref dynamic x) => x = x - 2, 5.0); PrintResult((ref dynamic x) => x = x - 2, 5); PrintResult((ref dynamic x) => x = x * 2.0, 5.0); PrintResult((ref dynamic x) => x = x * 2.0, 5); PrintResult((ref dynamic x) => x = x * 2, 5.0); PrintResult((ref dynamic x) => x = x * 2, 5); PrintResult((ref dynamic x) => x = x / 2.0, 5.0); PrintResult((ref dynamic x) => x = x / 2.0, 5); PrintResult((ref dynamic x) => x = x / 2, 5.0); PrintResult((ref dynamic x) => x = x / 2, 5); } private static void PrintResult(RefAction<dynamic> p, dynamic arg) { p(ref arg); Console.WriteLine(arg); } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/DynamicTests.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/DynamicTests.cs", "repo_id": "ILSpy", "token_count": 478 }
200
.assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly StackTests { .hash algorithm 0x00008004 .ver 1:0:4059:39717 } .module StackTests.exe .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000003 // ILONLY 32BITREQUIRED .class private auto ansi beforefieldinit StackTests.Program extends [mscorlib]System.Object { .method public hidebysig static void Main(string[] args) cil managed { .entrypoint .maxstack 8 ldc.i4.0 call string StackTests.Program::Test1(bool cond) call void [mscorlib]System.Console::WriteLine(string) // false ldc.i4.1 call string StackTests.Program::Test1(bool cond) call void [mscorlib]System.Console::WriteLine(string) // true ldc.i4.0 ldc.i4.0 ldc.i4.0 call int32 StackTests.Program::Test2(int32 switch1, int32 br1, int32 br2) call void [mscorlib]System.Console::WriteLine(int32) // 11 ldc.i4.0 ldc.i4.1 ldc.i4.0 call int32 StackTests.Program::Test2(int32 switch1, int32 br1, int32 br2) call void [mscorlib]System.Console::WriteLine(int32) // 21 ldc.i4.1 ldc.i4.1 ldc.i4.1 call int32 StackTests.Program::Test2(int32 switch1, int32 br1, int32 br2) call void [mscorlib]System.Console::WriteLine(int32) // 32 ldc.i4.2 ldc.i4.1 ldc.i4.0 call int32 StackTests.Program::Test2(int32 switch1, int32 br1, int32 br2) call void [mscorlib]System.Console::WriteLine(int32) // 23 ret } .method public hidebysig static string Test1(bool cond) cil managed { ldarg.0 brtrue TRUE FALSE: ldstr "false" br EXIT TRUE: ldstr "true" EXIT: ret } .method public hidebysig static int32 Test2(int32 switch1, int32 br1, int32 br2) cil managed { ldarg.0 switch (ENTRY1, ENTRY2, ENTRY3) ldc.i4.0 ret ENTRY1: ldc.i4.1 br BRANCH1 ENTRY2: ldc.i4.2 br BRANCH1 ENTRY3: ldc.i4.3 br BRANCH2 BRANCH1: ldarg.1 brtrue BRANCH2 EXIT1: ldc.i4 10 add ret BRANCH2: ldarg.2 brtrue.s EXIT3 EXIT2: ldc.i4 20 add ret EXIT3: ldc.i4 30 add ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor } // end of class StackTests.Program // =============================================================
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/StackTests.il/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/StackTests.il", "repo_id": "ILSpy", "token_count": 1147 }
201
// C:\Users\Siegfried\Documents\Visual Studio 2017\Projects\ConsoleApp13\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe // ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null // Global type: <Module> // Entry point: Program.main // Architecture: AnyCPU (32-bit preferred) // Runtime: .NET 4.0 using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.FSharp.Collections; using Microsoft.FSharp.Core; using Microsoft.FSharp.Core.CompilerServices; [assembly: FSharpInterfaceDataVersion(2, 0, 0)] [assembly: AssemblyTitle("ConsoleApplication1")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConsoleApplication1")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("e0674ff5-5e8f-4d4e-a88f-e447192454c7")] [CompilationMapping(SourceConstructFlags.Module)] public static class Program { [Serializable] [SpecialName] [CompilationMapping(SourceConstructFlags.Closure)] internal sealed class disposable_00403 : IDisposable { private void System_002DIDisposable_002DDispose() { } void IDisposable.Dispose() { //ILSpy generated this explicit interface implementation from .override directive in System-IDisposable-Dispose this.System_002DIDisposable_002DDispose(); } } [Serializable] [SpecialName] [CompilationMapping(SourceConstructFlags.Closure)] internal sealed class getSeq_00405 : GeneratedSequenceBase<int> { [DebuggerNonUserCode] [DebuggerBrowsable(DebuggerBrowsableState.Never)] [CompilerGenerated] public int pc; [DebuggerNonUserCode] [DebuggerBrowsable(DebuggerBrowsableState.Never)] [CompilerGenerated] public int current; public getSeq_00405(int pc, int current) { this.pc = pc; this.current = current; base._002Ector(); } public override int GenerateNext(ref IEnumerable<int> next) { switch (pc) { default: pc = 1; current = 1; return 1; case 1: pc = 2; break; case 2: break; } current = 0; return 0; } public override void Close() { pc = 2; } public bool get_CheckClose() { switch (pc) { default: return false; case 0: case 2: return false; } } [DebuggerNonUserCode] [CompilerGenerated] public int get_LastGenerated() { return current; } [DebuggerNonUserCode] [CompilerGenerated] public override IEnumerator<int> GetFreshEnumerator() { return new getSeq_00405(0, 0); } } public static IDisposable disposable() { return new disposable_00403(); } public static IEnumerable<int> getSeq() { return new getSeq_00405(0, 0); } public static FSharpList<int> getList() { return FSharpList<int>.Cons(1, FSharpList<int>.Empty); } public static int[] getArray() { return new int[1] { 1 }; } [EntryPoint] public static int main(string[] argv) { IDisposable disposable; using (Program.disposable()) { Console.WriteLine("Hello 1"); disposable = Program.disposable(); } using (disposable) { IEnumerable<int> seq = getSeq(); foreach (int item in seq) { Console.WriteLine(item); } FSharpList<int> fSharpList = getList(); for (FSharpList<int> tailOrNull = fSharpList.TailOrNull; tailOrNull != null; tailOrNull = fSharpList.TailOrNull) { int headOrDefault = fSharpList.HeadOrDefault; Console.WriteLine(headOrDefault); fSharpList = tailOrNull; } int[] array = getArray(); foreach (int value in array) { Console.WriteLine(value); } return 0; } } } namespace _003CStartupCode_0024ConsoleApplication1_003E { internal static class _0024AssemblyInfo { } internal static class _0024Program { } } namespace _003CStartupCode_0024ConsoleApplication1_003E._0024.NETFramework_002CVersion_003Dv4._6._1 { internal static class AssemblyAttributes { } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/FSharpLoops_Debug.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/FSharpLoops_Debug.cs", "repo_id": "ILSpy", "token_count": 1601 }
202
.class public auto ansi sealed EvType extends [mscorlib]System.MulticastDelegate { // Methods not included. Just the run of the mill ctor + {Begin|End}?Invoke } .class public auto ansi serializable beforefieldinit OwningClass { .field class EvType EvName .event EvType EvName { .addon instance void OwningClass::add_EvName(class EvType) .removeon instance void OwningClass::remove_EvName(class EvType) } .method public hidebysig specialname instance void add_EvName ( class EvType 'value' ) cil managed { .maxstack 3 .locals init ( [0] class EvType, [1] class EvType ) IL_0000: ldarg.0 IL_0001: ldfld class EvType OwningClass::EvName IL_0006: stloc.0 // loop start (head: IL_0007) IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldarg.0 IL_000a: ldflda class EvType OwningClass::EvName IL_000f: ldloc.1 IL_0010: ldarg.1 IL_0011: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_0016: castclass EvType IL_001b: ldloc.0 IL_001c: call !!0 [mscorlib]System.Threading.Interlocked::CompareExchange<class EvType>(!!0&, !!0, !!0) IL_0021: stloc.0 IL_0022: ldloc.0 IL_0023: ldloc.1 IL_0024: bne.un IL_0007 // end loop IL_0029: ret } // end of method OwningClass::add_EvName .method public hidebysig specialname instance void remove_EvName ( class EvType 'value' ) cil managed { .maxstack 3 .locals init ( [0] class EvType, [1] class EvType ) IL_0000: ldarg.0 IL_0001: ldfld class EvType OwningClass::EvName IL_0006: stloc.0 // loop start (head: IL_0007) IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldarg.0 IL_000a: ldflda class EvType OwningClass::EvName IL_000f: ldloc.1 IL_0010: ldarg.1 IL_0011: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_0016: castclass EvType IL_001b: ldloc.0 IL_001c: call !!0 [mscorlib]System.Threading.Interlocked::CompareExchange<class EvType>(!!0&, !!0, !!0) IL_0021: stloc.0 IL_0022: ldloc.0 IL_0023: ldloc.1 IL_0024: bne.un IL_0007 // end loop IL_0029: ret } // end of method OwningClass::remove_EvName } // end of class OwningClass
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1145.il/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1145.il", "repo_id": "ILSpy", "token_count": 961 }
203
using System; namespace ICSharpCode.Decompiler.Tests.TestCases.ILPretty { internal class Issue1918 { public static Guid[] NullVal; public unsafe void ProblemFunction(Guid[] A_0, int A_1) { fixed (Guid* ptr = A_0) { void* ptr2 = ptr; UIntPtr* ptr3 = (UIntPtr*)((byte*)ptr2 - sizeof(UIntPtr)); UIntPtr uIntPtr = *ptr3; try { *ptr3 = (UIntPtr)(ulong)A_1; } finally { *ptr3 = uIntPtr; } } fixed (Guid[] ptr = NullVal) { } } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1918.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1918.cs", "repo_id": "ILSpy", "token_count": 264 }
204
namespace ICSharpCode.Decompiler.Tests.TestCases.ILPretty { internal class Issue959 { public void Test(bool arg) { if (!arg && arg) { } } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue959.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue959.cs", "repo_id": "ILSpy", "token_count": 78 }
205
<?xml version="1.0" encoding="utf-8"?> <symbols> <files> <file id="1" name="ICSharpCode.Decompiler.Tests.TestCases.PdbGen\ForLoopTests.cs" language="C#" checksumAlgorithm="SHA256"><![CDATA[using System; namespace ICSharpCode.Decompiler.Tests.TestCases.PdbGen; public class ForLoopTests { public static void SimplePrintLoop(string[] args) { for (int i = 0; i < args.Length; i++) { Console.WriteLine(args[i]); } } public static void SimplePrintLoopWithCondition(string[] args) { for (int i = 0; i < args.Length; i++) { if (i % 2 != 0) { Console.WriteLine(args[i]); } } } } ]]></file> </files> <methods> <method containingType="ICSharpCode.Decompiler.Tests.TestCases.PdbGen.ForLoopTests" name="SimplePrintLoop" parameterNames="args" token="0x6000001"> <sequencePoints> <entry offset="0x0" startLine="9" startColumn="9" endLine="9" endColumn="18" document="1" /> <entry offset="0x2" hidden="true" document="1" /> <entry offset="0x4" startLine="11" startColumn="5" endLine="11" endColumn="32" document="1" /> <entry offset="0xc" startLine="9" startColumn="37" endLine="9" endColumn="40" document="1" /> <entry offset="0x10" startLine="9" startColumn="20" endLine="9" endColumn="35" document="1" /> <entry offset="0x16" startLine="13" startColumn="3" endLine="13" endColumn="4" document="1" /> </sequencePoints> <scope startOffset="0x0" endOffset="0x17"> <scope startOffset="0x0" endOffset="0x16"> <local name="i" il_index="0" il_start="0x0" il_end="0x16" attributes="0" /> </scope> </scope> </method> <method containingType="ICSharpCode.Decompiler.Tests.TestCases.PdbGen.ForLoopTests" name="SimplePrintLoopWithCondition" parameterNames="args" token="0x6000002"> <sequencePoints> <entry offset="0x0" startLine="17" startColumn="9" endLine="17" endColumn="18" document="1" /> <entry offset="0x2" hidden="true" document="1" /> <entry offset="0x4" startLine="19" startColumn="5" endLine="19" endColumn="20" document="1" /> <entry offset="0x9" startLine="21" startColumn="6" endLine="21" endColumn="33" document="1" /> <entry offset="0x11" startLine="17" startColumn="37" endLine="17" endColumn="40" document="1" /> <entry offset="0x15" startLine="17" startColumn="20" endLine="17" endColumn="35" document="1" /> <entry offset="0x1b" startLine="24" startColumn="3" endLine="24" endColumn="4" document="1" /> </sequencePoints> <scope startOffset="0x0" endOffset="0x1c"> <scope startOffset="0x0" endOffset="0x1b"> <local name="i" il_index="0" il_start="0x0" il_end="0x1b" attributes="0" /> </scope> </scope> </method> </methods> <method-spans> <method declaringType="ICSharpCode.Decompiler.Tests.TestCases.PdbGen.ForLoopTests" methodName="SimplePrintLoop" parameterNames="args" token="0x6000001"> <document startLine="9" endLine="13" /> </method> <method declaringType="ICSharpCode.Decompiler.Tests.TestCases.PdbGen.ForLoopTests" methodName="SimplePrintLoopWithCondition" parameterNames="args" token="0x6000002"> <document startLine="17" endLine="24" /> </method> </method-spans> </symbols>
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/PdbGen/ForLoopTests.xml/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/PdbGen/ForLoopTests.xml", "repo_id": "ILSpy", "token_count": 1345 }
206
using System; using System.Collections; using System.Collections.Generic; namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty { public class CS9_ExtensionGetEnumerator { public class NonGeneric { } public class Generic<T> { } public void Test(NonGeneric c) { foreach (object item in c) { Console.WriteLine(item); } } public void Test(Generic<int> c) { foreach (int item in c) { Console.WriteLine(item); } } #if !NET40 public async void TestAsync(Generic<int> c) { await foreach (int item in c) { Console.WriteLine(item); } } #endif } public static class CS9_ExtensionGetEnumerator_Ext { public static IEnumerator GetEnumerator(this CS9_ExtensionGetEnumerator.NonGeneric c) { throw null; } public static IEnumerator<T> GetEnumerator<T>(this CS9_ExtensionGetEnumerator.Generic<T> c) { throw null; } #if !NET40 public static IAsyncEnumerator<T> GetAsyncEnumerator<T>(this CS9_ExtensionGetEnumerator.Generic<T> c) { throw null; } #endif } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/CS9_ExtensionGetEnumerator.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/CS9_ExtensionGetEnumerator.cs", "repo_id": "ILSpy", "token_count": 452 }
207
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team // // 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. using System; namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty { internal class EnumTests { public enum SimpleEnum { Item1, Item2 } public enum OutOfOrderMembers { Item1 = 1, Item0 = 0 } public enum EnumSkippedItemTest { Item0 = 0, Item2 = 2 } public enum EnumDuplicateItemTest { Item0 = 0, Item1 = 1, Item2A = 2, Item2B = 2 } public enum LongBasedEnum : long { Item1, Item2 } public enum LongWithInitializers : long { Item1 = 0L, Item2 = 20L, Item3 = 21L } public enum ShortWithInitializers : short { Item1 = 0, Item2 = 20, Item3 = 21 } public enum ByteWithInitializers : byte { Item1 = 0, Item2 = 20, Item3 = 21 } [Flags] public enum SimpleFlagsEnum { None = 0, Item1 = 1, Item2 = 2, Item3 = 4, All = 7 } [Flags] public enum NegativeValueWithFlags { Value = -2147483647 } public enum NegativeValueWithoutFlags { Value = -2147483647 } public AttributeTargets SingleEnumValue() { return AttributeTargets.Class; } public AttributeTargets TwoEnumValuesOr() { return AttributeTargets.Class | AttributeTargets.Method; } public AttributeTargets ThreeEnumValuesOr() { return AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Parameter; } public AttributeTargets UnknownEnumValue() { return (AttributeTargets)1000000; } public AttributeTargets EnumAllValue() { return AttributeTargets.All; } public AttributeTargets EnumZeroValue() { return (AttributeTargets)0; } public object PreservingTypeWhenBoxed() { return AttributeTargets.Delegate; } public object PreservingTypeWhenBoxedTwoEnum() { return AttributeTargets.Class | AttributeTargets.Delegate; } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/EnumTests.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/EnumTests.cs", "repo_id": "ILSpy", "token_count": 1104 }
208
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team // // 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. using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty { public class Loops { #region foreach public class CustomClassEnumerator { public object Current { get { throw new NotImplementedException(); } } public bool MoveNext() { throw new NotImplementedException(); } public void Reset() { throw new NotImplementedException(); } public CustomClassEnumerator GetEnumerator() { return this; } } [StructLayout(LayoutKind.Sequential, Size = 1)] public struct CustomStructEnumerator { public object Current { get { throw new NotImplementedException(); } } public bool MoveNext() { throw new NotImplementedException(); } public void Reset() { throw new NotImplementedException(); } public CustomStructEnumerator GetEnumerator() { return this; } } public class CustomClassEnumerator<T> { public T Current { get { throw new NotImplementedException(); } } public void Dispose() { throw new NotImplementedException(); } public bool MoveNext() { throw new NotImplementedException(); } public void Reset() { throw new NotImplementedException(); } public CustomClassEnumerator<T> GetEnumerator() { return this; } } [StructLayout(LayoutKind.Sequential, Size = 1)] public struct CustomStructEnumerator<T> { public T Current { get { throw new NotImplementedException(); } } public void Dispose() { throw new NotImplementedException(); } public bool MoveNext() { throw new NotImplementedException(); } public void Reset() { throw new NotImplementedException(); } public CustomStructEnumerator<T> GetEnumerator() { return this; } } public class CustomClassEnumeratorWithIDisposable : IDisposable { public object Current { get { throw new NotImplementedException(); } } public void Dispose() { throw new NotImplementedException(); } public bool MoveNext() { throw new NotImplementedException(); } public void Reset() { throw new NotImplementedException(); } public CustomClassEnumeratorWithIDisposable GetEnumerator() { return this; } } [StructLayout(LayoutKind.Sequential, Size = 1)] public struct CustomStructEnumeratorWithIDisposable : IDisposable { public object Current { get { throw new NotImplementedException(); } } public void Dispose() { throw new NotImplementedException(); } public bool MoveNext() { throw new NotImplementedException(); } public void Reset() { throw new NotImplementedException(); } public CustomStructEnumeratorWithIDisposable GetEnumerator() { return this; } } public class CustomClassEnumeratorWithIDisposable<T> : IDisposable { public T Current { get { throw new NotImplementedException(); } } public void Dispose() { throw new NotImplementedException(); } public bool MoveNext() { throw new NotImplementedException(); } public void Reset() { throw new NotImplementedException(); } public CustomClassEnumeratorWithIDisposable<T> GetEnumerator() { return this; } } [StructLayout(LayoutKind.Sequential, Size = 1)] public struct CustomStructEnumeratorWithIDisposable<T> : IDisposable { public T Current { get { throw new NotImplementedException(); } } public void Dispose() { throw new NotImplementedException(); } public bool MoveNext() { throw new NotImplementedException(); } public void Reset() { throw new NotImplementedException(); } public CustomStructEnumeratorWithIDisposable<T> GetEnumerator() { return this; } } #if MCS [StructLayout(LayoutKind.Sequential, Size = 1)] #endif public struct DataItem { public int Property { get; set; } public void TestCall() { } } public class Item { } public class NonEnumerableArrayLike { private readonly int length; public Item this[int index] { get { return null; } } public int Length { get { return length; } } } private IEnumerable<string> alternatives; private object someObject; private void TryGetItem(int id, out Item item) { item = null; } private static void Operation(ref int i) { } private static void Operation(Func<bool> f) { } public void ForEachOnField() { foreach (string alternative in alternatives) { alternative.ToLower(); } } public void ForEach(IEnumerable<string> alternatives) { foreach (string alternative in alternatives) { alternative.ToLower(); } } public void ForEachOverList(List<string> list) { // List has a struct as enumerator, so produces quite different IL than foreach over the IEnumerable interface foreach (string item in list) { item.ToLower(); } } public void ForEachOverNonGenericEnumerable(IEnumerable enumerable) { foreach (object item in enumerable) { item.ToString(); } } public void ForEachOverNonGenericEnumerableWithAutomaticCastValueType(IEnumerable enumerable) { foreach (int item in enumerable) { item.ToString(); } } public void ForEachOverNonGenericEnumerableWithAutomaticCastRefType(IEnumerable enumerable) { foreach (string item in enumerable) { Console.WriteLine(item); } } public void ForEachOnCustomClassEnumerator(CustomClassEnumerator e) { foreach (object item in e) { Console.WriteLine(item); } } // TODO : Needs additional pattern detection // CustomStructEnumerator does not implement IDisposable // No try-finally-Dispose is generated. //public void ForEachOnCustomStructEnumerator(CustomStructEnumerator e) //{ // foreach (object item in e) { // Console.WriteLine(item); // } //} public void ForEachOnGenericCustomClassEnumerator<T>(CustomClassEnumerator<T> e) { foreach (T item in e) { Console.WriteLine(item); } } // TODO : Needs additional pattern detection // CustomStructEnumerator does not implement IDisposable // No try-finally-Dispose is generated. //public void ForEachOnGenericCustomStructEnumerator<T>(CustomStructEnumerator<T> e) //{ // foreach (T item in e) { // Console.WriteLine(item); // } //} public void ForEachOnCustomClassEnumeratorWithIDisposable(CustomClassEnumeratorWithIDisposable e) { foreach (object item in e) { Console.WriteLine(item); } } public void ForEachOnCustomStructEnumeratorWithIDisposable(CustomStructEnumeratorWithIDisposable e) { foreach (object item in e) { Console.WriteLine(item); } } public void ForEachOnGenericCustomClassEnumeratorWithIDisposable<T>(CustomClassEnumeratorWithIDisposable<T> e) { foreach (T item in e) { Console.WriteLine(item); } } public void ForEachOnGenericCustomStructEnumeratorWithIDisposable<T>(CustomStructEnumeratorWithIDisposable<T> e) { foreach (T item in e) { Console.WriteLine(item); } } public static void NonGenericForeachWithReturnFallbackTest(IEnumerable e) { Console.WriteLine("NonGenericForeachWithReturnFallback:"); IEnumerator enumerator = e.GetEnumerator(); try { Console.WriteLine("MoveNext"); if (enumerator.MoveNext()) { object current = enumerator.Current; Console.WriteLine("please don't inline 'current'"); Console.WriteLine(current); } } finally { IDisposable disposable = enumerator as IDisposable; if (disposable != null) { disposable.Dispose(); } } Console.WriteLine("After finally!"); } public static void ForeachWithRefUsage(List<int> items) { foreach (int item in items) { #if ROSLYN && OPT // The variable name differs based on whether roslyn optimizes out the 'item' variable int i = item; Operation(ref i); #else int i = item; Operation(ref i); #endif } } public static void ForeachWithCapturedVariable(List<int> items) { foreach (int item in items) { int c = item; Operation(() => c == 5); } } public static T LastOrDefault<T>(IEnumerable<T> items) { T result = default(T); foreach (T item in items) { result = item; } return result; } public void ForEachOverArray(string[] array) { foreach (string text in array) { Console.WriteLine(text.ToLower() + text.ToUpper()); } } public void ForOverNonArray(NonEnumerableArrayLike array) { for (int i = 0; i < array.Length; i++) { Item item = array[i]; Console.WriteLine(item.ToString() + item.ToString()); } } public unsafe void ForEachOverArrayOfPointers(int*[] array) { foreach (int* value in array) { Console.WriteLine(new IntPtr(value)); Console.WriteLine(new IntPtr(value)); } } public void ForEachBreakWhenFound(string name, ref StringComparison output) { #if MCS2 foreach (int value in Enum.GetValues(typeof(StringComparison))) { if (((StringComparison)value).ToString() == name) { output = (StringComparison)value; break; } } #elif MCS5 foreach (int value in Enum.GetValues(typeof(StringComparison))) { StringComparison stringComparison = (StringComparison)value; if (stringComparison.ToString() == name) { output = (StringComparison)value; break; } } #else foreach (StringComparison value in Enum.GetValues(typeof(StringComparison))) { if (value.ToString() == name) { output = value; break; } } #endif } public void ForEachOverListOfStruct(List<DataItem> items, int value) { foreach (DataItem item in items) { #if ROSLYN && OPT // The variable name differs based on whether roslyn optimizes out the 'item' variable DataItem current = item; current.Property = value; #else DataItem dataItem = item; dataItem.Property = value; #endif } } public void ForEachOverListOfStruct2(List<DataItem> items, int value) { foreach (DataItem item in items) { #if ROSLYN && OPT // The variable name differs based on whether roslyn optimizes out the 'item' variable DataItem current = item; current.TestCall(); current.Property = value; #else DataItem dataItem = item; dataItem.TestCall(); dataItem.Property = value; #endif } } public void ForEachOverListOfStruct3(List<DataItem> items, int value) { foreach (DataItem item in items) { item.TestCall(); } } #if !MCS public void ForEachOverMultiDimArray(int[,] items) { foreach (int value in items) { Console.WriteLine(value); Console.WriteLine(value); } } public void ForEachOverMultiDimArray2(int[,,] items) { foreach (int value in items) { Console.WriteLine(value); Console.WriteLine(value); } } public unsafe void ForEachOverMultiDimArray3(int*[,] items) { #if ROSLYN && OPT foreach (int* intPtr in items) { Console.WriteLine(*intPtr); Console.WriteLine(*intPtr); } #else foreach (int* ptr in items) { Console.WriteLine(*ptr); Console.WriteLine(*ptr); } #endif } #endif #endregion public void ForOverArray(string[] array) { for (int i = 0; i < array.Length; i++) { array[i].ToLower(); } } private static void AppendNamePart(string part, StringBuilder name) { foreach (char c in part) { if (c == '\\') { name.Append('\\'); } name.Append(c); } } public void NoForeachOverArray(string[] array) { for (int i = 0; i < array.Length; i++) { string value = array[i]; if (i % 5 == 0) { Console.WriteLine(value); } } } public void NestedLoops() { for (int i = 0; i < 10; i++) { if (i % 2 == 0) { for (int j = 0; j < 5; j++) { Console.WriteLine("Y"); } } else { Console.WriteLine("X"); } } } public int MultipleExits() { int num = 0; while (true) { if (num % 4 == 0) { return 4; } if (num % 7 == 0) { break; } if (num % 9 == 0) { return 5; } if (num % 11 == 0) { break; } num++; } return int.MinValue; } //public int InterestingLoop() //{ // int num = 0; // if (num % 11 == 0) { // while (true) { // if (num % 4 == 0) { // if (num % 7 == 0) { // if (num % 11 == 0) { // // use a continue here to prevent moving the if (i%7) outside the loop // continue; // } // Console.WriteLine("7"); // } else { // // this block is not part of the natural loop // Console.WriteLine("!7"); // } // break; // } // num++; // } // // This instruction is still dominated by the loop header // num = int.MinValue; // } // return num; //} public int InterestingLoop() { int num = 0; if (num % 11 == 0) { while (true) { if (num % 4 == 0) { if (num % 7 != 0) { Console.WriteLine("!7"); break; } if (num % 11 != 0) { Console.WriteLine("7"); break; } } else { num++; } } num = int.MinValue; } return num; } private bool Condition(string arg) { Console.WriteLine("Condition: " + arg); return false; } public void WhileLoop() { Console.WriteLine("Initial"); if (Condition("if")) { while (Condition("while")) { Console.WriteLine("Loop Body"); if (Condition("test")) { if (Condition("continue")) { continue; } if (!Condition("break")) { break; } } Console.WriteLine("End of loop body"); } Console.WriteLine("After loop"); } Console.WriteLine("End of method"); } //other configurations work fine, just with different labels #if OPT && !MCS public void WhileWithGoto() { while (Condition("Main Loop")) { if (Condition("Condition")) { goto IL_000f; } // TODO reorder branches with successive block? goto IL_0026; IL_000f: Console.WriteLine("Block1"); if (Condition("Condition2")) { continue; } // TODO remove redundant goto? goto IL_0026; IL_0026: Console.WriteLine("Block2"); goto IL_000f; } } #endif public void DoWhileLoop() { Console.WriteLine("Initial"); if (Condition("if")) { do { Console.WriteLine("Loop Body"); if (Condition("test")) { if (Condition("continue")) { continue; } if (!Condition("break")) { break; } } Console.WriteLine("End of loop body"); } while (Condition("while")); Console.WriteLine("After loop"); } Console.WriteLine("End of method"); } public void Issue1395(int count) { Environment.GetCommandLineArgs(); for (int i = 0; i < count; i++) { Environment.GetCommandLineArgs(); do { #if OPT || MCS IL_0013: #else IL_0016: #endif Environment.GetCommandLineArgs(); if (Condition("part1")) { Environment.GetEnvironmentVariables(); if (Condition("restart")) { #if OPT || MCS goto IL_0013; #else goto IL_0016; #endif } } else { Environment.GetLogicalDrives(); } Environment.GetCommandLineArgs(); while (count > 0) { switch (count) { case 0: case 1: case 2: Environment.GetCommandLineArgs(); break; case 3: case 5: case 6: Environment.GetEnvironmentVariables(); break; default: Environment.GetLogicalDrives(); break; } } count++; } while (Condition("do-while")); Environment.GetCommandLineArgs(); } Environment.GetCommandLineArgs(); } public void ForLoop() { Console.WriteLine("Initial"); if (Condition("if")) { for (int i = 0; Condition("for"); i++) { Console.WriteLine("Loop Body"); if (Condition("test")) { if (Condition("continue")) { continue; } if (!Condition("not-break")) { break; } } Console.WriteLine("End of loop body"); } Console.WriteLine("After loop"); } Console.WriteLine("End of method"); } public void ReturnFromDoWhileInTryFinally() { try { do { if (Condition("return")) { return; } } while (Condition("repeat")); Environment.GetCommandLineArgs(); } finally { Environment.GetCommandLineArgs(); } Environment.GetCommandLineArgs(); } public void ForLoopWithEarlyReturn(int[] ids) { for (int i = 0; i < ids.Length; i++) { Item item = null; TryGetItem(ids[i], out item); if (item == null) { break; } } } public void ForeachLoopWithEarlyReturn(List<object> items) { foreach (object item in items) { if ((someObject = item) == null) { break; } } } public void NestedForeach(List<object> items1, List<object> items2) { foreach (object item in items1) { bool flag = false; foreach (object item2 in items2) { if (item2 == item) { flag = true; break; } } if (!flag) { Console.WriteLine(item); } } Console.WriteLine("end"); } public void MergeAroundContinue() { for (int i = 0; i < 20; i++) { if (i % 3 == 0) { if (i != 6) { continue; } } else if (i % 5 == 0) { if (i != 5) { continue; } } else if (i % 7 == 0) { if (i != 7) { continue; } } else if (i % 11 == 0) { continue; } Console.WriteLine(i); } Console.WriteLine("end"); } public void ForEachInSwitch(int i, IEnumerable<string> args) { switch (i) { case 1: Console.WriteLine("one"); break; case 2: { foreach (string arg in args) { Console.WriteLine(arg); } break; } default: throw new NotImplementedException(); } } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/Loops.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/Loops.cs", "repo_id": "ILSpy", "token_count": 8686 }
209
// Copyright (c) 2019 Daniel Grunwald // // 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. namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty { internal class T01Issue1574 { private struct A { private bool val; public static implicit operator bool(A a) { return a.val; } } private struct C { private int val; public static implicit operator C(bool b) { return default(C); } } private C ChainedConversion() { return (bool)default(A); } public void Call_Overloaded() { Overloaded((bool)default(A)); } private void Overloaded(A a) { } private void Overloaded(bool a) { } } internal class T02BothDirectAndChainedConversionPossible { private struct A { private bool val; public static implicit operator bool(A a) { return a.val; } } private struct C { private int val; public static implicit operator C(bool b) { return default(C); } public static implicit operator C(A a) { return default(C); } public static bool operator ==(C a, C b) { return true; } public static bool operator !=(C a, C b) { return false; } } private C DirectConvert(A a) { return a; } private C IndirectConvert(A a) { return (bool)a; } private C? LiftedDirectConvert(A? a) { return a; } private C? LiftedIndirectConvert(A? a) { return (bool?)a; } private bool Compare(A a, C c) { return a == c; } private void LiftedCompare(A? a, C? c) { UseBool(a == c); UseBool(a == default(C)); UseBool(c == default(A)); } private void UseBool(bool b) { } } #if CS72 internal class T03ConversionWithInArgument { private struct T { private byte dummy; public static implicit operator T(in int val) { return default(T); } public static explicit operator T(in long val) { return default(T); } } private struct U { private byte dummy; public static implicit operator T(in U u) { return default(T); } public static explicit operator int(in U u) { return 0; } } private void UseT(T t) { } private int Test(int i, long l, U u) { UseT(i); UseT((T)l); UseT(u); return (int)u; } } #endif }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/UserDefinedConversions.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/UserDefinedConversions.cs", "repo_id": "ILSpy", "token_count": 1291 }
210
// Metadata version: v4.0.30319 .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly NoExtensionMethods { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) .custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..WrapNonEx 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) // ceptionThrows. // --- The following custom attribute is added automatically, do not uncomment ------- // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 07 01 00 00 00 00 ) .permissionset reqmin = {[mscorlib]System.Security.Permissions.SecurityPermissionAttribute = {property bool 'SkipVerification' = bool(true)}} .hash algorithm 0x00008004 .ver 0:0:0:0 } .module NoExtensionMethods.dll .custom instance void [mscorlib]System.Security.UnverifiableCodeAttribute::.ctor() = ( 01 00 00 00 ) .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // =============== CLASS MEMBERS DECLARATION =================== .class private abstract auto ansi sealed beforefieldinit ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoExtensionMethods extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method assembly hidebysig static class [mscorlib]System.Func`1<!!T> AsFunc<class T>(!!T 'value') cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 23 (0x17) .maxstack 2 .locals init (class [mscorlib]System.Func`1<!!T> V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box !!T IL_0007: ldftn !!0 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoExtensionMethods::Return<!!0>(!!0) IL_000d: newobj instance void class [mscorlib]System.Func`1<!!T>::.ctor(object, native int) IL_0012: stloc.0 IL_0013: br.s IL_0015 IL_0015: ldloc.0 IL_0016: ret } // end of method NoExtensionMethods::AsFunc .method private hidebysig static !!T Return<T>(!!T 'value') cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 1 .locals init (!!T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: br.s IL_0005 IL_0005: ldloc.0 IL_0006: ret } // end of method NoExtensionMethods::Return .method assembly hidebysig static class [mscorlib]System.Func`2<int32,int32> ExtensionMethodAsStaticFunc() cil managed { // Code size 18 (0x12) .maxstack 2 .locals init (class [mscorlib]System.Func`2<int32,int32> V_0) IL_0000: nop IL_0001: ldnull IL_0002: ldftn !!0 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoExtensionMethods::Return<int32>(!!0) IL_0008: newobj instance void class [mscorlib]System.Func`2<int32,int32>::.ctor(object, native int) IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } // end of method NoExtensionMethods::ExtensionMethodAsStaticFunc .method assembly hidebysig static class [mscorlib]System.Func`1<object> ExtensionMethodBoundToNull() cil managed { // Code size 18 (0x12) .maxstack 2 .locals init (class [mscorlib]System.Func`1<object> V_0) IL_0000: nop IL_0001: ldnull IL_0002: ldftn !!0 ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoExtensionMethods::Return<object>(!!0) IL_0008: newobj instance void class [mscorlib]System.Func`1<object>::.ctor(object, native int) IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } // end of method NoExtensionMethods::ExtensionMethodBoundToNull } // end of class ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoExtensionMethods // ============================================================= // *********** DISASSEMBLY COMPLETE ***********************
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/NoExtensionMethods.roslyn.il/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/NoExtensionMethods.roslyn.il", "repo_id": "ILSpy", "token_count": 2226 }
211
public class VBAutomaticEvents { public delegate void EventWithParameterEventHandler(int EventNumber); public delegate void EventWithoutParameterEventHandler(); public event EventWithParameterEventHandler EventWithParameter; public event EventWithoutParameterEventHandler EventWithoutParameter; public void RaiseEvents() { EventWithParameter?.Invoke(1); EventWithoutParameter?.Invoke(); } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/VBPretty/VBAutomaticEvents.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/VBPretty/VBAutomaticEvents.cs", "repo_id": "ILSpy", "token_count": 104 }
212