private static ushort FindCargoParent(ushort sourceBuilding, ushort targetBuilding, ItemClass.Service service, ItemClass.SubService subService) { BuildingManager instance = Singleton<BuildingManager>.instance; VehicleManager instance2 = Singleton<VehicleManager>.instance; ushort num = instance.m_buildings.m_buffer [(int)sourceBuilding].m_ownVehicles; int num2 = 0; while (num != 0) { if (instance2.m_vehicles.m_buffer [(int)num].m_targetBuilding == targetBuilding && (instance2.m_vehicles.m_buffer [(int)num].m_flags & Vehicle.Flags.WaitingCargo) != Vehicle.Flags.None) { VehicleInfo info = instance2.m_vehicles.m_buffer [(int)num].Info; if (info.m_class.m_service == service && info.m_class.m_subService == subService) { int num3; int num4; info.m_vehicleAI.GetSize (num, ref instance2.m_vehicles.m_buffer [(int)num], out num3, out num4); if (num3 < num4) { return num; } } } num = instance2.m_vehicles.m_buffer [(int)num].m_nextOwnVehicle; if (++num2 >= 65536) { CODebugBase<LogChannel>.Error (LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace); break; } } return 0; }
public static ushort FindNextCargoParent(ushort sourceBuilding, ItemClass.Service service, ItemClass.SubService subService) { BuildingManager instance = Singleton<BuildingManager>.instance; VehicleManager instance2 = Singleton<VehicleManager>.instance; ushort num = instance.m_buildings.m_buffer [(int)sourceBuilding].m_ownVehicles; ushort result = 0; int num2 = -1; int num3 = 0; while (num != 0) { if ((instance2.m_vehicles.m_buffer [(int)num].m_flags & Vehicle.Flags.WaitingCargo) != Vehicle.Flags.None) { VehicleInfo info = instance2.m_vehicles.m_buffer [(int)num].Info; if (info.m_class.m_service == service && info.m_class.m_subService == subService) { int num4; int b; info.m_vehicleAI.GetSize (num, ref instance2.m_vehicles.m_buffer [(int)num], out num4, out b); int num5 = Mathf.Max (num4 * 255 / Mathf.Max (1, b), (int)instance2.m_vehicles.m_buffer [(int)num].m_waitCounter); if (num5 > num2) { result = num; num2 = num5; } } } num = instance2.m_vehicles.m_buffer [(int)num].m_nextOwnVehicle; if (++num3 >= 65536) { CODebugBase<LogChannel>.Error (LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace); break; } } return result; }
public bool Add(ItemClass item, int amount, int foodType, int index = 0) { if (Type == InventoryType.MULTIPLE) { if (index < 0 || index >= Size) return false; if (Items[index].item_id > -1 && Items[index].item_id != item.item_id) return false; Items[index].Update(item.item_id, amount); AddCollection(item, amount, foodType); return true; } foreach (InventoryItem inve in Items.Values) { if (inve.item_id != item.item_id) continue; inve.Update(item.item_id, amount); AddCollection(item, amount, foodType); return true; } foreach (InventoryItem inve in Items.Values) { if (inve.item_id != -1) continue; inve.Update(item.item_id, amount); AddCollection(item, amount, foodType); return true; } return false; }
public static bool FindPathPosition(Vector3 position, ItemClass.Service service, NetInfo.LaneType laneType, VehicleInfo.VehicleType vehicleTypes, bool allowUnderground, bool requireConnect, float maxDistance, out PathUnit.Position pathPos, RoadManager.VehicleType vehicleType) { PathUnit.Position position2; float num; float num2; return CustomPathManager.FindPathPosition(position, service, laneType, vehicleTypes, allowUnderground, requireConnect, maxDistance, out pathPos, out position2, out num, out num2, vehicleType); }
public ItemType(string name, ItemClass itemClass, int weight, int price = 0) { Name = name; Class = itemClass; Weight = weight; Price = price; }
public new bool CreatePath(out uint unit, ref Randomizer randomizer, uint buildIndex, PathUnit.Position startPosA, PathUnit.Position startPosB, PathUnit.Position endPosA, PathUnit.Position endPosB, PathUnit.Position vehiclePosition, NetInfo.LaneType laneTypes, VehicleInfo.VehicleType vehicleTypes, float maxLength, bool isHeavyVehicle, bool ignoreBlocked, bool stablePath, bool skipQueue, ItemClass.Service vehicleService) { while (!Monitor.TryEnter(this.m_bufferLock, SimulationManager.SYNCHRONIZE_TIMEOUT)) { } uint num; try { if (!this.m_pathUnits.CreateItem(out num, ref randomizer)) { unit = 0u; bool result = false; return result; } this.m_pathUnitCount = (int)(this.m_pathUnits.ItemCount() - 1u); } finally { Monitor.Exit(this.m_bufferLock); } unit = num; byte simulationFlags = createSimulationFlag(isHeavyVehicle, ignoreBlocked, stablePath, vehicleService); assignPathProperties(unit, buildIndex, startPosA, startPosB, endPosA, endPosB, vehiclePosition, laneTypes, vehicleTypes, maxLength, simulationFlags); return findShortestPath(unit, skipQueue); }
public void DeepCloneMaintainReference(TypeModel model) { var collection = new List<ItemClass>() { new ItemClass() { Message = "Hello" } }; var itemClass = new ItemClass() { Message = "Haha" }; var obj = new ComplexTestOfMaintainedReference() { Collection1 = collection, Collection2 = collection, Item1 = itemClass, Item2 = itemClass, Primitive1 = 1, Primitive2 = 2, String1 = "Test" }; var clone = (ComplexTestOfMaintainedReference)model.DeepClone(obj); Assert.AreEqual(obj.Collection1.Count, clone.Collection1.Count); Assert.AreEqual(obj.Collection1[0].Message, clone.Collection1[0].Message); Assert.AreEqual(obj.Collection2.Count, clone.Collection2.Count); Assert.AreEqual(obj.Collection2[0].Message, clone.Collection2[0].Message); Assert.IsTrue(object.ReferenceEquals(clone.Collection1, clone.Collection2), "Collection reference"); Assert.AreEqual(obj.Item1.Message, clone.Item1.Message); Assert.AreEqual(obj.Item2.Message, clone.Item2.Message); Assert.IsTrue(object.ReferenceEquals(clone.Item1, clone.Item2), "Item reference"); Assert.AreEqual(obj.Primitive1, clone.Primitive1); Assert.AreEqual(obj.Primitive2, clone.Primitive2); Assert.AreEqual(obj.String1, clone.String1); }
// Called every frame on building upgrade public static BuildingInfo GetRandomBuildingInfo_Upgrade(Vector3 position, ushort prefabIndex, ref Randomizer r, ItemClass.Service service, ItemClass.SubService subService, ItemClass.Level level, int width, int length, BuildingInfo.ZoningMode zoningMode, int style) { // This method is very fragile, no logging here! var districtId = Singleton<DistrictManager>.instance.GetDistrict(position); // See if there is a special upgraded building var buildingInfo = BuildingThemesManager.instance.GetUpgradeBuildingInfo(prefabIndex, districtId); if (buildingInfo != null) { return buildingInfo; } var areaIndex = BuildingThemesManager.GetAreaIndex(service, subService, level, width, length, zoningMode); // list of possible prefabs var fastList = Singleton<BuildingThemesManager>.instance.GetAreaBuildings(districtId, areaIndex); if (fastList == null || fastList.m_size == 0) { return (BuildingInfo)null; } // select a random prefab from the list int index = r.Int32((uint)fastList.m_size); return PrefabCollection<BuildingInfo>.GetPrefab((uint)fastList.m_buffer[index]); }
public void DeepClone_ClassFieldMaintainsReference(TypeModel model) { var item = new ItemClass() { Message = "Bob yo" }; var container = new ContainerItemClass() { Item1 = item, Item2 = item }; var clone = (ContainerItemClass)model.DeepClone(container); Assert.IsTrue(object.ReferenceEquals(container.Item1, container.Item2)); Assert.IsTrue(object.ReferenceEquals(clone.Item1, clone.Item2)); Assert.AreEqual(container.Item1.Message, clone.Item1.Message); Assert.AreEqual(container.Item2.Message, clone.Item2.Message); container.Item1.Message = "New original"; clone.Item1.Message = "New clone"; Assert.AreEqual(container.Item1.Message, container.Item2.Message); Assert.AreEqual(clone.Item1.Message, clone.Item2.Message); container.Item2.Message = "New original 2"; clone.Item2.Message = "New clone 2"; Assert.AreEqual(container.Item1.Message, container.Item2.Message); Assert.AreEqual(clone.Item1.Message, clone.Item2.Message); }
/// <summary> /// Initializes a new instance of the Item class. /// </summary> /// <param name="itemTypeId">The ID of the item to create.</param> /// <param name="itemClass">The type of item that this is.</param> /// <param name="name">The item's name.</param> /// <param name="description">The item's description.</param> /// <exception cref="System.ArgumentNullException">Any parameter is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException">Item type ID is less than zero.</exception> /// <exception cref="System.ArgumentException">Item class is ItemClass.Undefined.</exception> protected Item(long itemTypeId, ItemClass itemClass, string name, string description) { if (name == null) { throw new ArgumentNullException("name"); } if (description == null) { throw new ArgumentNullException("description"); } if (itemTypeId < 0) { throw new ArgumentOutOfRangeException("itemTypeId", "must be greater than or equal to zero."); } if (itemClass == ItemClass.Undefined) { throw new ArgumentException("cannot be ItemClass.Undefined", "itemClass"); } this.ItemTypeId = itemTypeId; this.ItemClass = itemClass; this.Name = name; this.Description = description; }
public Item(ItemClass type, int amount) : base(ThingType.OBJECT_ITEM) { mType=type; mAmount=amount; mLifetime = Configuration.getValue("game_floorItemDecayTime", 0) * 10; }
public void DeepClone_ClassWithFieldsRef_AsReference(TypeModel model) { var classWithFields = new ClassWithFieldsRef(); var item = new ItemClass() { Message = "Hi there!" }; classWithFields._item1 = item; classWithFields._item2 = item; var list = new List<int> { 2, 4, 5 }; classWithFields._list1 = list; classWithFields._list2 = list; var clone = (ClassWithFieldsRef)model.DeepClone(classWithFields); Assert.AreEqual(classWithFields._item1.Message, clone._item1.Message); Assert.AreEqual(classWithFields._item2.Message, clone._item2.Message); Assert.AreEqual(classWithFields._list1.Count, clone._list1.Count); for (int i = 0; i < classWithFields._list1.Count; i++) { Assert.AreEqual(classWithFields._list1[i], clone._list1[i]); } Assert.AreEqual(classWithFields._list2.Count, clone._list2.Count); for (int i = 0; i < classWithFields._list2.Count; i++) { Assert.AreEqual(classWithFields._list2[i], clone._list2[i]); } Assert.IsTrue(object.ReferenceEquals(classWithFields._item1, classWithFields._item2)); Assert.IsTrue(object.ReferenceEquals(classWithFields._list1, classWithFields._list2)); Assert.IsTrue(object.ReferenceEquals(clone._item1, clone._item2)); Assert.IsTrue(object.ReferenceEquals(clone._list1, clone._list2)); }
public void DeepClone_DictionaryOfClassRef_AsReference(TypeModel model) { var itemClass = new ItemClass() { Message = "hello"}; var dictionary = new DictionaryOfClass() { Collection = new Dictionary<int, ItemClass> { { 1, itemClass }, { 2, itemClass } } }; var clone = (DictionaryOfClass)model.DeepClone(dictionary); Assert.AreEqual(dictionary.Collection.Count, clone.Collection.Count); foreach (var key in dictionary.Collection.Keys) { Assert.AreEqual(dictionary.Collection[key].Message, clone.Collection[key].Message); } Assert.IsTrue(object.ReferenceEquals(dictionary.Collection[1], dictionary.Collection[2]), "Original reference failed"); Assert.IsTrue(object.ReferenceEquals(clone.Collection[1], clone.Collection[2]), "Clone reference not maintained"); }
/// <summary> /// Initializes a new instance of the Munition class. /// Any out-of-range arguments will be clamped into the proper range automatically. /// </summary> /// <param name="itemTypeId">The ID of the item to create.</param> /// <param name="itemClass">The type of item that this is.</param> /// <param name="name">The item's name.</param> /// <param name="description">The item's description.</param> /// <param name="weight">The weight of the munition.</param> /// <param name="integrity">The munition's current integrity.</param> /// <param name="maximumIntegrity">The munition's maximum integrity.</param> /// <param name="integrityLevel">The munition's integrity level.</param> /// <param name="evasionBonus">The munition's evasion bonus.</param> /// <exception cref="System.ArgumentNullException">Any parameter is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException">ItemTypeId is less than zero.</exception> /// <exception cref="System.ArgumentException">ItemClass is ItemClass.Undefined.</exception> protected Munition(long itemTypeId, ItemClass itemClass, string name, string description, float weight, short integrity, short maximumIntegrity, byte integrityLevel, byte evasionBonus) : base(itemTypeId, itemClass, name, description) { this.Weight = weight; this.Integrity = integrity; this.MaximumIntegrity = maximumIntegrity; this.IntegrityLevel = integrityLevel; this.EvasionBonus = evasionBonus; }
public EquipmentSlot(int id, StringName sn, ItemClass[] itemClass, SlotType slot) { _id = id; _displayedName = sn; _allowedItemType = new ItemClass[itemClass.GetLength(0)]; _allowedItemType = itemClass; _item = null; _fullInfo = "-"; _slotType = slot; }
/// <summary> /// Calculated to the similar way the original code would have done it /// </summary> /// <param name="r"></param> /// <param name="width"></param> /// <param name="length"></param> /// <param name="subService"></param> /// <param name="level"></param> /// <returns></returns> public static int CalculateHomeCount(Randomizer r, int width, int length, ItemClass.SubService subService, ItemClass.Level level) { int[][] residentialArray = { new int [] { 20, 25, 30, 35, 40 }, new int [] { 60, 100, 130, 150, 160 } }; int iLevel = (int)(level >= 0 ? level : 0); int density = (subService == ItemClass.SubService.ResidentialLow) ? 0 : 1; int num = residentialArray[density][iLevel]; return Mathf.Max(100, width * length * num + r.Int32(100u)) / 100; }
public static bool CheckZoning(Building b, ItemClass.Zone zone) { int width = b.Width; int length = b.Length; Vector3 vector3_1 = new Vector3(Mathf.Cos(b.m_angle), 0.0f, Mathf.Sin(b.m_angle)); Vector3 vector3_2 = new Vector3(vector3_1.z, 0.0f, -vector3_1.x); Vector3 vector3_3 = vector3_1 * ((float)width * 4f); Vector3 vector3_4 = vector3_2 * ((float)length * 4f); Quad3 quad3 = new Quad3(); quad3.a = b.m_position - vector3_3 - vector3_4; quad3.b = b.m_position + vector3_3 - vector3_4; quad3.c = b.m_position + vector3_3 + vector3_4; quad3.d = b.m_position - vector3_3 + vector3_4; Vector3 vector3_5 = quad3.Min(); Vector3 vector3_6 = quad3.Max(); int num1= Mathf.Max((int)((vector3_5.x - 46f) / 64f + FakeZoneManager.HALFGRID), 0); int num2 = Mathf.Max((int)((vector3_5.z - 46f) / 64f + FakeZoneManager.HALFGRID), 0); int num3 = Mathf.Min((int)((vector3_6.x + 46f) / 64f + FakeZoneManager.HALFGRID), FakeZoneManager.GRIDSIZE - 1); int num4 = Mathf.Min((int)((vector3_6.z + 46f) / 64f + FakeZoneManager.HALFGRID), FakeZoneManager.GRIDSIZE - 1); uint validCells = 0U; ZoneManager instance = Singleton<ZoneManager>.instance; for (int index1 = num2; index1 <= num4; ++index1) { for (int index2 = num1; index2 <= num3; ++index2) { ushort num5 = FakeZoneManager.zoneGrid[index1 * FakeZoneManager.GRIDSIZE + index2]; int num6 = 0; while ((int)num5 != 0) { Vector3 vector3_7 = instance.m_blocks.m_buffer[(int)num5].m_position; if ((double)Mathf.Max(Mathf.Max(vector3_5.x - 46f - vector3_7.x, vector3_5.z - 46f - vector3_7.z), Mathf.Max((float)((double)vector3_7.x - (double)vector3_6.x - 46.0), (float)((double)vector3_7.z - (double)vector3_6.z - 46.0))) < 0.0) CheckZoning(b,zone, ref validCells, ref instance.m_blocks.m_buffer[num5]); num5 = instance.m_blocks.m_buffer[(int)num5].m_nextGridBlock; if (++num6 >= 32768) { CODebugBase<LogChannel>.Error(LogChannel.Core, "Invalid list detected!\n" + System.Environment.StackTrace); break; } } } } for (int index1 = 0; index1 < length; ++index1) { for (int index2 = 0; index2 < width; ++index2) { if (((int)validCells & 1 << (index1 << 3) + index2) == 0) return false; } } return true; }
public void DeepClone_KeyValuePairWithRef(TypeModel model) { var itemClass = new ItemClass() { Message = "ABC" }; var obj = new KeyValuePairWrapper() { Reference = new KeyValuePair<IItemClass, IItemClass>(itemClass, itemClass) }; var clone = (KeyValuePairWrapper)model.DeepClone(obj); Assert.AreEqual(obj.Reference.Key.Message, clone.Reference.Key.Message); Assert.IsTrue(object.ReferenceEquals(obj.Reference.Key, obj.Reference.Value), "Original reference failed"); Assert.IsTrue(object.ReferenceEquals(clone.Reference.Key, clone.Reference.Value), "Clone reference not maintained"); }
private static void CheckZoning(ref Building _this, ItemClass.Zone zone1, ItemClass.Zone zone2, ref uint validCells, ref bool secondary, ref ZoneBlock block) { BuildingInfo.ZoningMode zoningMode = _this.Info.m_zoningMode; int width = _this.Width; int length = _this.Length; Vector3 vector3_1 = new Vector3(Mathf.Cos(_this.m_angle), 0.0f, Mathf.Sin(_this.m_angle)) * 8f; Vector3 vector3_2 = new Vector3(vector3_1.z, 0.0f, -vector3_1.x); int rowCount = block.RowCount; int columnCount = ZoneBlockDetour.GetColumnCount(ref block); // modified Vector3 vector3_3 = new Vector3(Mathf.Cos(block.m_angle), 0.0f, Mathf.Sin(block.m_angle)) * 8f; Vector3 vector3_4 = new Vector3(vector3_3.z, 0.0f, -vector3_3.x); Vector3 vector3_5 = block.m_position - _this.m_position + vector3_1 * (float)((double)width * 0.5 - 0.5) + vector3_2 * (float)((double)length * 0.5 - 0.5); for (int z = 0; z < rowCount; ++z) { Vector3 vector3_6 = ((float)z - 3.5f) * vector3_4; for (int x = 0; (long)x < columnCount; ++x) // modified { if (((long)block.m_valid & ~(long)block.m_shared & 1L << (z << 3 | x)) != 0L) { ItemClass.Zone zone = block.GetZone(x, z); bool flag1 = zone == zone1; if (zone == zone2 && zone2 != ItemClass.Zone.None) { flag1 = true; secondary = true; } if (flag1) { Vector3 vector3_7 = ((float)x - 3.5f) * vector3_3; Vector3 vector3_8 = vector3_5 + vector3_7 + vector3_6; float num1 = (float)((double)vector3_1.x * (double)vector3_8.x + (double)vector3_1.z * (double)vector3_8.z); float num2 = (float)((double)vector3_2.x * (double)vector3_8.x + (double)vector3_2.z * (double)vector3_8.z); int num3 = Mathf.RoundToInt(num1 / 64f); int num4 = Mathf.RoundToInt(num2 / 64f); bool flag2 = false; if (zoningMode == BuildingInfo.ZoningMode.Straight) flag2 = num4 == 0; else if (zoningMode == BuildingInfo.ZoningMode.CornerLeft) flag2 = num4 == 0 && num3 >= width - 2 || num4 <= 1 && num3 == width - 1; else if (zoningMode == BuildingInfo.ZoningMode.CornerRight) flag2 = num4 == 0 && num3 <= 1 || num4 <= 1 && num3 == 0; if ((!flag2 || x == 0) && (num3 >= 0 && num4 >= 0) && (num3 < width && num4 < length)) validCells = validCells | (uint)(1 << (num4 << 3) + num3); } } } } }
public void add(int a, string b, Texture2D c, string d) { ItemClass newItem = new ItemClass (a, b, c, d); for (int i=0; i<list.Length; i++) { if (list[i].getID() == -1) { list[i] = newItem; list[i].count++; break; } if (list[i].getID() == a){ list[i].count++; break; } } }
private static void CheckZoning(Building bz, ItemClass.Zone zone, ref uint validCells, ref ZoneBlock block) { BuildingInfo.ZoningMode zoningMode = bz.Info.m_zoningMode; int width = bz.Width; int length = bz.Length; Vector3 a = new Vector3(Mathf.Cos(bz.m_angle), 0f, Mathf.Sin(bz.m_angle)) * 8f; Vector3 a2 = new Vector3(a.z, 0f, -a.x); int rowCount = block.RowCount; Vector3 a3 = new Vector3(Mathf.Cos(block.m_angle), 0f, Mathf.Sin(block.m_angle)) * 8f; Vector3 a4 = new Vector3(a3.z, 0f, -a3.x); Vector3 a5 = block.m_position - bz.m_position + a * ((float)width * 0.5f - 0.5f) + a2 * ((float)length * 0.5f - 0.5f); for (int i = 0; i < rowCount; i++) { Vector3 b = ((float)i - 3.5f) * a4; int num = 0; while ((long)num < 4L) { if ((block.m_valid & ~block.m_shared & 1uL << (i << 3 | num)) != 0uL && block.GetZone(num, i) == zone) { Vector3 b2 = ((float)num - 3.5f) * a3; Vector3 vector = a5 + b2 + b; float num2 = a.x * vector.x + a.z * vector.z; float num3 = a2.x * vector.x + a2.z * vector.z; int num4 = Mathf.RoundToInt(num2 / 64f); int num5 = Mathf.RoundToInt(num3 / 64f); bool flag = false; if (zoningMode == BuildingInfo.ZoningMode.Straight) { flag = (num5 == 0); } else if (zoningMode == BuildingInfo.ZoningMode.CornerLeft) { flag = ((num5 == 0 && num4 >= width - 2) || (num5 <= 1 && num4 == width - 1)); } else if (zoningMode == BuildingInfo.ZoningMode.CornerRight) { flag = ((num5 == 0 && num4 <= 1) || (num5 <= 1 && num4 == 0)); } if ((!flag || num == 0) && num4 >= 0 && num5 >= 0 && num4 < width && num5 < length) { validCells |= 1u << (num5 << 3) + num4; } } num++; } } }
public Texture2D lootRandomizer() { ItemClass items = new ItemClass(); //string returnString = string.Empty; Texture2D returnString = ItemClass.emptySlot; int randomNumber = Random.Range (0,6); //Debug.Log ("Loot Randomizer number: " + randomNumber); switch (randomNumber) { case 0: returnString = items.healthPot.itemIcon; Debug.Log ("health pot"); break; case 1: returnString = items.weapon.itemIcon; Debug.Log ("grant's beard"); break; case 2: returnString = items.torch.itemIcon; Debug.Log ("torch"); break; case 3: returnString = items.bones.itemIcon; Debug.Log ("bones"); break; case 4: returnString = items.axe.itemIcon; Debug.Log ("axe"); break; case 5: returnString = items.battery.itemIcon; Debug.Log ("battery"); break; case 6: returnString = items.memStick.itemIcon; Debug.Log ("memstick"); break; default: returnString = ItemClass.emptySlot; break; } return returnString; }
public int GetTileNodeCount(int x, int z, ItemClass.Service service, ItemClass.SubService subService) { int num = Singleton<GameAreaManager>.instance.GetTileIndex(x, z); if (num != -1) { num *= 17; if (subService != ItemClass.SubService.None) { num += subService - ItemClass.SubService.IndustrialOre - 1 + 12; } else { num += service - ItemClass.Service.Office - 1; } return m_tileNodesCount[num]; } return 0; }
public void AddTileNode(Vector3 position, ItemClass.Service service, ItemClass.SubService subService) { if (service > ItemClass.Service.Office) { int num = Singleton<GameAreaManager>.instance.GetAreaIndex(position); if (num != -1) { num *= 17; if (subService != ItemClass.SubService.None) { num += subService - ItemClass.SubService.IndustrialOre - 1 + 12; } else { num += service - ItemClass.Service.Office - 1; } m_tileNodesCount[num] += 1 ; } } }
public static List<Mod> CreateMods(string attribute, ItemClass ic) { List<Mod> mods = new List<Mod>(); List<float> values = new List<float>(); foreach (Match match in numberfilter.Matches(attribute)) { values.Add(float.Parse(match.Value, System.Globalization.CultureInfo.InvariantCulture)); } string at = numberfilter.Replace(attribute, "#"); if (at == "+# to all Attributes") { mods.Add(new Mod() { itemclass = ic, Value = values, Attribute = "+# to Strength" }); mods.Add(new Mod() { itemclass = ic, Value = values, Attribute = "+# to Dexterity" }); mods.Add(new Mod() { itemclass = ic, Value = values, Attribute = "+# to Intelligence" }); } else { mods.Add(new Mod() { itemclass = ic, Value = values, Attribute = at }); } return mods; }
public ushort FindBuilding(Vector3 pos, float maxDistance, ItemClass.Service service, ItemClass.SubService subService, Building.Flags flagsRequired, Building.Flags flagsForbidden) { int num1 = Mathf.Max((int)(((double)pos.x - (double)maxDistance) / 64.0 + 135.0), 0); int num2 = Mathf.Max((int)(((double)pos.z - (double)maxDistance) / 64.0 + 135.0), 0); int num3 = Mathf.Min((int)(((double)pos.x + (double)maxDistance) / 64.0 + 135.0), 269); int num4 = Mathf.Min((int)(((double)pos.z + (double)maxDistance) / 64.0 + 135.0), 269); ushort num5 = (ushort)0; float num6 = maxDistance * maxDistance; for (int index1 = num2; index1 <= num4; ++index1) { for (int index2 = num1; index2 <= num3; ++index2) { ushort num7 = this.m_buildingGrid[index1 * 270 + index2]; int num8 = 0; while ((int)num7 != 0) { //mod: add null check BuildingInfo info = this.m_buildings.m_buffer[(int)num7].Info; if (info != null) { if ((info.m_class.m_service == service || service == ItemClass.Service.None) && (info.m_class.m_subService == subService || subService == ItemClass.SubService.None) && (this.m_buildings.m_buffer[(int)num7].m_flags & (flagsRequired | flagsForbidden)) == flagsRequired) { float num9 = Vector3.SqrMagnitude(pos - this.m_buildings.m_buffer[(int)num7].m_position); if ((double)num9 < (double)num6) { num5 = num7; num6 = num9; } } } num7 = this.m_buildings.m_buffer[(int)num7].m_nextGridBuilding; if (++num8 >= 49152) { CODebugBase<LogChannel>.Error(LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace); break; } } } } return num5; }
void AddCollection(ItemClass item, int amount, int foodType) { FoodClass food = null; switch (foodType) { case 0: //Raw food food = ((ItemFood)item).Raw; break; case 1: //boiled food food = ((ItemFood)item).Boil; break; case 2: //Raw food food = ((ItemFood)item).Bake; break; } if (food == null) return; Food.Add(food, amount); if (FoodParams) FoodParams.Food = Food; if (TasteParam) TasteParam.Progress = Food.Taste; }
// called before a new building spawns on empty land (ZoneBlock.SimulationStep) public static BuildingInfo GetRandomBuildingInfo_Spawn(Vector3 position, ref Randomizer r, ItemClass.Service service, ItemClass.SubService subService, ItemClass.Level level, int width, int length, BuildingInfo.ZoningMode zoningMode, int style) { if (Debugger.Enabled) { Debugger.Log("GetRandomBuildingInfo_Spawn called!"); } var areaIndex = BuildingThemesManager.GetAreaIndex(service, subService, level, width, length, zoningMode); var districtId = Singleton<DistrictManager>.instance.GetDistrict(position); FastList<ushort> fastList = Singleton<BuildingThemesManager>.instance.GetAreaBuildings(districtId, areaIndex); if (fastList == null || fastList.m_size == 0) { return (BuildingInfo)null; } // select a random prefab from the list int index = r.Int32((uint)fastList.m_size); return PrefabCollection<BuildingInfo>.GetPrefab((uint)fastList.m_buffer[index]); }
public static void EndSession(ItemClass.Availability availability) { try { if (Mod.IsEnabled && Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableAll) || Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableEndSession)) { if (Mod.DEBUG_LOG_ON) { Helper.dbgLog("End Session telemetry disabled."); } return; } TelemetryKH telemetry = new TelemetryKH(); telemetry.AddEvent("end_session", new Telemetry.Pair[] { new Telemetry.Pair("type", availability.ToString()) }); telemetry.Push(); } catch (Exception ex) { CODebugBase<LogChannel>.Warn(LogChannel.HTTP, ex.GetType() + ": Telemetry event failed " + ex.Message); } }
public void DeepClone_KeyValuePairWithRefDefinedBefore(TypeModel model) { var itemClass = new ItemClass() { Message = "ABC" }; var obj = new KeyValuePairWrapper() { ListRefDefinedBefore = new KeyValuePair<IItemClass, List<IItemClass>> ( itemClass, new List<IItemClass>() { new ItemClass() { Message = "Stewie" }, itemClass } ) }; var clone = (KeyValuePairWrapper)model.DeepClone(obj); Assert.AreEqual(obj.ListRefDefinedBefore.Key.Message, clone.ListRefDefinedBefore.Key.Message); Assert.AreEqual(obj.ListRefDefinedBefore.Value.Count, clone.ListRefDefinedBefore.Value.Count); Assert.AreEqual(obj.ListRefDefinedBefore.Value[0].Message, clone.ListRefDefinedBefore.Value[0].Message); Assert.AreEqual(obj.ListRefDefinedBefore.Value[1].Message, clone.ListRefDefinedBefore.Value[1].Message); Assert.IsTrue(object.ReferenceEquals(obj.ListRefDefinedBefore.Key, obj.ListRefDefinedBefore.Value[1]), "Original reference failed"); Assert.IsTrue(object.ReferenceEquals(clone.ListRefDefinedBefore.Key, clone.ListRefDefinedBefore.Value[1]), "Clone reference not maintained"); }
public Item(IPersistentData persistentData, JObject val, ItemSlot itemSlot = ItemSlot.Unequipable, bool isGem = false) { JsonBase = val; Slot = itemSlot; Width = val["w"].Value <int>(); Height = val["h"].Value <int>(); if (val["x"] != null) { X = val["x"].Value <int>(); } if (val["y"] != null) { Y = val["y"].Value <int>(); } if (val["name"] != null) { NameLine = FilterJsonString(val["name"].Value <string>()); } JToken iconToken; if (val.TryGetValue("icon", out iconToken)) { _iconUrl = iconToken.Value <string>(); } Frame = (FrameType)val["frameType"].Value <int>(); TypeLine = FilterJsonString(val["typeLine"].Value <string>()); if (isGem) { // BaseType will be null for socketed gems. ItemClass = ItemClassEx.ItemClassForGem(TypeLine); Tags = ItemClass.ToTags(); } else { if (Frame == FrameType.Magic) { BaseType = persistentData.EquipmentData.ItemBaseFromTypeline(TypeLine); } else if ((Frame == FrameType.Unique || Frame == FrameType.Foil) && persistentData.EquipmentData.UniqueBaseDictionary.ContainsKey(NameLine)) { BaseType = persistentData.EquipmentData.UniqueBaseDictionary[NameLine]; } else { // item is not unique or the unique is unknown ItemBase iBase; persistentData.EquipmentData.ItemBaseDictionary.TryGetValue(TypeLine, out iBase); BaseType = iBase; } // For known bases, images are only downloaded if the item is unique or foil. All other items should // always have the same image. (except alt art non-uniques that are rare enough to be ignored) var loadImageFromIconUrl = _iconUrl != null && (BaseType == null || Frame == FrameType.Unique || Frame == FrameType.Foil); if (BaseType == null) { BaseType = new ItemBase(persistentData.EquipmentData.ItemImageService, itemSlot, TypeLine, Keywords == null ? "" : Keywords.FirstOrDefault(), Frame); } ItemClass = BaseType.ItemClass; Tags = BaseType.Tags; if (loadImageFromIconUrl) { Image = BaseType.Image.AsDefaultForImageFromUrl( persistentData.EquipmentData.ItemImageService, _iconUrl); } else { Image = BaseType.Image; } } if (val["properties"] != null) { foreach (var obj in val["properties"]) { Properties.Add(ItemModFromJson(obj, ModLocation.Property)); } if (Properties.Any(m => !m.Values.Any())) { // The name of one property of gems contains the Keywords of that gem. Keywords = Properties.First(m => !m.Values.Any()).Attribute.Split(',').Select(i => i.Trim()).ToList(); } } if (val["requirements"] != null) { var mods = val["requirements"].Select(t => ItemModFromJson(t, ModLocation.Requirement)).ToList(); if (!mods.Any(m => m.Attribute.StartsWith("Requires "))) { var modsToMerge = new [] { mods.FirstOrDefault(m => m.Attribute == "Level #"), mods.FirstOrDefault(m => m.Attribute == "# Str"), mods.FirstOrDefault(m => m.Attribute == "# Dex"), mods.FirstOrDefault(m => m.Attribute == "# Int") }.Where(m => m != null).ToList(); modsToMerge.ForEach(m => mods.Remove(m)); mods.Add(new ItemMod( "Requires " + string.Join(", ", modsToMerge.Select(m => m.Attribute)), false, modsToMerge.Select(m => m.Values).Flatten(), modsToMerge.Select(m => m.ValueColors).Flatten() )); } _requirements.AddRange(mods); } if (val["implicitMods"] != null) { foreach (var s in val["implicitMods"].Values <string>()) { _implicitMods.Add(ItemModFromString(FixOldRanges(s), ModLocation.Implicit)); } } if (val["explicitMods"] != null) { foreach (var s in val["explicitMods"].Values <string>()) { ExplicitMods.Add(ItemModFromString(FixOldRanges(s), ModLocation.Explicit)); } } if (val["craftedMods"] != null) { foreach (var s in val["craftedMods"].Values <string>()) { CraftedMods.Add(ItemModFromString(FixOldRanges(s), ModLocation.Crafted)); } } if (val["flavourText"] != null) { FlavourText = string.Join("\r\n", val["flavourText"].Values <string>().Select(s => s.Replace("\r", ""))); } var sockets = new List <int>(); if (val["sockets"] != null) { foreach (var obj in (JArray)val["sockets"]) { sockets.Add(obj["group"].Value <int>()); } } if (val["socketedItems"] != null) { int socket = 0; foreach (JObject obj in (JArray)val["socketedItems"]) { var item = new Item(persistentData, obj, isGem: true) { SocketGroup = sockets[socket++] }; _gems.Add(item); } } }
public override void Execute(List <string> _params, CommandSenderInfo _senderInfo) { try { if (_params.Count != 1 && _params.Count != 2 && _params.Count != 7) { SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] Wrong number of arguments, expected 1, 2 or 7, found {0}", _params.Count)); return; } if (_params[0].ToLower().Equals("off")) { if (Shop.IsEnabled) { Shop.IsEnabled = false; Config.WriteXml(); SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] Shop has been set to off")); return; } else { SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] Shop is already off")); return; } } else if (_params[0].ToLower().Equals("on")) { if (!Shop.IsEnabled) { Shop.IsEnabled = true; Config.WriteXml(); SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] Shop has been set to on")); return; } else { SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] Shop is already on")); return; } } else if (_params[0].ToLower().Equals("add")) { if (_params.Count != 7) { SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] Wrong number of arguments, expected 7, found {0}", _params.Count)); return; } else { if (Shop.IsEnabled) { ItemValue _itemValue = ItemClass.GetItem(_params[1], false); if (_itemValue.type == ItemValue.None.type) { SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] Item could not be found: {0}", _params[1])); return; } else { if (!int.TryParse(_params[3], out int _count)) { SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] Invalid item count: {0}", _params[3])); return; } else { if (_count > _itemValue.ItemClass.Stacknumber.Value) { _count = _itemValue.ItemClass.Stacknumber.Value; } if (!int.TryParse(_params[4], out int _quality)) { SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] Invalid item quality: {0}", _params[4])); return; } else { if (!int.TryParse(_params[5], out int _price)) { SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] Invalid item price: {0}", _params[5])); return; } else { if (_quality < 1) { _quality = 1; } else if (_quality > 600) { _quality = 600; } foreach (var _item in Shop.Dict) { if (_item.Value[0] == _params[1]) { Shop.Dict1.TryGetValue(_item.Key, out int[] _values); if (_values[0] == _count && _values[1] == _quality) { SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] Unable to add item {0}. It is already on the shop list", _params[1])); return; } } } if (!Shop.Categories.Contains(_params[6])) { Shop.Categories.Add(_params[6]); } string[] _strings = new string[] { _params[1], _params[2], _params[6] }; int[] _integers = new int[] { _count, _quality, _price }; if (!Shop.Dict.ContainsKey(Shop.Dict.Count + 1)) { Shop.Dict.Add(Shop.Dict.Count + 1, _strings); Shop.Dict1.Add(Shop.Dict1.Count + 1, _integers); Shop.UpdateXml(); SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] Item {0} has been added to the shop", _params[1])); return; } else if (!Shop.Dict.ContainsKey(Shop.Dict.Count + 2)) { Shop.Dict.Add(Shop.Dict.Count + 2, _strings); Shop.Dict1.Add(Shop.Dict1.Count + 2, _integers); Shop.UpdateXml(); SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] Item {0} has been added to the shop", _params[1])); return; } else { SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] Unable to add item {0}. Shop id are out of order. Check the xml file", _params[1])); return; } } } } } } else { SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] Shop is not enabled. Unable to write to the xml file")); return; } } } else if (_params[0].ToLower().Equals("remove")) { if (_params.Count != 2) { SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] Wrong number of arguments, expected 2, found {0}", _params.Count)); return; } else { if (!int.TryParse(_params[1], out int _number)) { SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] Invalid id: {0}", _params[1])); return; } else { if (!Shop.Dict.ContainsKey(_number - 1)) { SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] Id not found on the shop list: {0}", _params[1])); return; } else { Shop.Dict.Remove(_number - 1); Shop.Dict1.Remove(_number - 1); SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] Id {0} has been removed from the shop list", _number)); return; } } } } else if (_params[0].ToLower().Equals("list")) { if (_params.Count != 1) { SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] Wrong number of arguments, expected 1, found {0}", _params.Count)); return; } else { if (Shop.Dict.Count > 0) { foreach (var _item in Shop.Dict) { if (Shop.Dict1.TryGetValue(_item.Key, out int[] _values))
protected override bool CheckItemClass(ItemClass itemClass) => itemClass.m_layer == ItemClass.Layer.Default && itemClass switch { { m_service : ItemClass.Service.Road } => true,
internal void GetWeaponPositions(CellType[,] cellTypes) { ItemClass.GetItem(ItemSlot.WEAPON, WeaponEquippedID).GetWeaponPositions(cellTypes); //Pull slot locations from class next }
internal void GetPsiPositions(CellType[,] cellTypes) { ItemClass.GetItem(ItemSlot.MISC, MiscEquippedID).GetPsiPositions(cellTypes); //Pull slot locations from class next }
private void btnUpdate_Click(object sender, EventArgs e) { ProgressDialog pd = null; try { ItemClass item = this.comboBox1.SelectedItem as ItemClass; if (item == null) { MessageBox.Show("请先选择要更新的图层", "提示"); return; } ItemClass fd_item = this.comboBox2.SelectedItem as ItemClass; if (fd_item == null) { MessageBox.Show("请先选择要更新的字段", "提示"); return; } ILayer layer = item.Value as ILayer; IFeatureLayer featLayer = layer as IFeatureLayer; IFeatureClass fc = featLayer.FeatureClass; // string fdName = fd_item.Caption; // int fCount = fc.FeatureCount(null); if (fCount > 0) { IFeatureCursor pcursor = fc.Update(null, false); IFeature pf = pcursor.NextFeature(); int index = fc.FindField(fdName); pd = new ProgressDialog(); pd.Text = "进度"; pd.Message = "更新字段索引Index中......"; pd.Minimum = 0; pd.Maximum = fCount; pd.Show(this); int n = 0; while (pf != null) { n = n + 1; if (n % 200 == 0) { pd.Value = n; pd.Message = "更新字段索引Index中......" + pd.Value.ToString() + "/" + pd.Maximum.ToString(); Application.DoEvents(); pcursor.Flush(); } pf.set_Value(index, n); pcursor.UpdateFeature(pf); // pf = pcursor.NextFeature(); } pcursor.Flush(); if (pcursor != null) { TokayWorkspace.ComRelease(pcursor); pcursor = null; } if (pd != null) { pd.Dispose(); pd = null; } MessageBox.Show("更新完毕!", "提示"); } } catch (Exception ee) { MessageBox.Show(ee.StackTrace, "提示"); } finally { if (pd != null) { pd.Dispose(); pd = null; } } }
/// <returns>all mods in this group that can be can be crafted onto an item with the given tags and class /// </returns> public IEnumerable <IMod> GetMatchingMods(Tags tags, ItemClass itemClass) { return(_mods.Where(m => m.Matches(tags, itemClass))); }
/// <summary> /// Returns all <see cref="ItemSlot"/>s items of this class can be slotted into. /// </summary> public static ItemSlot ItemSlots(this ItemClass itemClass) { switch (itemClass) { case ItemClass.OneHandSword: case ItemClass.ThrustingOneHandSword: case ItemClass.OneHandAxe: case ItemClass.OneHandMace: case ItemClass.Sceptre: case ItemClass.Dagger: case ItemClass.Claw: case ItemClass.Wand: return(ItemSlot.MainHand | ItemSlot.OffHand); case ItemClass.FishingRod: case ItemClass.TwoHandSword: case ItemClass.TwoHandAxe: case ItemClass.TwoHandMace: case ItemClass.Bow: case ItemClass.Staff: return(ItemSlot.MainHand); case ItemClass.Belt: return(ItemSlot.Belt); case ItemClass.Ring: return(ItemSlot.Ring | ItemSlot.Ring2); case ItemClass.Amulet: return(ItemSlot.Amulet); case ItemClass.Quiver: case ItemClass.Shield: return(ItemSlot.OffHand); case ItemClass.Boots: return(ItemSlot.Boots); case ItemClass.BodyArmour: return(ItemSlot.BodyArmour); case ItemClass.Gloves: return(ItemSlot.Gloves); case ItemClass.Helmet: return(ItemSlot.Helm); case ItemClass.ActiveSkillGem: case ItemClass.SupportSkillGem: return(ItemSlot.Gem); case ItemClass.LifeFlask: case ItemClass.ManaFlask: case ItemClass.HybridFlask: case ItemClass.UtilityFlask: case ItemClass.CriticalUtilityFlask: case ItemClass.Jewel: case ItemClass.Unknown: case ItemClass.Any: return(ItemSlot.Unequipable); default: throw new ArgumentOutOfRangeException(nameof(itemClass), itemClass, null); } }
/// <summary> /// Tries to convert a string that is an Id from the GGPK's ItemClasses.dat to an <see cref="ItemClass"/> /// instance. /// </summary> public static bool TryParse(string ggpkItemClass, out ItemClass itemClass) { return(Enum.TryParse(ggpkItemClass.Replace(" ", ""), true, out itemClass)); }
public static void SpawnItems(ClientInfo _cInfo) { try { if (StartingItems.ItemList.Count > 0) { World world = GameManager.Instance.World; if (world.Players.dict.ContainsKey(_cInfo.entityId)) { EntityPlayer _player = PersistentOperations.GetEntityPlayer(_cInfo.playerId); if (_player != null && _player.IsSpawned() && !_player.IsDead()) { PersistentContainer.Instance.Players[_cInfo.playerId].StartingItems = true; PersistentContainer.Instance.Save(); List <string> _itemList = StartingItems.ItemList.Keys.ToList(); for (int i = 0; i < _itemList.Count; i++) { string _item = _itemList[i]; int[] _itemData; StartingItems.ItemList.TryGetValue(_item, out _itemData); ItemValue _itemValue = new ItemValue(ItemClass.GetItem(_item, false).type, false); if (_itemValue.HasQuality && _itemData[1] > 0) { _itemValue.Quality = _itemData[1]; } EntityItem entityItem = new EntityItem(); entityItem = (EntityItem)EntityFactory.CreateEntity(new EntityCreationData { entityClass = EntityClass.FromString("item"), id = EntityFactory.nextEntityID++, itemStack = new ItemStack(_itemValue, _itemData[0]), pos = world.Players.dict[_cInfo.entityId].position, rot = new Vector3(20f, 0f, 20f), lifetime = 60f, belongsPlayerId = _cInfo.entityId }); world.SpawnEntityInWorld(entityItem); _cInfo.SendPackage(NetPackageManager.GetPackage <NetPackageEntityCollect>().Setup(entityItem.entityId, _cInfo.entityId)); world.RemoveEntity(entityItem.entityId, EnumRemoveEntityReason.Despawned); Thread.Sleep(TimeSpan.FromSeconds(1)); } Log.Out(string.Format("[SERVERTOOLS] {0} with steam id {1} received their starting items", _cInfo.playerName, _cInfo.playerId)); SdtdConsole.Instance.Output(string.Format("[SERVERTOOLS] {0} with steam id {1} received their starting items", _cInfo.playerName, _cInfo.playerId)); string _phrase806; if (!Phrases.Dict.TryGetValue(806, out _phrase806)) { _phrase806 = "You have received the starting items. Check your inventory. If full, check the ground."; } ChatHook.ChatMessage(_cInfo, LoadConfig.Chat_Response_Color + _phrase806 + "[-]", -1, LoadConfig.Server_Response_Name, EChatType.Whisper, null); } else { SdtdConsole.Instance.Output(string.Format("Player with steamd Id {0} has not spawned. Unable to give starting items", _cInfo.playerId)); } } } } catch (Exception e) { Log.Out(string.Format("[SERVERTOOLS] Error in GiveStartingItemsConsole.SpawnItems: {0}", e.Message)); } }
public void Enchant(IEntity item, ItemClass itemClass, int itemLevel, IRandom random, RarityPicker rarityPicker) { var rarity = rarityPicker.Rarity; if (rarity == "Normal") { return; } if (rarity == "Magic") { SetEnchantedLineInDescription(item); if (random.PickOneFrom(1, 2) == 1) { var enchantPower = (int)(itemLevel * 1.5); var enchantment1 = GetEnchantmentFor(item, itemClass, enchantPower, random); ApplyEnchantmentTo(item, enchantment1); if (random.PickOneFrom(1, 2) == 1) { _itemNamer.NameMagicItem(item, enchantment1, null); } else { _itemNamer.NameMagicItem(item, null, enchantment1); } } else { var enchantPower = itemLevel; var enchantment1 = GetEnchantmentFor(item, itemClass, enchantPower, random); ApplyEnchantmentTo(item, enchantment1); var enchantment2 = GetEnchantmentFor(item, itemClass, enchantPower, random); ApplyEnchantmentTo(item, enchantment2); _itemNamer.NameMagicItem(item, enchantment1, enchantment2); } return; } if (rarity == "Rare") { var numberOfEnchantments = random.Between(4, 6); var enchantPower = itemLevel; for (int i = 0; i < numberOfEnchantments; i++) { var enchantment = GetEnchantmentFor(item, itemClass, enchantPower, random); ApplyEnchantmentTo(item, enchantment); } _itemNamer.NameRareItem(item, itemClass, random); return; } throw new ApplicationException("Unknown rarity in Enchant: " + rarity); }
public void SetKey(int key, ItemClass cls) { itemOnKey[key] = cls; }
public void CustomSimulationStep(ushort vehicleId, ref Vehicle vehicleData, Vector3 physicsLodRefPos) { #if DEBUG bool vehDebug = DebugSettings.VehicleId == 0 || DebugSettings.VehicleId == vehicleId; bool logParkingAi = DebugSwitch.BasicParkingAILog.Get() && vehDebug; #else var logParkingAi = false; #endif if ((vehicleData.m_flags & Vehicle.Flags.WaitingPath) != 0) { PathManager pathManager = Singleton <PathManager> .instance; byte pathFindFlags = pathManager.m_pathUnits.m_buffer[vehicleData.m_path].m_pathFindFlags; // NON-STOCK CODE START ExtPathState mainPathState = ExtPathState.Calculating; if ((pathFindFlags & PathUnit.FLAG_FAILED) != 0 || vehicleData.m_path == 0) { mainPathState = ExtPathState.Failed; } else if ((pathFindFlags & PathUnit.FLAG_READY) != 0) { mainPathState = ExtPathState.Ready; } #if DEBUG uint logVehiclePath = vehicleData.m_path; Log._DebugIf( logParkingAi, () => $"CustomCarAI.CustomSimulationStep({vehicleId}): " + $"Path: {logVehiclePath}, mainPathState={mainPathState}"); #endif IExtVehicleManager extVehicleManager = Constants.ManagerFactory.ExtVehicleManager; ExtSoftPathState finalPathState = ExtCitizenInstance.ConvertPathStateToSoftPathState(mainPathState); if (Options.parkingAI && extVehicleManager.ExtVehicles[vehicleId].vehicleType == ExtVehicleType.PassengerCar) { ushort driverInstanceId = extVehicleManager.GetDriverInstanceId(vehicleId, ref vehicleData); finalPathState = AdvancedParkingManager.Instance.UpdateCarPathState( vehicleId, ref vehicleData, ref Singleton <CitizenManager> .instance.m_instances.m_buffer[driverInstanceId], ref ExtCitizenInstanceManager.Instance.ExtInstances[driverInstanceId], mainPathState); #if DEBUG if (logParkingAi) { Log._Debug($"CustomCarAI.CustomSimulationStep({vehicleId}): " + $"Applied Parking AI logic. Path: {vehicleData.m_path}, " + $"mainPathState={mainPathState}, finalPathState={finalPathState}"); } #endif } switch (finalPathState) { case ExtSoftPathState.Ready: { #if DEBUG if (logParkingAi) { Log._Debug( $"CustomCarAI.CustomSimulationStep({vehicleId}): Path-finding " + $"succeeded for vehicle {vehicleId} (finalPathState={finalPathState}). " + $"Path: {vehicleData.m_path} -- calling CarAI.PathfindSuccess"); } #endif vehicleData.m_pathPositionIndex = 255; vehicleData.m_flags &= ~Vehicle.Flags.WaitingPath; vehicleData.m_flags &= ~Vehicle.Flags.Arriving; PathfindSuccess(vehicleId, ref vehicleData); TrySpawn(vehicleId, ref vehicleData); break; } case ExtSoftPathState.Ignore: { #if DEBUG if (logParkingAi) { Log._Debug( $"CustomCarAI.CustomSimulationStep({vehicleId}): Path-finding " + $"result shall be ignored for vehicle {vehicleId} " + $"(finalPathState={finalPathState}). Path: {vehicleData.m_path} -- ignoring"); } #endif return; } case ExtSoftPathState.Calculating: default: { #if DEBUG if (logParkingAi) { Log._Debug( $"CustomCarAI.CustomSimulationStep({vehicleId}): Path-finding " + $"result undetermined for vehicle {vehicleId} (finalPathState={finalPathState}). " + $"Path: {vehicleData.m_path} -- continue"); } #endif break; } case ExtSoftPathState.FailedHard: { #if DEBUG if (logParkingAi) { Log._Debug( $"CustomCarAI.CustomSimulationStep({vehicleId}): HARD path-finding " + $"failure for vehicle {vehicleId} (finalPathState={finalPathState}). " + $"Path: {vehicleData.m_path} -- calling CarAI.PathfindFailure"); } #endif vehicleData.m_flags &= ~Vehicle.Flags.WaitingPath; Singleton <PathManager> .instance.ReleasePath(vehicleData.m_path); vehicleData.m_path = 0u; PathfindFailure(vehicleId, ref vehicleData); return; } case ExtSoftPathState.FailedSoft: { #if DEBUG if (logParkingAi) { Log._Debug( $"CustomCarAI.CustomSimulationStep({vehicleId}): SOFT path-finding " + $"failure for vehicle {vehicleId} (finalPathState={finalPathState}). " + $"Path: {vehicleData.m_path} -- calling CarAI.InvalidPath"); } #endif // path mode has been updated, repeat path-finding vehicleData.m_flags &= ~Vehicle.Flags.WaitingPath; InvalidPath(vehicleId, ref vehicleData, vehicleId, ref vehicleData); break; } } // NON-STOCK CODE END } else { if ((vehicleData.m_flags & Vehicle.Flags.WaitingSpace) != 0) { TrySpawn(vehicleId, ref vehicleData); } } // NON-STOCK CODE START IExtVehicleManager extVehicleMan = Constants.ManagerFactory.ExtVehicleManager; extVehicleMan.UpdateVehiclePosition(vehicleId, ref vehicleData); if (Options.advancedAI && (vehicleData.m_flags & Vehicle.Flags.Spawned) != 0) { extVehicleMan.LogTraffic(vehicleId, ref vehicleData); } // NON-STOCK CODE END Vector3 lastFramePosition = vehicleData.GetLastFramePosition(); int lodPhysics; if (Vector3.SqrMagnitude(physicsLodRefPos - lastFramePosition) >= 1100f * 1100f) { lodPhysics = 2; } else if (Vector3.SqrMagnitude( Singleton <SimulationManager> .instance.m_simulationView.m_position - lastFramePosition) >= 500f * 500f) { lodPhysics = 1; } else { lodPhysics = 0; } SimulationStep(vehicleId, ref vehicleData, vehicleId, ref vehicleData, lodPhysics); if (vehicleData.m_leadingVehicle == 0 && vehicleData.m_trailingVehicle != 0) { VehicleManager vehManager = Singleton <VehicleManager> .instance; ushort trailerId = vehicleData.m_trailingVehicle; int numIters = 0; while (trailerId != 0) { ushort trailingVehicle = vehManager.m_vehicles.m_buffer[trailerId].m_trailingVehicle; VehicleInfo info = vehManager.m_vehicles.m_buffer[trailerId].Info; info.m_vehicleAI.SimulationStep( trailerId, ref vehManager.m_vehicles.m_buffer[trailerId], vehicleId, ref vehicleData, lodPhysics); trailerId = trailingVehicle; if (++numIters > 16384) { CODebugBase <LogChannel> .Error( LogChannel.Core, $"Invalid list detected!\n{Environment.StackTrace}"); break; } } } int privateServiceIndex = ItemClass.GetPrivateServiceIndex(m_info.m_class.m_service); int maxBlockCounter = (privateServiceIndex == -1) ? 150 : 100; if ((vehicleData.m_flags & (Vehicle.Flags.Spawned | Vehicle.Flags.WaitingPath | Vehicle.Flags.WaitingSpace)) == 0 && vehicleData.m_cargoParent == 0) { Singleton <VehicleManager> .instance.ReleaseVehicle(vehicleId); } else if (vehicleData.m_blockCounter >= maxBlockCounter) { // NON-STOCK CODE START if (VehicleBehaviorManager.Instance.MayDespawn(ref vehicleData)) { // NON-STOCK CODE END Singleton <VehicleManager> .instance.ReleaseVehicle(vehicleId); } // NON-STOCK CODE } }
public override void Execute(List <string> _params, CommandSenderInfo _senderInfo) { try { if (_params.Count < 1 && _params.Count > 2) { SdtdConsole.Instance.Output(string.Format("Wrong number of arguments, expected 1 or 2, found {0}", _params.Count)); return; } if (_params[0].ToLower().Equals("off")) { AuctionBox.IsEnabled = false; LoadConfig.WriteXml(); SdtdConsole.Instance.Output(string.Format("Auction has been set to off")); return; } else if (_params[0].ToLower().Equals("on")) { AuctionBox.IsEnabled = true; LoadConfig.WriteXml(); SdtdConsole.Instance.Output(string.Format("Auction has been set to on")); return; } else if (_params[0].ToLower().Equals("cancel")) { if (_params.Count != 2) { SdtdConsole.Instance.Output(string.Format("Wrong number of arguments, expected 2, found {0}", _params.Count)); return; } int _id; if (int.TryParse(_params[1], out _id)) { if (AuctionBox.AuctionItems.ContainsKey(_id)) { ClientInfo _cInfo = ConnectionManager.Instance.Clients.ForEntityId(_id); if (_cInfo != null) { string _auctionName = PersistentContainer.Instance.Players[_cInfo.playerId].AuctionItemName; int _auctionCount = PersistentContainer.Instance.Players[_cInfo.playerId].AuctionItemCount; int _auctionQuality = PersistentContainer.Instance.Players[_cInfo.playerId].AuctionItemQuality; int _auctionPrice = PersistentContainer.Instance.Players[_cInfo.playerId].AuctionItemPrice; ItemClass _class = ItemClass.GetItemClass(_auctionName, false); Block _block = Block.GetBlockByName(_auctionName, false); if (_class == null && _block == null) { ChatHook.ChatMessage(_cInfo, LoadConfig.Chat_Response_Color + "Could not complete the auction cancel. Unable to find item {0} in the item.xml list. Contact an administrator.[-]", -1, LoadConfig.Server_Response_Name, EChatType.Whisper, null); Log.Out(string.Format("Could not complete the auction cancel. Unable to find item {0} in the item.xml list", _auctionName)); return; } ItemValue itemValue = new ItemValue(ItemClass.GetItem(_auctionName).type, _auctionQuality, _auctionQuality, false, null, 1); World world = GameManager.Instance.World; var entityItem = (EntityItem)EntityFactory.CreateEntity(new EntityCreationData { entityClass = EntityClass.FromString("item"), id = EntityFactory.nextEntityID++, itemStack = new ItemStack(itemValue, _auctionCount), pos = world.Players.dict[_cInfo.entityId].position, rot = new UnityEngine.Vector3(20f, 0f, 20f), lifetime = 60f, belongsPlayerId = _cInfo.entityId }); world.SpawnEntityInWorld(entityItem); _cInfo.SendPackage(NetPackageManager.GetPackage <NetPackageEntityCollect>().Setup(entityItem.entityId, _cInfo.entityId)); world.RemoveEntity(entityItem.entityId, EnumRemoveEntityReason.Killed); AuctionBox.AuctionItems.Remove(_id); PersistentContainer.Instance.Players[_cInfo.playerId].AuctionId = 0; PersistentContainer.Instance.Players[_cInfo.playerId].AuctionItemName = ""; PersistentContainer.Instance.Players[_cInfo.playerId].AuctionItemCount = 0; PersistentContainer.Instance.Players[_cInfo.playerId].AuctionItemQuality = 0; PersistentContainer.Instance.Players[_cInfo.playerId].AuctionItemPrice = 0; PersistentContainer.Instance.Players[_cInfo.playerId].AuctionCancelTime = DateTime.Now; PersistentContainer.Instance.Save(); } else { AuctionBox.AuctionItems.Remove(_id); PersistentContainer.Instance.Players[_cInfo.playerId].AuctionReturn = true; PersistentContainer.Instance.Save(); } } else { SdtdConsole.Instance.Output(string.Format("Auction does not contain id {0}", _id)); } } else { SdtdConsole.Instance.Output(string.Format("Invalid integer {0}", _id)); } return; } else if (_params[0].ToLower().Equals("clear")) { if (_params.Count != 2) { SdtdConsole.Instance.Output(string.Format("Wrong number of arguments, expected 2, found {0}", _params.Count)); } int _id; if (int.TryParse(_params[1], out _id)) { if (AuctionBox.AuctionItems.ContainsKey(_id)) { AuctionBox.AuctionItems.Remove(_id); SdtdConsole.Instance.Output(string.Format("Id {0} has been removed from the auction", _id)); } else { SdtdConsole.Instance.Output(string.Format("Auction does not contain id {0}", _id)); } } else { SdtdConsole.Instance.Output(string.Format("Invalid integer {0}", _id)); } return; } else if (_params[0].ToLower().Equals("list")) { if (_params.Count != 1) { SdtdConsole.Instance.Output(string.Format("Wrong number of arguments, expected 1, found {0}", _params.Count)); return; } bool _auctionItemsFound = false; List <string> playerlist = PersistentContainer.Instance.Players.SteamIDs; for (int i = 0; i < playerlist.Count; i++) { string _steamId = playerlist[i]; int _auctionId = PersistentContainer.Instance.Players[_steamId].AuctionId; if (_auctionId > 0 && AuctionBox.AuctionItems.ContainsKey(_auctionId)) { _auctionItemsFound = true; int _auctionCount = PersistentContainer.Instance.Players[_steamId].AuctionItemCount; string _auctionName = PersistentContainer.Instance.Players[_steamId].AuctionItemName; int _auctionQuality = PersistentContainer.Instance.Players[_steamId].AuctionItemQuality; int _auctionPrice = PersistentContainer.Instance.Players[_steamId].AuctionItemPrice; if (_auctionQuality > 1) { string _message = "# {Id}: {Count} {Item} at {Quality} quality, for {Price} {Name}"; _message = _message.Replace("{Id}", _auctionId.ToString()); _message = _message.Replace("{Count}", _auctionCount.ToString()); _message = _message.Replace("{Item}", _auctionName); _message = _message.Replace("{Quality}", _auctionQuality.ToString()); _message = _message.Replace("{Price}", _auctionPrice.ToString()); _message = _message.Replace("{Name}", Wallet.Coin_Name); SdtdConsole.Instance.Output(_message); } else { string _message = "# {Id}: {Count} {Item} for {Price} {Name}"; _message = _message.Replace("{Id}", _auctionId.ToString()); _message = _message.Replace("{Count}", _auctionCount.ToString()); _message = _message.Replace("{Item}", _auctionName); _message = _message.Replace("{Price}", _auctionPrice.ToString()); _message = _message.Replace("{Name}", Wallet.Coin_Name); SdtdConsole.Instance.Output(_message); } } } if (!_auctionItemsFound) { SdtdConsole.Instance.Output("No items are currently for sale"); } } else { SdtdConsole.Instance.Output(string.Format("Invalid argument {0}.", _params[0])); } } catch (Exception e) { Log.Out(string.Format("[SERVERTOOLS] Error in AuctionConsole.Run: {0}.", e)); } }
/// <returns>the Tags an item with this ItemClass always has</returns> public static Tags ToTags(this ItemClass itemClass) { return(ItemClassToTags[itemClass]); }
private bool drawSignHandles(bool debug, ushort nodeId, ref NetNode node, bool viewOnly, bool handleClick, ref Vector3 camPos, out bool stateUpdated) { bool hovered = false; stateUpdated = false; if (viewOnly && !Options.junctionRestrictionsOverlay && MainTool.GetToolMode() != ToolMode.JunctionRestrictions) { return(false); } //NetManager netManager = Singleton<NetManager>.instance; var guiColor = GUI.color; Vector3 nodePos = Singleton <NetManager> .instance.m_nodes.m_buffer[nodeId].m_position; for (int i = 0; i < 8; ++i) { ushort segmentId = node.GetSegment(i); if (segmentId == 0) { continue; } SegmentGeometry geometry = SegmentGeometry.Get(segmentId); if (geometry == null) { Log.Error($"JunctionRestrictionsTool.drawSignHandles: No geometry information available for segment {segmentId}"); continue; } bool startNode = geometry.StartNodeId() == nodeId; bool incoming = geometry.IsIncoming(startNode); int numSignsPerRow = incoming ? 2 : 1; NetInfo segmentInfo = Singleton <NetManager> .instance.m_segments.m_buffer[segmentId].Info; ItemClass connectionClass = segmentInfo.GetConnectionClass(); if (connectionClass.m_service != ItemClass.Service.Road) { continue; // only for road junctions } // draw all junction restriction signs Vector3 segmentCenterPos = Singleton <NetManager> .instance.m_segments.m_buffer[segmentId].m_bounds.center; Vector3 yu = (segmentCenterPos - nodePos).normalized; Vector3 xu = Vector3.Cross(yu, new Vector3(0, 1f, 0)).normalized; float f = viewOnly ? 6f : 7f; // reserved sign size in game coordinates Vector3 centerStart = nodePos + yu * (viewOnly ? 5f : 14f); Vector3 zero = centerStart - 0.5f * (float)(numSignsPerRow - 1) * f * xu; // "top left" if (viewOnly) { if (Constants.ServiceFactory.SimulationService.LeftHandDrive) { zero -= xu * 8f; } else { zero += xu * 8f; } } bool signHovered; int x = 0; int y = 0; bool hasSignInPrevRow = false; // draw "lane-changing when going straight allowed" sign at (0; 0) bool allowed = JunctionRestrictionsManager.Instance.IsLaneChangingAllowedWhenGoingStraight(segmentId, startNode); bool configurable = Constants.ManagerFactory.JunctionRestrictionsManager.IsLaneChangingAllowedWhenGoingStraightConfigurable(segmentId, startNode, ref node); if ( debug || (configurable && (!viewOnly || allowed != Constants.ManagerFactory.JunctionRestrictionsManager.GetDefaultLaneChangingAllowedWhenGoingStraight(segmentId, startNode, ref node))) ) { DrawSign(viewOnly, !configurable, ref camPos, ref xu, ref yu, f, ref zero, x, y, guiColor, allowed ? TextureResources.LaneChangeAllowedTexture2D : TextureResources.LaneChangeForbiddenTexture2D, out signHovered); if (signHovered && handleClick) { hovered = true; if (MainTool.CheckClicked()) { JunctionRestrictionsManager.Instance.ToggleLaneChangingAllowedWhenGoingStraight(segmentId, startNode); stateUpdated = true; } } ++x; hasSignInPrevRow = true; } // draw "u-turns allowed" sign at (1; 0) allowed = JunctionRestrictionsManager.Instance.IsUturnAllowed(segmentId, startNode); configurable = Constants.ManagerFactory.JunctionRestrictionsManager.IsUturnAllowedConfigurable(segmentId, startNode, ref node); if ( debug || (configurable && (!viewOnly || allowed != Constants.ManagerFactory.JunctionRestrictionsManager.GetDefaultUturnAllowed(segmentId, startNode, ref node))) ) { DrawSign(viewOnly, !configurable, ref camPos, ref xu, ref yu, f, ref zero, x, y, guiColor, allowed ? TextureResources.UturnAllowedTexture2D : TextureResources.UturnForbiddenTexture2D, out signHovered); if (signHovered && handleClick) { hovered = true; if (MainTool.CheckClicked()) { if (!JunctionRestrictionsManager.Instance.ToggleUturnAllowed(segmentId, startNode)) { // TODO MainTool.ShowTooltip(Translation.GetString("..."), Singleton<NetManager>.instance.m_nodes.m_buffer[nodeId].m_position); } else { stateUpdated = true; } } } x++; hasSignInPrevRow = true; } x = 0; if (hasSignInPrevRow) { ++y; hasSignInPrevRow = false; } // draw "entering blocked junctions allowed" sign at (0; 1) allowed = JunctionRestrictionsManager.Instance.IsEnteringBlockedJunctionAllowed(segmentId, startNode); configurable = Constants.ManagerFactory.JunctionRestrictionsManager.IsEnteringBlockedJunctionAllowedConfigurable(segmentId, startNode, ref node); if ( debug || (configurable && (!viewOnly || allowed != Constants.ManagerFactory.JunctionRestrictionsManager.GetDefaultEnteringBlockedJunctionAllowed(segmentId, startNode, ref node))) ) { DrawSign(viewOnly, !configurable, ref camPos, ref xu, ref yu, f, ref zero, x, y, guiColor, allowed ? TextureResources.EnterBlockedJunctionAllowedTexture2D : TextureResources.EnterBlockedJunctionForbiddenTexture2D, out signHovered); if (signHovered && handleClick) { hovered = true; if (MainTool.CheckClicked()) { JunctionRestrictionsManager.Instance.ToggleEnteringBlockedJunctionAllowed(segmentId, startNode); stateUpdated = true; } } ++x; hasSignInPrevRow = true; } // draw "pedestrian crossing allowed" sign at (1; 1) allowed = JunctionRestrictionsManager.Instance.IsPedestrianCrossingAllowed(segmentId, startNode); configurable = Constants.ManagerFactory.JunctionRestrictionsManager.IsPedestrianCrossingAllowedConfigurable(segmentId, startNode, ref node); if ( debug || (configurable && (!viewOnly || !allowed)) ) { DrawSign(viewOnly, !configurable, ref camPos, ref xu, ref yu, f, ref zero, x, y, guiColor, allowed ? TextureResources.PedestrianCrossingAllowedTexture2D : TextureResources.PedestrianCrossingForbiddenTexture2D, out signHovered); if (signHovered && handleClick) { hovered = true; if (MainTool.CheckClicked()) { JunctionRestrictionsManager.Instance.TogglePedestrianCrossingAllowed(segmentId, startNode); stateUpdated = true; } } x++; hasSignInPrevRow = true; } x = 0; if (hasSignInPrevRow) { ++y; hasSignInPrevRow = false; } if (Options.turnOnRedEnabled) { IJunctionRestrictionsManager junctionRestrictionsManager = Constants.ManagerFactory.JunctionRestrictionsManager; bool lhd = Constants.ServiceFactory.SimulationService.LeftHandDrive; // draw "turn-left-on-red allowed" sign at (2; 0) allowed = junctionRestrictionsManager.IsTurnOnRedAllowed(lhd, segmentId, startNode); configurable = junctionRestrictionsManager.IsTurnOnRedAllowedConfigurable(lhd, segmentId, startNode, ref node); if ( debug || (configurable && (!viewOnly || allowed != junctionRestrictionsManager.GetDefaultTurnOnRedAllowed(lhd, segmentId, startNode, ref node))) ) { DrawSign(viewOnly, !configurable, ref camPos, ref xu, ref yu, f, ref zero, x, y, guiColor, allowed ? TextureResources.LeftOnRedAllowedTexture2D : TextureResources.LeftOnRedForbiddenTexture2D, out signHovered); if (signHovered && handleClick) { hovered = true; if (MainTool.CheckClicked()) { junctionRestrictionsManager.ToggleTurnOnRedAllowed(lhd, segmentId, startNode); stateUpdated = true; } } hasSignInPrevRow = true; } x++; // draw "turn-right-on-red allowed" sign at (2; 1) allowed = junctionRestrictionsManager.IsTurnOnRedAllowed(!lhd, segmentId, startNode); configurable = junctionRestrictionsManager.IsTurnOnRedAllowedConfigurable(!lhd, segmentId, startNode, ref node); if ( debug || (configurable && (!viewOnly || allowed != junctionRestrictionsManager.GetDefaultTurnOnRedAllowed(!lhd, segmentId, startNode, ref node))) ) { DrawSign(viewOnly, !configurable, ref camPos, ref xu, ref yu, f, ref zero, x, y, guiColor, allowed ? TextureResources.RightOnRedAllowedTexture2D : TextureResources.RightOnRedForbiddenTexture2D, out signHovered); if (signHovered && handleClick) { hovered = true; if (MainTool.CheckClicked()) { junctionRestrictionsManager.ToggleTurnOnRedAllowed(!lhd, segmentId, startNode); stateUpdated = true; } } hasSignInPrevRow = true; } x++; } } guiColor.a = 1f; GUI.color = guiColor; return(hovered); }
public override void Execute(List <string> _params, CommandSenderInfo _senderInfo) { try { if (_params.Count < 1 && _params.Count > 2) { SingletonMonoBehaviour <SdtdConsole> .Instance.Output(string.Format("[SERVERTOOLS] Wrong number of arguments, expected 1 or 2, found {0}", _params.Count)); return; } if (_params[0].ToLower().Equals("off")) { if (Auction.IsEnabled) { Auction.IsEnabled = false; Config.WriteXml(); Config.LoadXml(); SingletonMonoBehaviour <SdtdConsole> .Instance.Output(string.Format("[SERVERTOOLS] Auction has been set to off")); return; } else { SingletonMonoBehaviour <SdtdConsole> .Instance.Output(string.Format("[SERVERTOOLS] Auction is already off")); return; } } else if (_params[0].ToLower().Equals("on")) { if (!Auction.IsEnabled) { Auction.IsEnabled = true; Config.WriteXml(); Config.LoadXml(); SingletonMonoBehaviour <SdtdConsole> .Instance.Output(string.Format("[SERVERTOOLS] Auction has been set to on")); return; } else { SingletonMonoBehaviour <SdtdConsole> .Instance.Output(string.Format("[SERVERTOOLS] Auction is already on")); return; } } else if (_params[0].ToLower().Equals("cancel")) { if (_params.Count != 2) { SingletonMonoBehaviour <SdtdConsole> .Instance.Output(string.Format("[SERVERTOOLS] Wrong number of arguments, expected 2, found {0}", _params.Count)); return; } if (int.TryParse(_params[1], out int _id)) { if (Auction.AuctionItems.ContainsKey(_id)) { Auction.AuctionItems.TryGetValue(_id, out string playerId); if (PersistentContainer.Instance.Players[playerId].Auction != null && PersistentContainer.Instance.Players[playerId].Auction.Count > 0) { if (PersistentContainer.Instance.Players[playerId].Auction.ContainsKey(_id)) { if (PersistentContainer.Instance.Players[playerId].Auction.TryGetValue(_id, out ItemDataSerializable _itemData)) { ClientInfo cInfo = PersistentOperations.GetClientInfoFromNameOrId(playerId); if (cInfo != null) { ItemValue itemValue = new ItemValue(ItemClass.GetItem(_itemData.name, false).type, false); if (itemValue != null) { itemValue.UseTimes = _itemData.useTimes; itemValue.Quality = _itemData.quality; World world = GameManager.Instance.World; var entityItem = (EntityItem)EntityFactory.CreateEntity(new EntityCreationData { entityClass = EntityClass.FromString("item"), id = EntityFactory.nextEntityID++, itemStack = new ItemStack(itemValue, _itemData.count), pos = world.Players.dict[cInfo.entityId].position, rot = new UnityEngine.Vector3(20f, 0f, 20f), lifetime = 60f, belongsPlayerId = cInfo.entityId }); world.SpawnEntityInWorld(entityItem); cInfo.SendPackage(NetPackageManager.GetPackage <NetPackageEntityCollect>().Setup(entityItem.entityId, cInfo.entityId)); world.RemoveEntity(entityItem.entityId, EnumRemoveEntityReason.Despawned); Auction.AuctionItems.Remove(_id); PersistentContainer.Instance.Players[playerId].Auction.Remove(_id); PersistentContainer.Instance.AuctionPrices.Remove(_id); PersistentContainer.DataChange = true; using (StreamWriter sw = new StreamWriter(filepath, true, Encoding.UTF8)) { sw.WriteLine(string.Format("{0}: {1} {2} had their auction entry # {3} cancelled via console by {4}.", DateTime.Now, cInfo.PlatformId.ReadablePlatformUserIdentifier, cInfo.playerName, _id, _senderInfo.RemoteClientInfo.PlatformId.ReadablePlatformUserIdentifier)); sw.WriteLine(); sw.Flush(); sw.Close(); } ChatHook.ChatMessage(cInfo, Config.Chat_Response_Color + "Your auction item has returned to you.[-]", -1, Config.Server_Response_Name, EChatType.Whisper, null); } else { Auction.AuctionItems.Remove(_id); PersistentContainer.Instance.Players[playerId].Auction.Remove(_id); PersistentContainer.Instance.AuctionPrices.Remove(_id); PersistentContainer.DataChange = true; } } else { if (PersistentContainer.Instance.Players[playerId].AuctionReturn != null && PersistentContainer.Instance.Players[playerId].AuctionReturn.Count > 0) { PersistentContainer.Instance.Players[playerId].AuctionReturn.Add(_id, _itemData); } else { Dictionary <int, ItemDataSerializable> _auctionReturn = new Dictionary <int, ItemDataSerializable>(); _auctionReturn.Add(_id, _itemData); PersistentContainer.Instance.Players[playerId].AuctionReturn = _auctionReturn; } Auction.AuctionItems.Remove(_id); PersistentContainer.Instance.Players[playerId].Auction.Remove(_id); PersistentContainer.Instance.AuctionPrices.Remove(_id); PersistentContainer.DataChange = true; } SingletonMonoBehaviour <SdtdConsole> .Instance.Output(string.Format("[SERVERTOOLS] Id {0} has been removed from the auction list", _id)); } } } } else { SingletonMonoBehaviour <SdtdConsole> .Instance.Output("[SERVERTOOLS] Could not find this id listed in the auction. Unable to cancel[-]"); } } else { SingletonMonoBehaviour <SdtdConsole> .Instance.Output(string.Format("[SERVERTOOLS] Invalid integer {0}", _id)); } return; } else if (_params[0].ToLower().Equals("clear")) { if (_params.Count != 2) { SingletonMonoBehaviour <SdtdConsole> .Instance.Output(string.Format("[SERVERTOOLS] Wrong number of arguments, expected 2, found {0}", _params.Count)); } if (int.TryParse(_params[1], out int _id)) { if (Auction.AuctionItems.ContainsKey(_id)) { Auction.AuctionItems.TryGetValue(_id, out string _playerId); Auction.AuctionItems.Remove(_id); if (PersistentContainer.Instance.Players[_playerId].Auction != null && PersistentContainer.Instance.Players[_playerId].Auction.Count > 0) { PersistentContainer.Instance.Players[_playerId].Auction.Remove(_id); } if (PersistentContainer.Instance.AuctionPrices != null && PersistentContainer.Instance.AuctionPrices.Count > 0) { PersistentContainer.Instance.AuctionPrices.Remove(_id); } PersistentContainer.DataChange = true; SingletonMonoBehaviour <SdtdConsole> .Instance.Output(string.Format("[SERVERTOOLS] Id {0} has been removed from the auction", _id)); } else { SingletonMonoBehaviour <SdtdConsole> .Instance.Output(string.Format("[SERVERTOOLS] Auction does not contain id {0}", _id)); } } else { SingletonMonoBehaviour <SdtdConsole> .Instance.Output(string.Format("[SERVERTOOLS] Invalid integer {0}", _id)); } return; } else if (_params[0].ToLower().Equals("list")) { if (_params.Count != 1) { SingletonMonoBehaviour <SdtdConsole> .Instance.Output(string.Format("[SERVERTOOLS] Wrong number of arguments, expected 1, found {0}", _params.Count)); return; } if (Auction.AuctionItems.Count > 0) { if (PersistentContainer.Instance.Players.IDs.Count > 0) { List <string> playerlist = PersistentContainer.Instance.Players.IDs; Dictionary <int, int> _auctionPrices = PersistentContainer.Instance.AuctionPrices; for (int i = 0; i < playerlist.Count; i++) { string id = playerlist[i]; if (PersistentContainer.Instance.Players[id].Auction != null && PersistentContainer.Instance.Players[id].Auction.Count > 0) { foreach (var auctionItem in PersistentContainer.Instance.Players[id].Auction) { _auctionPrices.TryGetValue(auctionItem.Key, out int _price); string _message = "# {Id}: {Count} {Item} at {Quality} quality, {Durability} durability for {Price} {Name}"; _message = _message.Replace("{Id}", auctionItem.Key.ToString()); _message = _message.Replace("{Count}", auctionItem.Value.count.ToString()); _message = _message.Replace("{Item}", auctionItem.Value.name); _message = _message.Replace("{Quality}", auctionItem.Value.quality.ToString()); _message = _message.Replace("{Durability}", (100 - auctionItem.Value.useTimes).ToString()); _message = _message.Replace("{Price}", _price.ToString()); _message = _message.Replace("{Name}", Wallet.Currency_Name); SingletonMonoBehaviour <SdtdConsole> .Instance.Output(_message); } } } } } else { SingletonMonoBehaviour <SdtdConsole> .Instance.Output("[SERVERTOOLS] No items are listed in the auction"); } } else { SingletonMonoBehaviour <SdtdConsole> .Instance.Output(string.Format("[SERVERTOOLS] Invalid argument {0}", _params[0])); } } catch (Exception e) { Log.Out(string.Format("[SERVERTOOLS] Error in AuctionConsole.Execute: {0}", e.Message)); } }
public static void LoadXml() { if (!Utils.FileExists(filePath)) { UpdateXml(); } XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.Load(filePath); } catch (XmlException e) { Log.Error(string.Format("[SERVERTOOLS] Failed loading {0}: {1}", file, e.Message)); return; } XmlNode _XmlNode = xmlDoc.DocumentElement; foreach (XmlNode childNode in _XmlNode.ChildNodes) { if (childNode.Name == "Items") { Dict.Clear(); Dict1.Clear(); Categories.Clear(); foreach (XmlNode subChild in childNode.ChildNodes) { if (subChild.NodeType == XmlNodeType.Comment) { continue; } if (subChild.NodeType != XmlNodeType.Element) { Log.Warning(string.Format("[SERVERTOOLS] Unexpected XML node found in 'Shop' section: {0}", subChild.OuterXml)); continue; } XmlElement _line = (XmlElement)subChild; if (!_line.HasAttribute("Item")) { Log.Warning(string.Format("[SERVERTOOLS] Ignoring Shop entry because of missing Item attribute: {0}", subChild.OuterXml)); continue; } if (!_line.HasAttribute("Name")) { Log.Warning(string.Format("[SERVERTOOLS] Ignoring Shop entry because of missing Name attribute: {0}", subChild.OuterXml)); continue; } if (!_line.HasAttribute("Count")) { Log.Warning(string.Format("[SERVERTOOLS] Ignoring Shop entry because of missing Count attribute: {0}", subChild.OuterXml)); continue; } if (!_line.HasAttribute("Quality")) { Log.Warning(string.Format("[SERVERTOOLS] Ignoring Shop entry because of missing Quality attribute: {0}", subChild.OuterXml)); continue; } if (!_line.HasAttribute("Price")) { Log.Warning(string.Format("[SERVERTOOLS] Ignoring Shop entry because of missing Price attribute: {0}", subChild.OuterXml)); continue; } if (!_line.HasAttribute("Category")) { Log.Warning(string.Format("[SERVERTOOLS] Ignoring Shop entry because of missing Category attribute: {0}", subChild.OuterXml)); continue; } if (!int.TryParse(_line.GetAttribute("Item"), out int _item)) { Log.Out(string.Format("[SERVERTOOLS] Ignoring Shop entry because of invalid (non-numeric) value for 'Item' attribute: {0}", subChild.OuterXml)); continue; } if (!int.TryParse(_line.GetAttribute("Count"), out int _count)) { Log.Out(string.Format("[SERVERTOOLS] Ignoring Shop entry because of invalid (non-numeric) value for 'Count' attribute: {0}", subChild.OuterXml)); continue; } if (!int.TryParse(_line.GetAttribute("Quality"), out int _quality)) { Log.Out(string.Format("[SERVERTOOLS] Ignoring Shop entry because of invalid (non-numeric) value for 'Quality' attribute: {0}", subChild.OuterXml)); continue; } if (!int.TryParse(_line.GetAttribute("Price"), out int _price)) { Log.Out(string.Format("[SERVERTOOLS] Ignoring Shop entry because of invalid (non-numeric) value for 'Price' attribute: {0}", subChild.OuterXml)); continue; } string _name = _line.GetAttribute("Name"); string _secondaryname; if (_line.HasAttribute("SecondaryName")) { _secondaryname = _line.GetAttribute("SecondaryName"); } else { _secondaryname = _name; } ItemValue _itemValue = ItemClass.GetItem(_name, false); if (_itemValue.type == ItemValue.None.type) { Log.Out(string.Format("[SERVERTOOLS] Ignoring Shop entry because item could not be found: {0}", _name)); continue; } if (_count > _itemValue.ItemClass.Stacknumber.Value) { _count = _itemValue.ItemClass.Stacknumber.Value; } string _category = _line.GetAttribute("Category").ToLower(); if (!Categories.Contains(_category)) { Categories.Add(_category); } if (_quality < 1) { _quality = 1; } else if (_quality > 600) { _quality = 600; } if (!Dict.ContainsKey(_item)) { string[] _strings = new string[] { _name, _secondaryname, _category }; Dict.Add(_item, _strings); int[] _integers = new int[] { _count, _quality, _price }; Dict1.Add(_item, _integers); } } } } }
public EquipmentEventArgs(ItemClass _item) { item = _item; }
private void UpdateBindings() { ushort vehicleID = 0; ushort lineId = this.GetLineID(out vehicleID); if ((int)lineId == 0) { this._passengerPanel.Hide(); this._statsPanel.Hide(); this._buttonPanel.Hide(); this._publicTransportVehicleWorldInfoPanel.component.height = 229f; } else { this._publicTransportVehicleWorldInfoPanel.component.height = 332f; this._editType.isVisible = !OptionsWrapper <Settings> .Options.HideVehicleEditor; ItemClass itemClass = Singleton <TransportManager> .instance.m_lines.m_buffer[(int)lineId].Info.m_class; ItemClass.SubService subService = itemClass.m_subService; ItemClass.Service service = itemClass.m_service; ItemClass.Level level = itemClass.m_level; switch (subService) { case ItemClass.SubService.PublicTransportBus: case ItemClass.SubService.PublicTransportMetro: case ItemClass.SubService.PublicTransportTrain: case ItemClass.SubService.PublicTransportTram: case ItemClass.SubService.PublicTransportShip: case ItemClass.SubService.PublicTransportPlane: case ItemClass.SubService.PublicTransportMonorail: case ItemClass.SubService.PublicTransportCableCar: this._passengerPanel.Show(); if ((int)vehicleID != 0) { this._lastStopExchange.text = string.Format(Localization.Get("VEHICLE_PANEL_LAST_STOP_EXCHANGE"), (object)VehicleManagerMod.m_cachedVehicleData[(int)vehicleID].LastStopGonePassengers, (object)VehicleManagerMod.m_cachedVehicleData[(int)vehicleID].LastStopNewPassengers); } break; case ItemClass.SubService.None: if (service == ItemClass.Service.Disaster && level == ItemClass.Level.Level4) { this._passengerPanel.Show(); if ((int)vehicleID != 0) { this._lastStopExchange.text = string.Format(Localization.Get("VEHICLE_PANEL_LAST_STOP_EXCHANGE"), (object)VehicleManagerMod.m_cachedVehicleData[(int)vehicleID].LastStopGonePassengers, (object)VehicleManagerMod.m_cachedVehicleData[(int)vehicleID].LastStopNewPassengers); } } else { this._passengerPanel.Hide(); } break; default: this._passengerPanel.Hide(); break; } this._distanceTraveled.parent.Show(); this._distanceProgress.parent.Show(); VehicleManager vm = Singleton <VehicleManager> .instance; if ((vm.m_vehicles.m_buffer[(int)vehicleID].m_flags & Vehicle.Flags.Stopped) != ~(Vehicle.Flags.Created | Vehicle.Flags.Deleted | Vehicle.Flags.Spawned | Vehicle.Flags.Inverted | Vehicle.Flags.TransferToTarget | Vehicle.Flags.TransferToSource | Vehicle.Flags.Emergency1 | Vehicle.Flags.Emergency2 | Vehicle.Flags.WaitingPath | Vehicle.Flags.Stopped | Vehicle.Flags.Leaving | Vehicle.Flags.Arriving | Vehicle.Flags.Reversed | Vehicle.Flags.TakingOff | Vehicle.Flags.Flying | Vehicle.Flags.Landing | Vehicle.Flags.WaitingSpace | Vehicle.Flags.WaitingCargo | Vehicle.Flags.GoingBack | Vehicle.Flags.WaitingTarget | Vehicle.Flags.Importing | Vehicle.Flags.Exporting | Vehicle.Flags.Parking | Vehicle.Flags.CustomName | Vehicle.Flags.OnGravel | Vehicle.Flags.WaitingLoading | Vehicle.Flags.Congestion | Vehicle.Flags.DummyTraffic | Vehicle.Flags.Underground | Vehicle.Flags.Transition | Vehicle.Flags.InsideBuilding | Vehicle.Flags.LeftHandDrive)) { if (VehicleManagerMod.m_cachedVehicleData[(int)vehicleID].IsUnbunchingInProgress) { this._status.text = Localization.Get("VEHICLE_PANEL_STATUS_UNBUNCHING"); } this._distance.text = this._status.text; float num = (float)vm.m_vehicles.m_buffer[(int)vehicleID].m_waitCounter / 12f; int p = Mathf.RoundToInt(num * 100f); this._distanceTraveled.value = num; this._distanceTraveled.progressColor = (Color32)Color.green; this._distanceProgress.text = LocaleFormatter.FormatPercentage(p); } else { bool flag = true; string text = Localization.Get("VEHICLE_PANEL_STATUS_NEXT_STOP"); if (subService == ItemClass.SubService.PublicTransportShip) { this.UpdateProgress(); } else if (subService == ItemClass.SubService.PublicTransportPlane) { if ((vm.m_vehicles.m_buffer[(int)vehicleID].m_flags & Vehicle.Flags.Landing) != ~(Vehicle.Flags.Created | Vehicle.Flags.Deleted | Vehicle.Flags.Spawned | Vehicle.Flags.Inverted | Vehicle.Flags.TransferToTarget | Vehicle.Flags.TransferToSource | Vehicle.Flags.Emergency1 | Vehicle.Flags.Emergency2 | Vehicle.Flags.WaitingPath | Vehicle.Flags.Stopped | Vehicle.Flags.Leaving | Vehicle.Flags.Arriving | Vehicle.Flags.Reversed | Vehicle.Flags.TakingOff | Vehicle.Flags.Flying | Vehicle.Flags.Landing | Vehicle.Flags.WaitingSpace | Vehicle.Flags.WaitingCargo | Vehicle.Flags.GoingBack | Vehicle.Flags.WaitingTarget | Vehicle.Flags.Importing | Vehicle.Flags.Exporting | Vehicle.Flags.Parking | Vehicle.Flags.CustomName | Vehicle.Flags.OnGravel | Vehicle.Flags.WaitingLoading | Vehicle.Flags.Congestion | Vehicle.Flags.DummyTraffic | Vehicle.Flags.Underground | Vehicle.Flags.Transition | Vehicle.Flags.InsideBuilding | Vehicle.Flags.LeftHandDrive) || (vm.m_vehicles.m_buffer[(int)vehicleID].m_flags & Vehicle.Flags.TakingOff) != ~(Vehicle.Flags.Created | Vehicle.Flags.Deleted | Vehicle.Flags.Spawned | Vehicle.Flags.Inverted | Vehicle.Flags.TransferToTarget | Vehicle.Flags.TransferToSource | Vehicle.Flags.Emergency1 | Vehicle.Flags.Emergency2 | Vehicle.Flags.WaitingPath | Vehicle.Flags.Stopped | Vehicle.Flags.Leaving | Vehicle.Flags.Arriving | Vehicle.Flags.Reversed | Vehicle.Flags.TakingOff | Vehicle.Flags.Flying | Vehicle.Flags.Landing | Vehicle.Flags.WaitingSpace | Vehicle.Flags.WaitingCargo | Vehicle.Flags.GoingBack | Vehicle.Flags.WaitingTarget | Vehicle.Flags.Importing | Vehicle.Flags.Exporting | Vehicle.Flags.Parking | Vehicle.Flags.CustomName | Vehicle.Flags.OnGravel | Vehicle.Flags.WaitingLoading | Vehicle.Flags.Congestion | Vehicle.Flags.DummyTraffic | Vehicle.Flags.Underground | Vehicle.Flags.Transition | Vehicle.Flags.InsideBuilding | Vehicle.Flags.LeftHandDrive) || (vm.m_vehicles.m_buffer[(int)vehicleID].m_flags & Vehicle.Flags.Flying) == ~(Vehicle.Flags.Created | Vehicle.Flags.Deleted | Vehicle.Flags.Spawned | Vehicle.Flags.Inverted | Vehicle.Flags.TransferToTarget | Vehicle.Flags.TransferToSource | Vehicle.Flags.Emergency1 | Vehicle.Flags.Emergency2 | Vehicle.Flags.WaitingPath | Vehicle.Flags.Stopped | Vehicle.Flags.Leaving | Vehicle.Flags.Arriving | Vehicle.Flags.Reversed | Vehicle.Flags.TakingOff | Vehicle.Flags.Flying | Vehicle.Flags.Landing | Vehicle.Flags.WaitingSpace | Vehicle.Flags.WaitingCargo | Vehicle.Flags.GoingBack | Vehicle.Flags.WaitingTarget | Vehicle.Flags.Importing | Vehicle.Flags.Exporting | Vehicle.Flags.Parking | Vehicle.Flags.CustomName | Vehicle.Flags.OnGravel | Vehicle.Flags.WaitingLoading | Vehicle.Flags.Congestion | Vehicle.Flags.DummyTraffic | Vehicle.Flags.Underground | Vehicle.Flags.Transition | Vehicle.Flags.InsideBuilding | Vehicle.Flags.LeftHandDrive)) { text = this._status.text; flag = false; } this.UpdateProgress(); } this._status.text = text; if (flag) { ushort targetBuilding = vm.m_vehicles.m_buffer[(int)vehicleID].m_targetBuilding; InstanceID id = new InstanceID(); id.NetNode = targetBuilding; string name = Singleton <InstanceManager> .instance.GetName(id); this._target.objectUserData = (object)id; this._target.text = name == null?string.Format(Localization.Get("STOP_LIST_BOX_ROW_STOP"), (object)(TransportLineMod.GetStopIndex(lineId, targetBuilding) + 1)) : name; this._target.Enable(); this._target.Show(); } this._distance.text = ColossalFramework.Globalization.Locale.Get(this._distance.localeID); this._distanceTraveled.progressColor = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue); } this._statsPanel.Show(); this._passengersCurrentWeek.text = VehicleManagerMod.m_cachedVehicleData[(int)vehicleID].PassengersThisWeek.ToString(); this._passengersLastWeek.text = VehicleManagerMod.m_cachedVehicleData[(int)vehicleID].PassengersLastWeek.ToString(); this._passengersAverage.text = VehicleManagerMod.m_cachedVehicleData[(int)vehicleID].PassengersAverage.ToString(); PrefabData prefabData = Array.Find(VehiclePrefabs.instance.GetPrefabs(service, subService, level), item => item.PrefabDataIndex == vm.m_vehicles.m_buffer[(int)vehicleID].Info.m_prefabDataIndex); int num1 = VehicleManagerMod.m_cachedVehicleData[(int)vehicleID].IncomeThisWeek - prefabData.MaintenanceCost; UILabel earningsCurrentWeek = this._earningsCurrentWeek; float num2 = (float)num1 * 0.01f; string str1 = num2.ToString(ColossalFramework.Globalization.Locale.Get("MONEY_FORMAT"), (IFormatProvider)LocaleManager.cultureInfo); earningsCurrentWeek.text = str1; this._earningsCurrentWeek.textColor = (Color32)this.GetColor((float)num1); int incomeLastWeek = VehicleManagerMod.m_cachedVehicleData[(int)vehicleID].IncomeLastWeek; UILabel earningsLastWeek = this._earningsLastWeek; num2 = (float)incomeLastWeek * 0.01f; string str2 = num2.ToString(ColossalFramework.Globalization.Locale.Get("MONEY_FORMAT"), (IFormatProvider)LocaleManager.cultureInfo); earningsLastWeek.text = str2; this._earningsLastWeek.textColor = (Color32)this.GetColor((float)incomeLastWeek); int incomeAverage = VehicleManagerMod.m_cachedVehicleData[(int)vehicleID].IncomeAverage; UILabel earningsAverage = this._earningsAverage; num2 = (float)incomeAverage * 0.01f; string str3 = num2.ToString(ColossalFramework.Globalization.Locale.Get("MONEY_FORMAT"), (IFormatProvider)LocaleManager.cultureInfo); earningsAverage.text = str3; this._earningsAverage.textColor = (Color32)this.GetColor((float)incomeAverage); this._buttonPanel.Show(); } }
internal void GetShieldPositions(CellType[,] cellTypes) { ItemClass.GetItem(ItemSlot.SHIELDS, ShieldEquippedID).GetShieldPositions(cellTypes); //Pull slot locations from class next }
private bool RayCastSegmentAndNode(NetInfo connectedType, Segment3 ray, float snapElevation, bool nameOnly, ItemClass.Service service, ItemClass.Service service2, ItemClass.SubService subService, ItemClass.SubService subService2, ItemClass.Layer itemLayers, ItemClass.Layer itemLayers2, NetNode.Flags ignoreNodeFlags, NetSegment.Flags ignoreSegmentFlags, out Vector3 hit, out ushort nodeIndex, out ushort segmentIndex) { var bounds = new Bounds(new Vector3(0f, 512f, 0f), new Vector3(17280f, 1152f, 17280f)); if (ray.Clip(bounds)) { Vector3 vector = ray.b - ray.a; var num = (int)((ray.a.x / 64f) + 135f); var num2 = (int)((ray.a.z / 64f) + 135f); var num3 = (int)((ray.b.x / 64f) + 135f); var num4 = (int)((ray.b.z / 64f) + 135f); var num5 = Mathf.Abs(vector.x); var num6 = Mathf.Abs(vector.z); int num7; int num8; if (num5 >= num6) { num7 = ((vector.x <= 0f) ? -1 : 1); num8 = 0; if (num5 > 0.001f) { vector *= 64f / num5; } } else { num7 = 0; num8 = ((vector.z <= 0f) ? -1 : 1); if (num6 > 0.001f) { vector *= 64f / num6; } } var num9 = 2f; var num10 = 16f; var num11 = 2f; var num12 = 16f; ushort num13 = 0; ushort num14 = 0; ushort num15 = 0; Vector3 vector2 = ray.a; Vector3 vector3 = ray.a; var num16 = num; var num17 = num2; do { Vector3 vector4 = vector3 + vector; int num18; int num19; int num20; int num21; if (num7 != 0) { if ((num16 == num && num7 > 0) || (num16 == num3 && num7 < 0)) { num18 = Mathf.Max((int)(((vector4.x - 64f) / 64f) + 135f), 0); } else { num18 = Mathf.Max(num16, 0); } if ((num16 == num && num7 < 0) || (num16 == num3 && num7 > 0)) { num19 = Mathf.Min((int)(((vector4.x + 64f) / 64f) + 135f), 269); } else { num19 = Mathf.Min(num16, 269); } num20 = Mathf.Max((int)(((Mathf.Min(vector2.z, vector4.z) - 64f) / 64f) + 135f), 0); num21 = Mathf.Min((int)(((Mathf.Max(vector2.z, vector4.z) + 64f) / 64f) + 135f), 269); } else { if ((num17 == num2 && num8 > 0) || (num17 == num4 && num8 < 0)) { num20 = Mathf.Max((int)(((vector4.z - 64f) / 64f) + 135f), 0); } else { num20 = Mathf.Max(num17, 0); } if ((num17 == num2 && num8 < 0) || (num17 == num4 && num8 > 0)) { num21 = Mathf.Min((int)(((vector4.z + 64f) / 64f) + 135f), 269); } else { num21 = Mathf.Min(num17, 269); } num18 = Mathf.Max((int)(((Mathf.Min(vector2.x, vector4.x) - 64f) / 64f) + 135f), 0); num19 = Mathf.Min((int)(((Mathf.Max(vector2.x, vector4.x) + 64f) / 64f) + 135f), 269); } for (var i = num20; i <= num21; i++) { for (var j = num18; j <= num19; j++) { var num22 = Singleton <NetManager> .instance.m_nodeGrid[(i * 270) + j]; var num23 = 0; while (num22 != 0) { NetNode.Flags flags = NodeBuffer[num22].m_flags; NetInfo info = NodeBuffer[num22].Info; ItemClass connectionClass = info.GetConnectionClass(); if ((((service == ItemClass.Service.None || connectionClass.m_service == service) && (subService == ItemClass.SubService.None || connectionClass.m_subService == subService) && (itemLayers == ItemClass.Layer.None || (connectionClass.m_layer & itemLayers) != ItemClass.Layer.None)) || (info.m_intersectClass != null && (service == ItemClass.Service.None || info.m_intersectClass.m_service == service) && (subService == ItemClass.SubService.None || info.m_intersectClass.m_subService == subService) && (itemLayers == ItemClass.Layer.None || (info.m_intersectClass.m_layer & itemLayers) != ItemClass.Layer.None)) || (info.m_netAI.CanIntersect(connectedType) && connectionClass.m_service == service2 && (subService2 == ItemClass.SubService.None || connectionClass.m_subService == subService2) && (itemLayers2 == ItemClass.Layer.None || (connectionClass.m_layer & itemLayers2) != ItemClass.Layer.None))) && (flags & ignoreNodeFlags) == NetNode.Flags.None && (connectedType == null || (info.m_netAI.CanConnect(connectedType) && connectedType.m_netAI.CanConnect(info)))) { var flag = false; if ((flags & (NetNode.Flags.Middle | NetNode.Flags.Untouchable)) == (NetNode.Flags.Middle | NetNode.Flags.Untouchable) && NodeBuffer[num22].CountSegments(NetSegment.Flags.Untouchable, 0) >= 2) { flag = true; } if (!flag && NodeBuffer[num22].RayCast(ray, snapElevation, out var num24, out var num25) && (num25 < num12 || (num25 == num12 && num24 < num11))) { num11 = num24; num12 = num25; num14 = num22; } } num22 = NodeBuffer[num22].m_nextGridNode; if (++num23 > 32768) { CODebugBase <LogChannel> .Error(LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace); break; } } } } for (var k = num20; k <= num21; k++) { for (var l = num18; l <= num19; l++) { var num26 = Singleton <NetManager> .instance.m_segmentGrid[(k * 270) + l]; var num27 = 0; while (num26 != 0) { NetSegment.Flags flags2 = SegmentBuffer[num26].m_flags; NetInfo info2 = SegmentBuffer[num26].Info; ItemClass connectionClass2 = info2.GetConnectionClass(); if (((service == ItemClass.Service.None || connectionClass2.m_service == service) && (subService == ItemClass.SubService.None || connectionClass2.m_subService == subService) && (itemLayers == ItemClass.Layer.None || (connectionClass2.m_layer & itemLayers) != ItemClass.Layer.None || nameOnly)) || (info2.m_intersectClass != null && (service == ItemClass.Service.None || info2.m_intersectClass.m_service == service) && (subService == ItemClass.SubService.None || info2.m_intersectClass.m_subService == subService) && (itemLayers == ItemClass.Layer.None || (info2.m_intersectClass.m_layer & itemLayers) != ItemClass.Layer.None || nameOnly)) || (info2.m_netAI.CanIntersect(connectedType) && connectionClass2.m_service == service2 && (subService2 == ItemClass.SubService.None || connectionClass2.m_subService == subService2) && (itemLayers2 == ItemClass.Layer.None || (connectionClass2.m_layer & itemLayers2) != ItemClass.Layer.None || nameOnly))) { var flag2 = (flags2 & ignoreSegmentFlags) != NetSegment.Flags.None && !nameOnly; if ((flags2 & ignoreSegmentFlags) == NetSegment.Flags.None && (connectedType == null || (info2.m_netAI.CanConnect(connectedType) && connectedType.m_netAI.CanConnect(info2))) && SegmentBuffer[num26].RayCast(num26, ray, snapElevation, nameOnly, out var num28, out var num29) && (num29 < num10 || (num29 == num10 && num28 < num9))) { var startNode = SegmentBuffer[num26].m_startNode; var endNode = SegmentBuffer[num26].m_endNode; Vector3 position = NodeBuffer[startNode].m_position; Vector3 position2 = NodeBuffer[endNode].m_position; var num30 = NodeBuffer[startNode].Info.GetMinNodeDistance(); var num31 = NodeBuffer[endNode].Info.GetMinNodeDistance(); num10 = num29; num9 = num28; Vector3 a = ray.a + ((ray.b - ray.a) * num28); NetNode.Flags flags3 = NodeBuffer[startNode].m_flags; if ((flags3 & NetNode.Flags.End) != NetNode.Flags.None) { flags3 &= ~NetNode.Flags.Moveable; } NetNode.Flags flags4 = NodeBuffer[endNode].m_flags; if ((flags4 & NetNode.Flags.End) != NetNode.Flags.None) { flags4 &= ~NetNode.Flags.Moveable; } if (flag2) { num30 = 1000f; num31 = 1000f; } var flag3 = (flags3 & (NetNode.Flags.Moveable | ignoreNodeFlags)) == NetNode.Flags.None; var flag4 = (flags4 & (NetNode.Flags.Moveable | ignoreNodeFlags)) == NetNode.Flags.None; var num32 = VectorUtils.LengthSqrXZ(a - position) / (num30 * num30); var num33 = VectorUtils.LengthSqrXZ(a - position2) / (num31 * num31); if (flag3 && num32 < 1f && (!flag4 || num32 < num33) && !nameOnly) { num13 = startNode; if (!flag2) { num15 = num26; } } else if (flag4 && num33 < 1f && !nameOnly) { num13 = endNode; if (!flag2) { num15 = num26; } } else if (!flag2) { num13 = 0; num15 = num26; } } } num26 = SegmentBuffer[num26].m_nextGridSegment; if (++num27 > 36864) { CODebugBase <LogChannel> .Error(LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace); break; } } } } vector2 = vector3; vector3 = vector4; num16 += num7; num17 += num8; }while ((num16 <= num3 || num7 <= 0) && (num16 >= num3 || num7 >= 0) && (num17 <= num4 || num8 <= 0) && (num17 >= num4 || num8 >= 0)); if (num12 < num10 || (num12 == num10 && num11 < num9)) { num9 = num11; num13 = num14; } if (num9 != 2f) { hit = ray.Position(num9); nodeIndex = num13; segmentIndex = num15; return(true); } } hit = Vector3.zero; nodeIndex = 0; segmentIndex = 0; return(false); }
public CameraTreeNode(ItemClass i) { this.Init(i); }
public void GetItem(string itemName) { ItemClass tmp_item = ItemClass.HealthPotion; EquipmentClass tmp_equip = EquipmentClass.Ribbon; bool isItem = true; switch (itemName) { //TODO: use hash tables instead case "SpringSoul": tmp_item = ItemClass.SpringSoul; break; case "SummerSoul": tmp_item = ItemClass.SummerSoul; break; case "AutumnSoul": tmp_item = ItemClass.AutumnSoul; break; case "WinterSoul": tmp_item = ItemClass.WinterSoul; break; case "ActivateCrystal": tmp_item = ItemClass.ActivateCrystal; break; case "RegenPotion": tmp_item = ItemClass.RegenPotion; break; case "Shroom": tmp_item = ItemClass.Shroom; break; case "Apple": tmp_item = ItemClass.Apple; break; case "ShrineTool": tmp_item = ItemClass.ShrineTool; break; case "SpringFlower": tmp_equip = EquipmentClass.SpringFlower; isItem = false; break; case "Crystal": GetCrystal(); return; default: return; } if (isItem) { itemCount[(int)tmp_item]++; GameObject.Find("ItemGetHint").GetComponent <ItemHintArea>().AddItemHint(new ConsumeableItem(tmp_item)); } else { equipmentExist[(int)tmp_equip] = true; GameObject.Find("ItemGetHint").GetComponent <ItemHintArea>().AddItemHint(new ConsumeableItem(tmp_equip)); } //check item state if (currentProcess == GameMainProcessState.AutumnShrine_FindItem && itemCount[(int)ItemClass.Apple] >= 5 && itemCount[(int)ItemClass.ShrineTool] >= 1) { SetMainProcess(GameMainProcessState.AutumnShrine_ItemFoundALL); } }
public static void LoadXml() { if (!Utils.FileExists(filePath)) { UpdateXml(); } XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.Load(filePath); } catch (XmlException e) { Log.Error(string.Format("[SERVERTOOLS] Failed loading {0}: {1}", file, e.Message)); return; } XmlNode _XmlNode = xmlDoc.DocumentElement; foreach (XmlNode childNode in _XmlNode.ChildNodes) { if (childNode.Name == "items") { dict.Clear(); dict1.Clear(); categories.Clear(); foreach (XmlNode subChild in childNode.ChildNodes) { if (subChild.NodeType == XmlNodeType.Comment) { continue; } if (subChild.NodeType != XmlNodeType.Element) { Log.Warning(string.Format("[SERVERTOOLS] Unexpected XML node found in 'Shop' section: {0}", subChild.OuterXml)); continue; } XmlElement _line = (XmlElement)subChild; if (!_line.HasAttribute("item")) { Log.Warning(string.Format("[SERVERTOOLS] Ignoring Shop entry because of missing item attribute: {0}", subChild.OuterXml)); continue; } if (!_line.HasAttribute("name")) { Log.Warning(string.Format("[SERVERTOOLS] Ignoring Shop entry because of missing name attribute: {0}", subChild.OuterXml)); continue; } if (!_line.HasAttribute("secondaryname")) { updateConfig = true; } if (!_line.HasAttribute("count")) { Log.Warning(string.Format("[SERVERTOOLS] Ignoring Shop entry because of missing count attribute: {0}", subChild.OuterXml)); continue; } if (!_line.HasAttribute("quality")) { Log.Warning(string.Format("[SERVERTOOLS] Ignoring Shop entry because of missing quality attribute: {0}", subChild.OuterXml)); continue; } if (!_line.HasAttribute("price")) { Log.Warning(string.Format("[SERVERTOOLS] Ignoring Shop entry because of missing price attribute: {0}", subChild.OuterXml)); continue; } if (!_line.HasAttribute("category")) { Log.Warning(string.Format("[SERVERTOOLS] Ignoring Shop entry because of missing category attribute: {0}", subChild.OuterXml)); continue; } int _item = 1; int _count = 1; int _quality = 1; int _price = 1; if (!int.TryParse(_line.GetAttribute("item"), out _item)) { Log.Out(string.Format("[SERVERTOOLS] Ignoring Shop entry because of invalid (non-numeric) value for 'item' attribute: {0}", subChild.OuterXml)); continue; } if (!int.TryParse(_line.GetAttribute("count"), out _count)) { Log.Out(string.Format("[SERVERTOOLS] Ignoring Shop entry because of invalid (non-numeric) value for 'count' attribute: {0}", subChild.OuterXml)); continue; } if (!int.TryParse(_line.GetAttribute("quality"), out _quality)) { Log.Out(string.Format("[SERVERTOOLS] Ignoring Shop entry because of invalid (non-numeric) value for 'quality' attribute: {0}", subChild.OuterXml)); continue; } if (!int.TryParse(_line.GetAttribute("price"), out _price)) { Log.Out(string.Format("[SERVERTOOLS] Ignoring Shop Item entry because of invalid (non-numeric) value for 'price' attribute: {0}", subChild.OuterXml)); continue; } string _name = _line.GetAttribute("name"); string _secondaryname; if (_line.HasAttribute("secondaryname")) { _secondaryname = _line.GetAttribute("secondaryname"); } else { _secondaryname = _name; } ItemClass _class; Block _block; int _id; if (int.TryParse(_name, out _id)) { _class = ItemClass.GetForId(_id); _block = Block.GetBlockByName(_name, false); } else { _class = ItemClass.GetItemClass(_name, false); _block = Block.GetBlockByName(_name, false); } if (_class == null && _block == null) { Log.Out(string.Format("[SERVERTOOLS] Shop entry skipped. Item not found: {0}", _name)); continue; } string _category = _line.GetAttribute("category").ToLower(); if (!categories.Contains(_category)) { categories.Add(_category); } if (_quality < 1) { _quality = 1; } else if (_quality > 600) { _quality = 600; } if (!dict.ContainsKey(_item)) { string[] _strings = new string[] { _name, _secondaryname, _category }; dict.Add(_item, _strings); int[] _integers = new int[] { _count, _quality, _price }; dict1.Add(_item, _integers); } } } } if (updateConfig) { updateConfig = false; UpdateXml(); } }
static bool Prefix(XUiC_RecipeStack __instance, ref bool __result) { if (__instance.recipe == null) { __result = false; return(false); } EntityPlayerLocal entityPlayer = __instance.xui.playerUI.entityPlayer; if (entityPlayer == null) { __result = false; return(false); } ItemValue itemValue = null; if (__instance.originalItem == null || __instance.originalItem.Equals(ItemValue.None)) { __instance.outputItemValue = new ItemValue(__instance.recipe.itemValueType, __instance.outputQuality, __instance.outputQuality, false, default(FastTags), 1f); ItemClass itemClass = __instance.outputItemValue.ItemClass; if (__instance.outputItemValue == null) { __result = false; return(false); } if (itemClass == null) { __result = false; return(false); } if (entityPlayer.entityId == __instance.startingEntityId) { __instance.giveExp(__instance.outputItemValue, itemClass); } if (__instance.recipe.GetName().Equals("meleeToolStoneAxe")) { UserProfile user = __instance.xui.playerUI.entityPlayer.user; Platform.AchievementManager.SetAchievementStat(user, EnumAchievementDataStat.StoneAxeCrafted, 1); } else if (__instance.recipe.GetName().Equals("woodFrameBlock")) { UserProfile user2 = __instance.xui.playerUI.entityPlayer.user; Platform.AchievementManager.SetAchievementStat(user2, EnumAchievementDataStat.WoodFrameCrafted, 1); } } else if (__instance.amountToRepair > 0) { ItemValue itemValue2 = __instance.originalItem.Clone(); itemValue2.UseTimes -= __instance.amountToRepair; ItemClass itemClass2 = itemValue2.ItemClass; if (itemValue2.UseTimes < 0) { itemValue2.UseTimes = 0; } __instance.outputItemValue = itemValue2.Clone(); if (__instance.originalItem.PercentUsesLeft == 0f && __instance.originalItem.Quality <= 10) { __instance.outputItemValue = null; Manager.BroadcastPlay(itemClass2.Properties.Values[ItemClass.PropSoundDestroy]); } else if (__instance.originalItem.Quality > 10) { float num = 10f; if (GameManager.Instance != null && GameManager.Instance.World != null && entityPlayer.entityId == __instance.startingEntityId) { int num2 = Mathf.FloorToInt(entityPlayer.GetCVar("AS_ConstructionTools_Lvl") / 10f); num -= (float)num2; } __instance.outputItemValue.Quality = Mathf.Max(__instance.outputItemValue.Quality - (int)num, 10); if (new ItemValue(__instance.outputItemValue.type, __instance.outputItemValue.Quality, __instance.outputItemValue.Quality, false, default(FastTags), 1f).Modifications.Length < __instance.outputItemValue.Modifications.Length) { if (__instance.outputItemValue.Modifications[__instance.outputItemValue.Modifications.Length - 1] != null) { itemValue = __instance.outputItemValue.Modifications[__instance.outputItemValue.Modifications.Length - 1].Clone(); } ItemValue[] modifications = __instance.outputItemValue.Modifications; Array.Resize(ref modifications, __instance.outputItemValue.Modifications.Length - 1); __instance.outputItemValue.Modifications = modifications; } } QuestEventManager.Current.RepairedItem(__instance.outputItemValue); __instance.amountToRepair = 0; } XUiC_WorkstationOutputGrid childByType = __instance.windowGroup.Controller.GetChildByType <XUiC_WorkstationOutputGrid>(); if (childByType != null && (__instance.originalItem == null || __instance.originalItem.Equals(ItemValue.None))) { ItemStack itemStack = new ItemStack(__instance.outputItemValue, __instance.recipe.count); ItemStack[] slots = childByType.GetSlots(); bool flag = false; for (int i = 0; i < slots.Length; i++) { if (slots[i].CanStackWith(itemStack)) { slots[i].count += __instance.recipe.count; flag = true; break; } } if (!flag) { for (int j = 0; j < slots.Length; j++) { if (slots[j].IsEmpty()) { slots[j] = itemStack; flag = true; break; } } } if (flag) { childByType.SetSlots(slots); childByType.UpdateData(slots); childByType.IsDirty = true; QuestEventManager.Current.CraftedItem(itemStack); if (__instance.playSound) { if (__instance.recipe.craftingArea != null) { WorkstationData workstationData = CraftingManager.GetWorkstationData(__instance.recipe.craftingArea); if (workstationData != null) { Manager.PlayInsidePlayerHead(workstationData.CraftCompleteSound, -1, 0f, false, false); } } else { Manager.PlayInsidePlayerHead("craft_complete_item", -1, 0f, false, false); } } } else if (!__instance.AddItemToInventory()) { __instance.isInventoryFull = true; string text = "No room in workstation output, crafting has been halted until space is cleared."; if (Localization.Exists("wrnWorkstationOutputFull", string.Empty)) { text = Localization.Get("wrnWorkstationOutputFull", string.Empty); } GameManager.ShowTooltip(entityPlayer, text); Manager.PlayInsidePlayerHead("ui_denied", -1, 0f, false, false); __result = false; return(false); } } else { if (!__instance.xui.dragAndDrop.ItemStack.IsEmpty() && __instance.xui.dragAndDrop.ItemStack.itemValue.ItemClass is ItemClassQuest) { __result = false; return(false); } ItemStack itemStack2 = new ItemStack(__instance.outputItemValue, __instance.recipe.count); if (!__instance.xui.PlayerInventory.AddItemNoPartial(itemStack2, false)) { if (itemStack2.count != __instance.recipe.count) { __instance.xui.PlayerInventory.DropItem(itemStack2); QuestEventManager.Current.CraftedItem(itemStack2); __result = true; return(false); } __instance.isInventoryFull = true; string text2 = "No room in inventory, crafting has been halted until space is cleared."; if (Localization.Exists("wrnInventoryFull", string.Empty)) { text2 = Localization.Get("wrnInventoryFull", string.Empty); } GameManager.ShowTooltip(entityPlayer, text2); Manager.PlayInsidePlayerHead("ui_denied", -1, 0f, false, false); __result = false; return(false); } else { if (__instance.originalItem != null && !__instance.originalItem.IsEmpty()) { if (__instance.recipe.ingredients.Count > 0) { QuestEventManager.Current.ScrappedItem(__instance.recipe.ingredients[0]); } } else { itemStack2.count = __instance.recipe.count - itemStack2.count; QuestEventManager.Current.CraftedItem(itemStack2); } if (__instance.playSound) { Manager.PlayInsidePlayerHead("craft_complete_item", -1, 0f, false, false); } } } if (!__instance.isInventoryFull) { __instance.originalItem = ItemValue.None.Clone(); } if (itemValue != null) { ItemStack itemStack3 = new ItemStack(itemValue, 1); if (!__instance.xui.PlayerInventory.AddItemNoPartial(itemStack3, false)) { __instance.xui.PlayerInventory.DropItem(itemStack3); } } __result = true; return(false); }
public static MainViewModel FromXML(XElement xml) { MainViewModel mvm = new MainViewModel(); XElement statusEffects = xml.Element("StatusEffects"); if (statusEffects != null) { foreach (var a in statusEffects.Elements("StatusEffect")) { mvm.StatusEffects.Add(StatusEffect.FromXML(a)); } } XElement zones = xml.Element("Zones"); if (zones != null) { mvm.Zones = new ObservableCollection <Zone>(from a in zones.Elements("Zone") select Zone.FromXML(a)); } //Link the exits. foreach (var sourceZone in mvm.Zones) { foreach (var sourceRoom in sourceZone.Rooms) { foreach (var exit in sourceRoom.Exits) { foreach (var destZone in mvm.Zones) { if (exit.ZoneID == destZone.ZoneId) { foreach (var destRoom in destZone.Rooms) { if (exit.RoomID == destRoom.RoomID) { exit.ZoneLink = destZone; exit.RoomLink = destRoom; } } } } } } } XElement interactables = xml.Element("Interactables"); if (interactables != null) { mvm.Interactables = new ObservableCollection <Interactable>(from a in interactables.Elements("Interactable") select Interactable.FromXML(a)); } XElement variables = xml.Element("Variables"); if (variables != null) { mvm.Variables = new ObservableCollection <Variable>(from a in variables.Elements("Variable") select Variable.FromXML(a)); } XElement arrays = xml.Element("Arrays"); if (arrays != null) { mvm.Arrays = new ObservableCollection <VarArray>(); mvm.Arrays = new ObservableCollection <VarArray>(from a in arrays.Elements("Array") select VarArray.FromXML(a)); } else { mvm.Arrays = new ObservableCollection <VarArray>(); } mvm.InteractableGroups.Clear(); mvm.RecalculateInteractableGroups(); XElement itemClasses = xml.Element("ItemClasses"); mvm.ItemClasses = new ObservableCollection <ItemClass>(); if (itemClasses != null) { foreach (var a in itemClasses.Elements("ItemClass")) { mvm.ItemClasses.Add(ItemClass.FromXML(a)); } } XElement settings = xml.Element("PlayerSettings"); if (settings != null) { mvm.Settings = PlayerSettings.FromXML(settings); } XElement items = xml.Element("Items"); mvm.Items = new ObservableCollection <Item>(); if (items != null) { foreach (var a in items.Elements("Item")) { mvm.Items.Add(Item.FromXml(a)); } } XElement commonEvents = xml.Element("CommonEvents"); if (commonEvents != null) { foreach (var a in commonEvents.Elements("CommonEvent")) { mvm.CommonEvents.Add(CommonEvent.FromXML(a)); } } XElement conversations = xml.Element("Conversations"); if (conversations != null) { foreach (var a in conversations.Elements("Conversation")) { mvm.Conversations.Add(Conversation.FromXML(a)); } } //Resolve all interactable references //foreach (var a in mvm.InteractableRefStack) //{ // var guid = a.Value; // var list = a.Key; // var interactable = mvm.Interactables.Where(i => i.InteractableID == guid).FirstOrDefault(); //} return(mvm); }
public void ClickButton(int ClickType) { if (DictionaryClickFrist)//item→item 第二次 { bool CanCreat = true; for (int i = 0; i < TempSelect.Raws.Length; i++) { CanCreat = Sen_Try_Bag(TempSelect.Raws[i].Num, TempSelect.Raws[i].Type.Type); if (CanCreat) { } else { break; } } if (CanCreat) { Dictionary_Button.Button[SelectFrist_Type_Dictionary].GetComponent <Image>().color = TempColor; for (int i = 0; i < TempSelect.Raws.Length; i++) { CanCreat = Sen_Try_Bag(TempSelect.Raws[i].Num, TempSelect.Raws[i].Type.Type); if (CanCreat) { Sen_Bag(TempSelect.Raws[i].Num, TempSelect.Raws[i].Type.Type); } else { break; } } if (Items[ClickType] == EmptyItem) { DictionaryClickFrist = false; ItemClassAdd(ClickType, TempSelect.GroupInBag, TempSelect); if (ClickType == SelectType) { DrawHand(SelectType); } FreshUI(ClickType, true); } else { if (Items[ClickType].Type == TempSelect.Type) { if (Items[ClickType].GroupInBag + TempItemNumber <= Items[ClickType].MaxGroupInBag) { DictionaryClickFrist = false; Items[ClickType].GroupInBag += TempItemNumber; TempItemNumber = 0; FreshUI(ClickType, true); } else { TempItemNumber -= Items[ClickType].MaxGroupInBag - Items[ClickType].GroupInBag; Items[ClickType].GroupInBag = Items[ClickType].MaxGroupInBag; FreshUI(ClickType, true); } } } } } else { if (!SelectFrist)//item→item 第一次 { if (Items[ClickType].Type >= 0) { SelectFrist = true; TempItemNumber = Items[ClickType].GroupInBag; TempSelect = Items[ClickType]; SelectFrist_Type_Items = ClickType; if (ClickType == SelectType) { DedrawHand(ClickType); } Items_Button[SelectFrist_Type_Items].GetComponent <Image>().color = TempColor; TempColor = Dictionary_Button.Button[ClickType].GetComponent <Image>().color; Items_Button[ClickType].GetComponent <Image>().color = Color_Select; } } else//item→item 第二次 { if (Items[ClickType] == EmptyItem) { SelectSecend_Type = ClickType; SelectFrist = false; if (ClickType >= 0) { ChangeBag(SelectFrist_Type_Items, ClickType); } else { ChangeBag(false); } if (ClickType == SelectType && Hand == null) { DrawHand(ClickType); } TempSelect = null; } else { if (SelectFrist_Type_Items == ClickType) { SelectFrist = false; } else { if (Items[ClickType].Type == TempSelect.Type) { if (Items[ClickType].GroupInBag + TempItemNumber <= Items[ClickType].MaxGroupInBag) { SelectFrist = false; Items[ClickType].GroupInBag += TempItemNumber; TempSelect.GroupInBag = TempItemNumber = 0; FreshUI(SelectFrist_Type_Items, true); FreshUI(ClickType, true); } else { TempSelect.GroupInBag = TempItemNumber -= Items[ClickType].MaxGroupInBag - Items[ClickType].GroupInBag; Items[ClickType].GroupInBag = Items[ClickType].MaxGroupInBag; FreshUI(SelectFrist_Type_Items, true); FreshUI(ClickType, true); } } } } } } }
private IEntity GetEnchantmentFor(IEntity item, ItemClass itemClass, int enchantPower, IRandom random) { var enchantment = _enchantmentPicker.PickEnchantmentFor(item, itemClass, enchantPower, random); return(enchantment); }
/// <summary> /// Lightweight simulation step method. /// This method is occasionally being called for different cars. /// </summary> /// <param name="vehicleId"></param> /// <param name="vehicleData"></param> /// <param name="physicsLodRefPos"></param> public void CustomSimulationStep(ushort vehicleId, ref Vehicle vehicleData, Vector3 physicsLodRefPos) { if ((vehicleData.m_flags & Vehicle.Flags.WaitingPath) != 0) { PathManager pathManager = Singleton <PathManager> .instance; byte pathFindFlags = pathManager.m_pathUnits.m_buffer[vehicleData.m_path].m_pathFindFlags; // NON-STOCK CODE START ExtPathState mainPathState = ExtPathState.Calculating; if ((pathFindFlags & PathUnit.FLAG_FAILED) != 0 || vehicleData.m_path == 0) { mainPathState = ExtPathState.Failed; } else if ((pathFindFlags & PathUnit.FLAG_READY) != 0) { mainPathState = ExtPathState.Ready; } #if BENCHMARK using (var bm = new Benchmark(null, "UpdateCarPathState")) { #endif if (Options.prohibitPocketCars && VehicleStateManager.Instance.VehicleStates[vehicleId].vehicleType == ExtVehicleType.PassengerCar) { mainPathState = AdvancedParkingManager.Instance.UpdateCarPathState(vehicleId, ref vehicleData, ref ExtCitizenInstanceManager.Instance.ExtInstances[CustomPassengerCarAI.GetDriverInstanceId(vehicleId, ref vehicleData)], mainPathState); } #if BENCHMARK } #endif // NON-STOCK CODE END if (mainPathState == ExtPathState.Ready) { vehicleData.m_pathPositionIndex = 255; vehicleData.m_flags &= ~Vehicle.Flags.WaitingPath; vehicleData.m_flags &= ~Vehicle.Flags.Arriving; this.PathfindSuccess(vehicleId, ref vehicleData); this.TrySpawn(vehicleId, ref vehicleData); } else if (mainPathState == ExtPathState.Failed) { vehicleData.m_flags &= ~Vehicle.Flags.WaitingPath; Singleton <PathManager> .instance.ReleasePath(vehicleData.m_path); vehicleData.m_path = 0u; this.PathfindFailure(vehicleId, ref vehicleData); return; } } else { if ((vehicleData.m_flags & Vehicle.Flags.WaitingSpace) != 0) { this.TrySpawn(vehicleId, ref vehicleData); } } // NON-STOCK CODE START #if BENCHMARK using (var bm = new Benchmark(null, "UpdateVehiclePosition")) { #endif VehicleStateManager.Instance.UpdateVehiclePosition(vehicleId, ref vehicleData); #if BENCHMARK } #endif if (!Options.isStockLaneChangerUsed()) { #if BENCHMARK using (var bm = new Benchmark(null, "LogTraffic")) { #endif // Advanced AI traffic measurement VehicleStateManager.Instance.LogTraffic(vehicleId); #if BENCHMARK } #endif } // NON-STOCK CODE END Vector3 lastFramePosition = vehicleData.GetLastFramePosition(); int lodPhysics; if (Vector3.SqrMagnitude(physicsLodRefPos - lastFramePosition) >= 1210000f) { lodPhysics = 2; } else if (Vector3.SqrMagnitude(Singleton <SimulationManager> .instance.m_simulationView.m_position - lastFramePosition) >= 250000f) { lodPhysics = 1; } else { lodPhysics = 0; } this.SimulationStep(vehicleId, ref vehicleData, vehicleId, ref vehicleData, lodPhysics); if (vehicleData.m_leadingVehicle == 0 && vehicleData.m_trailingVehicle != 0) { VehicleManager vehManager = Singleton <VehicleManager> .instance; ushort trailerId = vehicleData.m_trailingVehicle; int numIters = 0; while (trailerId != 0) { ushort trailingVehicle = vehManager.m_vehicles.m_buffer[(int)trailerId].m_trailingVehicle; VehicleInfo info = vehManager.m_vehicles.m_buffer[(int)trailerId].Info; info.m_vehicleAI.SimulationStep(trailerId, ref vehManager.m_vehicles.m_buffer[(int)trailerId], vehicleId, ref vehicleData, lodPhysics); trailerId = trailingVehicle; if (++numIters > 16384) { CODebugBase <LogChannel> .Error(LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace); break; } } } int privateServiceIndex = ItemClass.GetPrivateServiceIndex(this.m_info.m_class.m_service); int maxBlockCounter = (privateServiceIndex == -1) ? 150 : 100; if ((vehicleData.m_flags & (Vehicle.Flags.Spawned | Vehicle.Flags.WaitingPath | Vehicle.Flags.WaitingSpace)) == 0 && vehicleData.m_cargoParent == 0) { Singleton <VehicleManager> .instance.ReleaseVehicle(vehicleId); } else if ((int)vehicleData.m_blockCounter >= maxBlockCounter) { // NON-STOCK CODE START bool mayDespawn = true; #if BENCHMARK using (var bm = new Benchmark(null, "MayDespawn")) { #endif mayDespawn = VehicleBehaviorManager.Instance.MayDespawn(ref vehicleData); #if BENCHMARK } #endif if (mayDespawn) { // NON-STOCK CODE END Singleton <VehicleManager> .instance.ReleaseVehicle(vehicleId); } // NON-STOCK CODE } }