public void CookOverride() { SmeltTicks++; if (SmeltTicks % 2 == 0) { TrySmeltItems(); } var burnable = _plugin.FindBurnable(Furnace); if (burnable == null) { _plugin.StopCooking(Furnace); return; } ItemModBurnable component = burnable.info.GetComponent <ItemModBurnable>(); burnable.fuel -= 0.5f * Furnace.cookingTemperature / 200f; if (!burnable.HasFlag(global::Item.Flag.OnFire)) { burnable.SetFlag(global::Item.Flag.OnFire, true); burnable.MarkDirty(); } if (burnable.fuel <= 0f) { var array = ArrayPool.Get(2); array[0] = burnable; array[1] = component; ConsumeFuelMethod.Invoke(Furnace, array); ArrayPool.Free(array); } }
//void Update() //{ // timer += Time.deltaTime; // if (timer >= 1) // { // timer = 0; // if (!imageLoaded && OwnerID != new CSteamID(0)) // { // Texture2D tex = GetUserAvatar(OwnerID); // SetTex(tex); // } // } //} public void SelectAvatar() { if (Client.Users == null) { return; } for (int i = 0; i < Client.Users.Count; i++) { string data = SteamMatchmaking.GetLobbyMemberData(Client.Lobby.LobbyID, Client.Users[i].SteamID, "AvatarID"); if (data == "") { continue; } int index; if (int.TryParse(data, out index)) { if (index == avatarID) { return; } } } byte[] d = ArrayPool <byte> .Get(1); d[0] = (byte)avatarID; Client.SendPacketToHost(d, 0, 1, PacketType.RequestAvatarSelection, EP2PSend.k_EP2PSendReliable); ArrayPool <byte> .Recycle(d); }
public void TestRandomAccess(int size) { using (ArrayPool <int> .Get(size, out var array)) { Assert.GreaterOrEqual(array.Length, size); } }
private void EnemyDeath(Enemy enemy) { if (HostEnemySpawner.Instance.enemiesCount < HostEnemySpawner.MAX_NUM_ENEMIES) { if (enemy.Destroy) { byte[] d = ArrayPool <byte> .Get(sizeof(int)); ByteManipulator.Write(d, 0, enemy.NetworkId.NetworkId); Client.SendPacketToInGameUsers(d, 0, d.Length, PacketType.EnemyDeath, Steamworks.EP2PSend.k_EP2PSendReliable); ArrayPool <byte> .Recycle(d); enemy.Destroy = false; } enemy.randomSpawnTimer -= Time.deltaTime; if (enemy.randomSpawnTimer <= 0) { HostEnemySpawner.Instance.InstantiateEnemy(); enemy.randomSpawnTimer = UnityEngine.Random.Range(0f, 5.0f); enemy.Recycling = false; EnemyToRecycleToRemove.Add(enemy); } } }
public static void StartRevealChain(Cell[,] level, int x, int y, Func <Cell, Vector2Int, bool> onSouldReveal) { if (!level.TryGetValue(x, y, out Cell cell)) { return; // Indexes out of range } if (cell.isRevealed || cell.hasFlag) { return; // cell is no subject revelation. } if ((level[x, y].isRevealed = onSouldReveal(cell, new Vector2Int(x, y))) == false) { return; // reveal result asks to stop chain. } if (cell.value == 0) { const int neighborCount = 8; var neighbors = ArrayPool <Vector2Int> .Get(neighborCount); LevelUtility.GetAdjacentCellsSquare(new Vector2Int(x, y), neighbors); for (int i = 0; i < neighborCount; i++) { Vector2Int nPos = neighbors[i]; StartRevealChain(level, nPos.x, nPos.y, onSouldReveal); } ArrayPool <Vector2Int> .Release(neighbors); } }
void ControlAvatarDisponibility(byte[] data, uint dataLenght, CSteamID sender) { int avatarIndex = data[0]; for (int i = 0; i < Client.Users.Count; i++) { string userIndex = SteamMatchmaking.GetLobbyMemberData(Client.Lobby.LobbyID, Client.Users[i].SteamID, "AvatarID"); if (userIndex == "") { continue; } int index; if (int.TryParse(userIndex, out index)) { if (index == avatarIndex) { return; } } } byte[] d = ArrayPool <byte> .Get(1); d[0] = (byte)avatarIndex; Client.SendPacket(d, 0, d.Length, PacketType.AnswerAvatarSelection, Client.MyID, sender, EP2PSend.k_EP2PSendReliable); ArrayPool <byte> .Recycle(d); }
public static void BreakToParticles(this SpriteRenderer spr, float pixelSize, Material material) { var points = ArrayPool <Vector3> .Get(particleBufferSize); spr.Rasterize(Rasterizer2D.CreateTarget(pixelSize), (point, uv) => { points.Push(point); }); var go = new GameObject(); var ps = go.AddComponent <ParticleSystem>(); ps.Stop(); var psmain = ps.main; psmain.loop = false; psmain.maxParticles = (int)points.length; psmain.duration = 20; psmain.gravityModifier = 1; var psemit = ps.emission; psemit.enabled = false; var pscol = ps.collision; pscol.enabled = true; pscol.mode = ParticleSystemCollisionMode.Collision2D; pscol.type = ParticleSystemCollisionType.World; pscol.bounce = 0.3f; pscol.lifetimeLoss = 0.1f; pscol.dampen = 0.1f; var psr = ps.GetComponent <ParticleSystemRenderer>(); psr.material = material; ps.Emit((int)points.length); var particles = ArrayPool <ParticleSystem.Particle> .Get(points.length); particles.Resize(points.length); ps.GetParticles(particles.array); for (int i = 0; i < particles.length; ++i) { particles.array[i].position = points[i]; particles.array[i].startSize = pixelSize; particles.array[i].velocity = new Vector3(1, 1, 0) * Random.insideUnitCircle * 0.2f; } ps.SetParticles(particles.array, (int)particles.length); ps.Play(); ArrayPool <Vector3> .Release(points); ArrayPool <ParticleSystem.Particle> .Release(particles); }
public void SendShotCall() { byte[] d = ArrayPool <byte> .Get(sizeof(int)); ByteManipulator.Write(d, 0, gnOnject.NetworkId); Client.SendPacketToInGameUsers(d, 0, d.Length, PacketType.ShootCall, Client.MyID, Steamworks.EP2PSend.k_EP2PSendUnreliable, false); ArrayPool <byte> .Recycle(d); }
/// <summary> /// Update the driven text with the formatted value and inputs /// </summary> public void UpdateDrivenText() { #if BT_DEBUG_UNSTRIP if (m_debug) { Debug.Log("[" + Time.frameCount + "][" + this.Path() + "] UpdateDrivenText"); } #endif if (m_inputs == null || m_inputs.Length == 0) { #if BT_DEBUG_UNSTRIP if (m_debug) { Debug.LogWarning("[" + Time.frameCount + "][" + this.Path() + "] UpdateDrivenText no inputs set"); } #endif this.driven.value = this.format; return; } using (var inputList = ListPool <object> .Get()) { foreach (var i in m_inputs) { if (i == null) { #if UNITY_EDITOR || DEBUG_UNSTRIP Debug.LogWarning("[" + Time.frameCount + "] " + this.Path() + " missing input item at index " + i); #endif inputList.Add(""); continue; } inputList.Add(i.valueObj); } using (var inputArgs = ArrayPool <object> .Get(inputList.Count)) { if (!Application.isPlaying) { for (var i = 0; i < inputArgs.array.Length; i++) { inputArgs.array [i] = m_editorPlaceholderInputs != null && m_editorPlaceholderInputs.Length > 0 ? m_editorPlaceholderInputs [Mathf.Min(m_editorPlaceholderInputs.Length - 1, i)] : ""; } } else { inputList.CopyTo(inputArgs.array); } this.driven.value = string.Format(this.format, inputArgs.array); } } }
void SendHitToHost(int id) { byte[] data = ArrayPool <byte> .Get(sizeof(int)); ByteManipulator.Write(data, 0, id); Client.SendPacketToHost(data, 0, data.Length, PacketType.ShootHitServer, Steamworks.EP2PSend.k_EP2PSendReliable); ArrayPool <byte> .Recycle(data); Debug.Log("hit"); }
public void UpdateInstance(CellView view, Vector2Int coords, CellStatusFlags cellStatus) { if (view == null) { return; } bool isRevealed = cellStatus.HasFlag(CellStatusFlags.IsRevealed); bool isMarked = !isRevealed && cellStatus.HasFlag(CellStatusFlags.IsMarked); view.textMesh.enabled = isRevealed; view.ToggleFlag(isMarked); SetCellBackground(view, isRevealed, isMarked); if (isMarked) { view.FlagColor = colorSheet.flagColor; } if (isRevealed) { if (cellStatus.HasFlag(CellStatusFlags.HasMine)) { SetMineMode(view, true); } else { SetMineMode(view, false); const int neighborCount = 8; var neighbors = ArrayPool <Vector2Int> .Get(neighborCount); LevelUtility.GetAdjacentCellsSquare(coords, neighbors); int cellValue = 0; for (int i = 0; i < neighborCount; ++i) { var neighborStatus = levelDataManager.GetCellStatus(neighbors[i]); if (neighborStatus.HasFlag(CellStatusFlags.HasMine)) { cellValue++; } } ArrayPool <Vector2Int> .Release(neighbors); view.textMesh.text = cellValue == 0 ? "" : cellValue.ToString(); view.textMesh.color = colorSheet.GetColorForCellValue(cellValue); } } else { view.mineSprite.enabled = false; } }
private void DoOnPopulateMesh(VertexHelper vh) { vh.Clear(); var thisRT = this.rectTransform; var thisRect = this.rectTransform.rect; int vOff = 0; var rectArray = this.rectRefs; if (rectArray == null || rectArray.Count == 0) { return; } using (var quad = ArrayPool <UIVertex> .Get(4)) { Rect prevRect = default(Rect); for (var i = 0; i < rectArray.Count; i++) { var c = rectArray[i].value; if (c == null) { continue; } var curRect = thisRT.InverseTransformRect(c); if (i > 0 && m_connectEnds) { var uiVert = UIVertex.simpleVert; uiVert.color = this.color; var zPos = thisRT.position.z; uiVert.position = new Vector3(prevRect.xMax, prevRect.yMin, zPos); uiVert.uv0 = new Vector2(0, 0); quad.array[0] = uiVert; uiVert.position = new Vector3(prevRect.xMax, prevRect.yMax, zPos); uiVert.uv0 = new Vector2(0, 1); quad.array[1] = uiVert; uiVert.position = new Vector3(curRect.xMin, curRect.yMax, zPos); uiVert.uv0 = new Vector2(1, 1); quad.array[2] = uiVert; uiVert.position = new Vector3(curRect.xMin, curRect.yMin, zPos); uiVert.uv0 = new Vector2(1, 0); quad.array[3] = uiVert; vOff += vh.AddQuadClipped(quad.array, thisRect, vOff); } vOff += vh.AddRectClipped(curRect, this.color, thisRect, vOff); prevRect = curRect; } } }
void Send(byte[] data, int startIndex, int length, PacketType command, CSteamID sender, CSteamID receiver, EP2PSend sendType) { if (MyID == receiver) { InvokeCommand((int)command, data, (uint)length, sender); return; } byte[] toSend = ArrayPool <byte> .Get(length + HeaderLength); ByteManipulator.Write(toSend, 0, (byte)command); ByteManipulator.Write(toSend, sizeof(byte), (ulong)sender); ByteManipulator.Write <byte>(data, startIndex, toSend, HeaderLength, length); SteamNetworking.SendP2PPacket(receiver, toSend, (uint)toSend.Length, sendType); ArrayPool <byte> .Recycle(toSend); }
/* * v0 ---- v1 \ / \/ \ v2 */ void BlitTriangle(Vector2 v0, Vector2 v1, Vector2 v2, Vector2 uv0, Vector2 uv1, Vector2 uv2, PlotDelegate plotDelegate) { if (v0.x > v1.x) { MUtils.Swap(ref v0, ref v1); } var L1 = new RasterizedLine(v0, v2); var L2 = new RasterizedLine(v1, v2); var i1 = L1.CreatePixelIterator(); var i2 = L2.CreatePixelIterator(); Vector2 newUv0 = Vector2.zero; Vector3 newUv1 = Vector2.zero; var pList1 = ArrayPool <RasterizedLine.Pixel> .Get(); var pList2 = ArrayPool <RasterizedLine.Pixel> .Get(); CacheYOnChanged(i1, pList1); CacheYOnChanged(i2, pList2); if (CheckSequence(pList1, pList2)) { for (int i = 0; i < pList1.length; ++i) { var a = pList1[i]; var b = pList2[i]; BlitHorizontalLine(a.x, b.x, a.y, newUv0, newUv1, plotDelegate); } } else { for (int i = 0; i < pList1.length; ++i) { var a = pList1[i]; var b = pList2[-i - 1]; BlitHorizontalLine(a.x, b.x, a.y, newUv0, newUv1, plotDelegate); } } ArrayPool <RasterizedLine.Pixel> .Release(pList1); ArrayPool <RasterizedLine.Pixel> .Release(pList2); }
public static void RevealCellsRecursively(LevelTable level, int x, int y, Dictionary <Vector2Int, Cell> revealList) { if (revealList.Count > level.CellCount) { throw new OverflowException(); } var pos = new Vector2Int(x, y); if (revealList.ContainsKey(pos)) { return; } if (!LevelUtility.IsCellWithinBounds(x, y, level.Size)) { return; // Indexes out of range. } Cell cell = level[x, y]; if (cell.isRevealed || cell.hasFlag) { return; // cell is not subject revelation. } level.MarkCellRevealed(pos); revealList[pos] = level[x, y]; if (cell.value == 0) { const int neighborCount = 8; var neighbors = ArrayPool <Vector2Int> .Get(neighborCount); LevelUtility.GetAdjacentCellsSquare(pos, neighbors); for (int i = 0; i < neighborCount; i++) { Vector2Int nPos = neighbors[i]; RevealCellsRecursively(level, nPos.x, nPos.y, revealList); } ArrayPool <Vector2Int> .Release(neighbors); } }
void Receive(uint lenght) { byte[] receiver = ArrayPool <byte> .Get((int)lenght); uint dataLenght; CSteamID sender; SteamNetworking.ReadP2PPacket(receiver, lenght, out dataLenght, out sender); int command = receiver[0]; CSteamID packetSender = (CSteamID)ByteManipulator.ReadUInt64(receiver, 1); int finalLength = (int)lenght - HeaderLength; ByteManipulator.Write <byte>(receiver, HeaderLength, receiver, 0, finalLength); InvokeCommand(command, receiver, (uint)finalLength, packetSender); ArrayPool <byte> .Recycle(receiver); }
public void ArrayPool_Concurrency() { var pool = new ArrayPool <int>(1); Parallel.ForEach( Enumerable.Range(0, 1000), _ => { var arr = pool.Get(); try { Assert.IsNotNull(arr); } finally { pool.Release(arr); } } ); }
void OnEnable() { var manager = World.Active.EntityManager; var moveCommandComponentTypes = ArrayPool.Get <ComponentType>(3); moveCommandComponentTypes[0] = ComponentType.ReadWrite <MoveCommand>(); moveCommandComponentTypes[1] = ComponentType.ReadWrite <DestroyableComponentData>(); moveCommandComponentTypes[2] = ComponentType.ReadWrite <DateTimeTicksToProcess>(); _moveCommandComponentTypes = manager.CreateArchetype(moveCommandComponentTypes); var synchronizePositionComponentTypes = ArrayPool.Get <ComponentType>(6); synchronizePositionComponentTypes[0] = ComponentType.ReadWrite <SyncInfoTag>(); synchronizePositionComponentTypes[1] = ComponentType.ReadWrite <TeamTag>(); synchronizePositionComponentTypes[2] = ComponentType.ReadWrite <Translation>(); synchronizePositionComponentTypes[3] = ComponentType.ReadWrite <Rotation>(); synchronizePositionComponentTypes[4] = ComponentType.ReadWrite <PhysicsVelocity>(); synchronizePositionComponentTypes[5] = ComponentType.ReadWrite <DestroyableComponentData>(); _synchronizePositionComponentTypes = manager.CreateArchetype(synchronizePositionComponentTypes); if (!FindComponentOfInterfaceOrClassHelper.FindComponentOfInterfaceOrClass(out _prefabStorage)) { throw new KeyNotFoundException(); } if (!FindSystemOfInterfaceHelper.FindSystemOfInterface(out _initialDeserializer)) { throw new KeyNotFoundException(); } _prefabStorage.FindPrefab <PlayerMachineTag>(manager, out _playerPrefabEntity); if (IsMine) { var idEntity = manager.CreateEntity(ComponentType.ReadWrite <UserIdSingleton>()); var userIdSingleton = new UserIdSingleton(OwnerActorNr); manager.SetComponentData(idEntity, userIdSingleton); RPC(nameof(SpawnPlayerMachine), RpcTarget.Others); } _prefabStorage.FindPrefab <Point, DateTimeTicksToProcess>(manager, out _nextPointPrefabEntity); }
public void LoadServices(bool forceReload, Action onCompleteCallback = null) { if (!m_servicesLoaded || forceReload) { EnsureServicesExists(); Services.Get.InitStarted(); DoLoadServices(() => { m_servicesLoaded = true; #if UNITY_EDITOR var servicesT = Services.Get.transform; using (var services = ArrayPool <Transform> .Get(servicesT.childCount)) { for (var i = 0; i < services.array.Length; i++) { services.array[i] = servicesT.GetChild(i); } Array.Sort(services.array, (x, y) => StringComparer.InvariantCultureIgnoreCase.Compare(x.name, y.name)); for (var i = 0; i < services.array.Length; i++) { services.array[i].SetSiblingIndex(i); } } #endif Services.Get.InitComplete(); if (onCompleteCallback != null) { onCompleteCallback(); } if (this.disposeAfterLoad) { Dispose(); } }); } }
public static void EnsureDrivenNotCircular(UnityEditor.Editor editor) { var proxiesFloat = editor.target as ProxiesFloat; var drivenProp = editor.serializedObject.FindProperty("m_driven"); var driven = drivenProp.objectReferenceValue as HasFloat; using (var validTargets = ListPool <HasFloat> .Get()) { proxiesFloat.FindAllNonCircularTargets(validTargets); if (driven != null && proxiesFloat.IsInDrivenChainOf(driven)) { drivenProp.objectReferenceValue = (validTargets.Count > 0)? validTargets[0]: null; } if (validTargets.Count > 1) { var selectedIx = -1; using (var options = ArrayPool <GUIContent> .Get(validTargets.Count)) { for (int i = 0; i < options.array.Length; i++) { if (object.ReferenceEquals(validTargets[i], driven)) { selectedIx = i; } options.array[i] = new GUIContent(validTargets[i].GetType().Name); } var nextSelectedIx = EditorGUILayout.Popup(new GUIContent("Driven (select)", "there is more than one valid 'driven' target on this GameObject"), selectedIx, options.array); if (nextSelectedIx != selectedIx) { drivenProp.objectReferenceValue = (nextSelectedIx >= 0)? validTargets[nextSelectedIx]: null; } } } } }
override public void OnGUI(Rect position, SerializedProperty property, GUIContent label) { var saveColor = GUI.color; EditorGUI.BeginProperty(position, label, property); // Draw label position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label); SerializedProperty resourcePathProp = property.FindPropertyRelative("m_resourcePath"); SerializedProperty selectedComponentTypeProp = property.FindPropertyRelative("m_selectedComponentType"); var baseHeight = base.GetPropertyHeight(property, label); this.renderedPropertyHeight = baseHeight; var curRect = new Rect(position.x, position.y, position.width, baseHeight); // position.height); GUI.color = this.lastValidCount > 0 ? VALID : PENDING; EditorGUI.PropertyField(curRect, resourcePathProp, new GUIContent("Resource Path", "a resource path that contains assets each having a component whose type name matches the asset name") ); this.renderedPropertyHeight += baseHeight; var resourcePath = resourcePathProp.stringValue ?? ""; // Don't make child fields be indented int indent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; var selectedComponentTypeName = selectedComponentTypeProp.stringValue ?? ""; var trimIx = selectedComponentTypeName.LastIndexOf('.'); if (trimIx > 0) { selectedComponentTypeName = selectedComponentTypeName.Substring(trimIx + 1); } using (var prefabs = ListPool <FileInfo> .Get()) using (var validPrefabs = ListPool <FileInfo> .Get()) using (var invalidPrefabs = ListPool <FileInfo> .Get()) { ResourcePathsByPathPrefix.FindAllPrefabs(resourcePath, prefabs); var oldIx = -1; for (var i = 0; i < prefabs.Count; i++) { var pName = Path.GetFileNameWithoutExtension(prefabs[i].Name); var pAsset = Resources.Load <GameObject>(string.Format("{0}/{1}", resourcePath, pName)); if (pAsset == null) { invalidPrefabs.Add(prefabs[i]); continue; } if (FindComponentWithTypeName(pAsset, pName) != null) { if (pName == selectedComponentTypeName) { oldIx = validPrefabs.Count; } validPrefabs.Add(prefabs[i]); } else { invalidPrefabs.Add(prefabs[i]); } } this.lastValidCount = validPrefabs.Count; using (var prefabNames = ArrayPool <string> .Get(validPrefabs.Count + 1)) { prefabNames.array[0] = "[none]"; for (var nameIx = 0; nameIx < validPrefabs.Count; nameIx++) { prefabNames.array[nameIx + 1] = Path.GetFileNameWithoutExtension(validPrefabs[nameIx].Name); } curRect.y += baseHeight; oldIx += 1; // account for empty first entry GUI.color = validPrefabs.Count > 0 ? VALID : PENDING; var newIx = validPrefabs.Count > 0 ? EditorGUI.Popup(curRect, "Selected Resource Prefab (" + validPrefabs.Count + ")", oldIx, prefabNames.array) : EditorGUI.Popup(curRect, "No Valid Prefabs at Resource Path", oldIx, prefabNames.array); this.renderedPropertyHeight += baseHeight; GUI.color = saveColor; if (newIx != oldIx) { if (newIx <= 0) { selectedComponentTypeProp.stringValue = ""; } else { var selectedAssetName = Path.GetFileNameWithoutExtension(validPrefabs[newIx - 1].Name); var selectedAsset = Resources.Load <GameObject>(string.Format("{0}/{1}", resourcePath, selectedAssetName)); var c = FindComponentWithTypeName(selectedAsset, selectedAssetName); selectedComponentTypeProp.stringValue = c.GetType().FullName; } } } if (invalidPrefabs.Count > 0) { GUI.color = PENDING; using (var invalidNames = ArrayPool <GUIContent> .Get(invalidPrefabs.Count)) { for (var nameIx = 0; nameIx < invalidPrefabs.Count; nameIx++) { invalidNames.array[nameIx] = new GUIContent(Path.GetFileNameWithoutExtension(invalidPrefabs[nameIx].Name)); } curRect.y += baseHeight; var selectedIx = EditorGUI.Popup(curRect, new GUIContent("Unusable Prefabs", "These prefabs do not meet the requirement of having a Component whose type name matches the prefab name"), 0, invalidNames.array ); this.renderedPropertyHeight += baseHeight; curRect.y += curRect.height; var selectedAssetName = Path.GetFileNameWithoutExtension(invalidPrefabs[selectedIx].Name); Debug.LogWarning("path to problem prefab=" + selectedAssetName); var selectedAsset = Resources.Load <GameObject>(string.Format("{0}/{1}", resourcePath, selectedAssetName)); Component bestMatch; if (selectedAsset != null && (bestMatch = FindComponentWithNameClosestTo(selectedAsset)) != null) { curRect.height = baseHeight * 6; EditorGUI.HelpBox(curRect, "\nResource prefab " + selectedAssetName + " must have a component with type name " + selectedAssetName + "\n\nFound a component with similar name " + bestMatch.GetType().Name + "\n\nMaybe rename the component class or the prefab to match?\n", MessageType.Warning); } else { curRect.height = baseHeight * 2; EditorGUI.HelpBox(curRect, "Resource prefab " + selectedAssetName + " must have a component with type name " + selectedAssetName, MessageType.Warning); } this.renderedPropertyHeight += curRect.height; } GUI.color = saveColor; } } EditorGUI.indentLevel = indent; EditorGUI.EndProperty(); }
protected List <HookMethod> FindHooks(string name, object[] args) { HookCache hookCache; object[] defaultValue; bool flag; List <HookMethod> hookMethod = this.HooksCache.GetHookMethod(name, args, out hookCache); if (hookMethod != null) { return(hookMethod); } List <HookMethod> hookMethods = new List <HookMethod>(); if (!this.Hooks.TryGetValue(name, out hookMethod)) { return(hookMethods); } HookMethod hookMethod1 = null; HookMethod hookMethod2 = null; foreach (HookMethod hookMethod3 in hookMethod) { if (!hookMethod3.IsBaseHook) { int num = (args != null ? (int)args.Length : 0); bool flag1 = false; if (num == (int)hookMethod3.Parameters.Length) { defaultValue = args; } else { defaultValue = ArrayPool.Get((int)hookMethod3.Parameters.Length); flag1 = true; if (num > 0 && defaultValue.Length != 0) { Array.Copy(args, defaultValue, Math.Min(num, (int)defaultValue.Length)); } if ((int)defaultValue.Length > num) { for (int i = num; i < (int)defaultValue.Length; i++) { ParameterInfo parameters = hookMethod3.Parameters[i]; if (parameters.DefaultValue != null && parameters.DefaultValue != DBNull.Value) { defaultValue[i] = parameters.DefaultValue; } else if (parameters.ParameterType.IsValueType) { defaultValue[i] = Activator.CreateInstance(parameters.ParameterType); } } } } if (hookMethod3.HasMatchingSignature(defaultValue, out flag)) { if (!flag) { hookMethod2 = hookMethod3; } else { hookMethod1 = hookMethod3; if (hookMethod1 != null) { hookMethods.Add(hookMethod1); } else if (hookMethod2 != null) { hookMethods.Add(hookMethod2); } hookCache.SetupMethods(hookMethods); return(hookMethods); } } if (!flag1) { continue; } ArrayPool.Free(defaultValue); } else { hookMethods.Add(hookMethod3); } } if (hookMethod1 != null) { hookMethods.Add(hookMethod1); } else if (hookMethod2 != null) { hookMethods.Add(hookMethod2); } hookCache.SetupMethods(hookMethods); return(hookMethods); }
protected sealed override object OnCallHook(string name, object[] args) { object[] defaultValue; object obj = null; bool flag = false; foreach (HookMethod hookMethod in this.FindHooks(name, args)) { int num = (args != null ? (int)args.Length : 0); if (num == (int)hookMethod.Parameters.Length) { defaultValue = args; } else { defaultValue = ArrayPool.Get((int)hookMethod.Parameters.Length); flag = true; if (num > 0 && defaultValue.Length != 0) { Array.Copy(args, defaultValue, Math.Min(num, (int)defaultValue.Length)); } if ((int)defaultValue.Length > num) { for (int i = num; i < (int)defaultValue.Length; i++) { ParameterInfo parameters = hookMethod.Parameters[i]; if (parameters.DefaultValue != null && parameters.DefaultValue != DBNull.Value) { defaultValue[i] = parameters.DefaultValue; } else if (parameters.ParameterType.IsValueType) { defaultValue[i] = Activator.CreateInstance(parameters.ParameterType); } } } } try { obj = this.InvokeMethod(hookMethod, defaultValue); } catch (TargetInvocationException targetInvocationException1) { TargetInvocationException targetInvocationException = targetInvocationException1; if (flag) { ArrayPool.Free(defaultValue); } Exception innerException = targetInvocationException.InnerException; if (innerException == null) { innerException = targetInvocationException; } throw innerException; } if (num != (int)hookMethod.Parameters.Length) { for (int j = 0; j < (int)hookMethod.Parameters.Length; j++) { if (hookMethod.Parameters[j].IsOut || hookMethod.Parameters[j].ParameterType.IsByRef) { args[j] = defaultValue[j]; } } } if (!flag) { continue; } ArrayPool.Free(defaultValue); } return(obj); }
public static MaterialBvh Create(Dictionary <string, object> tags, int shapesPerNode = 8) { var verts = (Vector3[])tags.GetValueOrDefault(MyImporterConstants.TAG_VERTICES); var normals = (Byte4[])tags.GetValueOrDefault(MyImporterConstants.TAG_NORMALS); var box = (BoundingBox)tags.GetValueOrDefault(MyImporterConstants.TAG_BOUNDING_BOX); var parts = (List <MyMeshPartInfo>)tags.GetValueOrDefault(MyImporterConstants.TAG_MESH_PARTS); var sections = (List <MyMeshSectionInfo>)tags.GetValueOrDefault(MyImporterConstants.TAG_MESH_SECTIONS); var strings = new HashSet <string>(); var triangles = new List <TriangleData>(parts.Sum(x => x.m_indices.Count / 3)); void AddTriangle(string section, string material, int v0, int v1, int v2) { section = section ?? ""; material = material ?? ""; strings.Add(section); strings.Add(material); var normal = normals != null ? (VF_Packer.UnpackNormal(normals[v0]) + VF_Packer.UnpackNormal(normals[v1]) + VF_Packer.UnpackNormal(normals[v2])) : (Vector3?)null; triangles.Add(new TriangleData(new Triangle(in verts[v0], in verts[v1], in verts[v2], normal), section, material)); } foreach (var part in parts) { var materialName = part.m_MaterialDesc?.MaterialName ?? "<<no material>>"; using (PoolManager.Get(out List <KeyValuePair <string, MyMeshSectionMeshInfo> > mtlSections)) { foreach (var section in sections) { foreach (var mesh in section.Meshes) { if (mesh.MaterialName == materialName) { mtlSections.Add(new KeyValuePair <string, MyMeshSectionMeshInfo>(section.Name, mesh)); } } } mtlSections.Sort((a, b) => a.Value.StartIndex.CompareTo(b.Value.StartIndex)); var processed = 0; var idx = part.m_indices; foreach (var section in mtlSections) { for (var i = processed; i < section.Value.StartIndex - 2; i += 3) { AddTriangle(null, materialName, idx[i], idx[i + 1], idx[i + 2]); } var endOfSection = section.Value.StartIndex + section.Value.IndexCount; for (var i = section.Value.StartIndex; i < endOfSection - 2; i += 3) { AddTriangle(section.Key, materialName, idx[i], idx[i + 1], idx[i + 2]); } processed = endOfSection; } for (var i = processed; i < idx.Count - 2; i += 3) { AddTriangle(null, materialName, idx[i], idx[i + 1], idx[i + 2]); } } } PackedBvh bvh; using (ArrayPool <BoundingBox> .Get(triangles.Count, out var array)) { for (var i = 0; i < triangles.Count; i++) { var tri = triangles[i].Triangle; array[i].Min = Vector3.Min(Vector3.Min(tri.A, tri.B), tri.C); array[i].Max = Vector3.Max(Vector3.Max(tri.A, tri.B), tri.C); } using (var builder = new SahBvhBuilder(shapesPerNode, new EqReadOnlySpan <BoundingBox>(array, 0, triangles.Count))) bvh = builder.Build(); } return(new MaterialBvh(bvh, triangles.ToArray(), strings)); }
protected List <HookMethod> FindHooks(string name, object[] args) { // Get the full name of the hook `name(argument type 1, argument type 2, ..., argument type x)` // Check the cache if we already found a match for this hook HookCache cache; List <HookMethod> methods = HooksCache.GetHookMethod(name, args, out cache); if (methods != null) { return(methods); } List <HookMethod> matches = new List <HookMethod>(); // Get all hook methods that could match, return an empty list if none match if (!Hooks.TryGetValue(name, out methods)) { return(matches); } // Find matching hooks HookMethod exactMatch = null; HookMethod overloadedMatch = null; foreach (HookMethod h in methods) { // A base hook should always have a matching signature either directly or through inheritance // and should always be called as core functionality depends on it. if (h.IsBaseHook) { matches.Add(h); continue; } // Check if this method matches the hook arguments passed if it isn't a base hook object[] hookArgs; int received = args?.Length ?? 0; bool pooledArray = false; if (received != h.Parameters.Length) { // The call argument count is different to the declared callback methods argument count hookArgs = ArrayPool.Get(h.Parameters.Length); pooledArray = true; if (received > 0 && hookArgs.Length > 0) { // Remove any additional arguments which the callback method does not declare Array.Copy(args, hookArgs, Math.Min(received, hookArgs.Length)); } if (hookArgs.Length > received) { // Create additional parameters for arguments excluded in this hook call for (int n = received; n < hookArgs.Length; n++) { ParameterInfo parameter = h.Parameters[n]; if (parameter.DefaultValue != null && parameter.DefaultValue != DBNull.Value) { // Use the default value that was provided by the method definition hookArgs[n] = parameter.DefaultValue; } else if (parameter.ParameterType.IsValueType) { // Use the default value for value types hookArgs[n] = Activator.CreateInstance(parameter.ParameterType); } } } } else { hookArgs = args; } bool isExactMatch; if (h.HasMatchingSignature(hookArgs, out isExactMatch)) { if (isExactMatch) { exactMatch = h; break; } // Should we determine the level and call the closest overloaded match? Performance impact? overloadedMatch = h; } if (pooledArray) { ArrayPool.Free(hookArgs); } } if (exactMatch != null) { matches.Add(exactMatch); } else { if (overloadedMatch != null) { matches.Add(overloadedMatch); } } cache.SetupMethods(matches); return(matches); }
/// <summary> /// Calls the specified hook on this plugin /// </summary> /// <param name="name"></param> /// <param name="args"></param> /// <returns></returns> protected sealed override object OnCallHook(string name, object[] args) { object returnvalue = null; bool pooledArray = false; // Call all hooks that match the signature foreach (HookMethod h in FindHooks(name, args)) { int received = args?.Length ?? 0; object[] hookArgs; if (received != h.Parameters.Length) { // The call argument count is different to the declared callback methods argument count hookArgs = ArrayPool.Get(h.Parameters.Length); pooledArray = true; if (received > 0 && hookArgs.Length > 0) { // Remove any additional arguments which the callback method does not declare Array.Copy(args, hookArgs, Math.Min(received, hookArgs.Length)); } if (hookArgs.Length > received) { // Create additional parameters for arguments excluded in this hook call for (int n = received; n < hookArgs.Length; n++) { ParameterInfo parameter = h.Parameters[n]; if (parameter.DefaultValue != null && parameter.DefaultValue != DBNull.Value) { // Use the default value that was provided by the method definition hookArgs[n] = parameter.DefaultValue; } else if (parameter.ParameterType.IsValueType) { // Use the default value for value types hookArgs[n] = Activator.CreateInstance(parameter.ParameterType); } } } } else { hookArgs = args; } try { returnvalue = InvokeMethod(h, hookArgs); } catch (TargetInvocationException ex) { if (pooledArray) { ArrayPool.Free(hookArgs); } throw ex.InnerException ?? ex; } if (received != h.Parameters.Length) { // A copy of the call arguments was used for this method call for (int n = 0; n < h.Parameters.Length; n++) { // Copy output values for out and by reference arguments back to the calling args if (h.Parameters[n].IsOut || h.Parameters[n].ParameterType.IsByRef) { args[n] = hookArgs[n]; } } } if (pooledArray) { ArrayPool.Free(hookArgs); } } return(returnvalue); }
/// <summary> /// Calls a hook on all plugins of this manager /// </summary> /// <param name="hook"></param> /// <param name="args"></param> /// <returns></returns> public object CallHook(string hook, params object[] args) { // Locate the sublist if (!hookSubscriptions.TryGetValue(hook, out IList <Plugin> plugins)) { return(null); } if (plugins.Count == 0) { return(null); } // Loop each item object[] values = ArrayPool.Get(plugins.Count); int returnCount = 0; object finalValue = null; Plugin finalPlugin = null; for (int i = 0; i < plugins.Count; i++) { // Call the hook object value = plugins[i].CallHook(hook, args); if (value != null) { values[i] = value; finalValue = value; finalPlugin = plugins[i]; returnCount++; } } // Is there a return value? if (returnCount == 0) { ArrayPool.Free(values); return(null); } if (returnCount > 1 && finalValue != null) { // Notify log of hook conflict hookConflicts.Clear(); for (int i = 0; i < plugins.Count; i++) { object value = values[i]; if (value == null) { continue; } if (value.GetType().IsValueType) { if (!values[i].Equals(finalValue)) { hookConflicts.Add($"{plugins[i].Name} - {value} ({value.GetType().Name})"); } } else { if (values[i] != finalValue) { hookConflicts.Add($"{plugins[i].Name} - {value} ({value.GetType().Name})"); } } } if (hookConflicts.Count > 0) { hookConflicts.Add($"{finalPlugin.Name} ({finalValue} ({finalValue.GetType().Name}))"); Logger.Write(LogType.Warning, "Calling hook {0} resulted in a conflict between the following plugins: {1}", hook, string.Join(", ", hookConflicts.ToArray())); } } ArrayPool.Free(values); return(finalValue); }
public object CallHook(string hook, params object[] args) { IList <Plugin> plugins; if (!this.hookSubscriptions.TryGetValue(hook, out plugins)) { return(null); } if (plugins.Count == 0) { return(null); } object[] objArray = ArrayPool.Get(plugins.Count); int num = 0; object obj = null; Plugin item = null; for (int i = 0; i < plugins.Count; i++) { object obj1 = plugins[i].CallHook(hook, args); if (obj1 != null) { objArray[i] = obj1; obj = obj1; item = plugins[i]; num++; } } if (num == 0) { ArrayPool.Free(objArray); return(null); } if (num > 1 && obj != null) { this.hookConflicts.Clear(); for (int j = 0; j < plugins.Count; j++) { object obj2 = objArray[j]; if (obj2 != null) { if (obj2.GetType().IsValueType) { if (!objArray[j].Equals(obj)) { this.hookConflicts.Add(string.Format("{0} - {1} ({2})", plugins[j].Name, obj2, obj2.GetType().Name)); } } else if (objArray[j] != obj) { this.hookConflicts.Add(string.Format("{0} - {1} ({2})", plugins[j].Name, obj2, obj2.GetType().Name)); } } } if (this.hookConflicts.Count > 0) { this.hookConflicts.Add(string.Format("{0} ({1} ({2}))", item.Name, obj, obj.GetType().Name)); this.Logger.Write(LogType.Warning, "Calling hook {0} resulted in a conflict between the following plugins: {1}", new object[] { hook, string.Join(", ", this.hookConflicts.ToArray()) }); } } ArrayPool.Free(objArray); return(obj); }