void CreateReplenishableContainer(BasePlayer player, ReplenishPlayer rPlayer, StorageContainer container, HitInfo info, string type) { if (GetReplenishableContainer(container.inventory) != null) { containers.Remove(GetReplenishableContainer(container.inventory)); ReplyPlayer(player, "AlreadyReplenishing"); } ReplenishableContainer repl = new ReplenishableContainer(container.inventory.uid, rPlayer.timer); repl.type = Lang(type); repl.SaveItems(container.inventory); var worldPos = info.HitEntity.transform.position; repl.pos = new Pos(worldPos.x, worldPos.y, worldPos.z); containers.Add(repl); ReplyFormatted(player, String.Format(Lang("BoxAdded"), repl.type, repl.uid, repl.timer)); }
public Workspace() { storageContainer = new StorageContainer(); }
public static bool Prefix(Constructable __instance) { if (Player.main.GetVehicle() != null && GameModeUtils.RequiresIngredients()) { Type ConstructableType = typeof(Constructable); List <TechType> resourceMapField = (List <TechType>)AccessTools.Field(ConstructableType, "resourceMap").GetValue(__instance); MethodInfo getResourceIDMethod = AccessTools.Method(ConstructableType, "GetResourceID"); MethodInfo GetConstructIntervalMethod = AccessTools.Method(ConstructableType, "GetConstructInterval"); MethodInfo updateMaterialMethod = AccessTools.Method(ConstructableType, "UpdateMaterial"); Vehicle thisVehicle = Player.main.GetVehicle(); if (__instance._constructed) { return(true); } int count = resourceMapField.Count; int resourceID = (int)getResourceIDMethod.Invoke(__instance, null); float backupConstructedAmount = __instance.constructedAmount; __instance.constructedAmount -= Time.deltaTime / (count * (float)GetConstructIntervalMethod.Invoke(__instance, null)); __instance.constructedAmount = Mathf.Clamp01(__instance.constructedAmount); int resourceID2 = (int)getResourceIDMethod.Invoke(__instance, null); if (resourceID2 != resourceID) { TechType techType = resourceMapField[resourceID2]; GameObject gameObject = CraftData.InstantiateFromPrefab(techType, false); Pickupable component = gameObject.GetComponent <Pickupable>(); if (thisVehicle.GetType().Equals(typeof(Exosuit))) { StorageContainer storageContainer = ((Exosuit)thisVehicle).storageContainer; if (storageContainer.container.HasRoomFor(component)) { string name = Language.main.Get(component.GetTechName()); ErrorMessage.AddMessage(Language.main.GetFormat("VehicleAddedToStorage", name)); uGUI_IconNotifier.main.Play(component.GetTechType(), uGUI_IconNotifier.AnimationType.From, null); #if SUBNAUTICA component = component.Initialize(); #elif BELOWZERO component.Initialize(); #endif var item = new InventoryItem(component); storageContainer.container.UnsafeAdd(item); component.PlayPickupSound(); } else { __instance.constructedAmount = backupConstructedAmount; return(true); } } else { var seamoth = (SeaMoth)thisVehicle; bool storageCheck = false; for (int i = 0; i < 12; i++) { try { ItemsContainer storage = seamoth.GetStorageInSlot(i, TechType.VehicleStorageModule); if (storage != null && storage.HasRoomFor(component)) { string name = Language.main.Get(component.GetTechName()); ErrorMessage.AddMessage(Language.main.GetFormat("VehicleAddedToStorage", name)); uGUI_IconNotifier.main.Play(component.GetTechType(), uGUI_IconNotifier.AnimationType.From, null); #if SUBNAUTICA component = component.Initialize(); #elif BELOWZERO component.Initialize(); #endif var item = new InventoryItem(component); storage.UnsafeAdd(item); component.PlayPickupSound(); storageCheck = true; break; } } catch (Exception) { continue; } } if (!storageCheck) { __instance.constructedAmount = backupConstructedAmount; return(true); } } } updateMaterialMethod.Invoke(__instance, null); return(__instance.constructedAmount <= 0f); } else { return(true); } }
protected virtual ValueTask <IStateStorage <S, K> > GetStateStorage() { return(StorageContainer.GetStateStorage <K, S>(this)); }
void CloseBank(BasePlayer player, StorageContainer view) { if (!onlinePlayers.ContainsKey(player)) { return; } if (onlinePlayers [player].View == null) { return; } if (!banks.ContainsKey(player.userID)) { return; } BankProfile profile = banks [player.userID]; InvalidateBank(player, profile, view); profile.items.Clear(); foreach (Item item in view.inventory.itemList) { profile.Add(item); } SaveProfile(player.userID, profile); foreach (Item item in view.inventory.itemList.ToArray()) { if (item.position != -1) { item.RemoveFromContainer(); item.Remove(0f); } } profile.open = false; if (containers.ContainsKey(view.inventory)) { containers.Remove(view.inventory); } player.inventory.loot.containers = new List <ItemContainer> (); view.inventory = new ItemContainer(); if (player.inventory.loot.IsLooting()) { player.SendConsoleCommand("inventory.endloot", null); } onlinePlayers [player].View = null; onlinePlayers [player].Target = null; UnityEngine.Object.Destroy(view); //view.Kill (BaseNetworkable.DestroyMode.None); timer.In(1f, delegate() { if (onlinePlayers.Values.Count(p => p.View != null) <= 0) { Unsubscribe(nameof(CanNetworkTo)); Unsubscribe(nameof(OnEntityTakeDamage)); } }); }
/// <summary> /// インスタンスを生成します。 /// </summary> /// <param name="container">StorageContainer。</param> /// <param name="name">ディレクトリ名。</param> /// <param name="path">ルート ディレクトリからの相対ディレクトリ パス。</param> StorageDirectory(StorageContainer container, string name, string path) { this.container = container; Name = name; Path = path; }
public Task RetractAsync(StorageContainer model) { return(Wait()); }
/// <summary> /// Loads the contents of a physical folder into structured storage /// </summary> /// <param name="path">The current physical path to load</param> /// <param name="container">The StorageContainer to be loaded</param> void ProcessStorageFolder(string path, StorageContainer container, WorkerProgressHandler progress) { byte[] buffer = new byte[8192]; // Local file buffer array int read; // Bytes read from the file Invoke(progress, new object[] { "Processing folder " + path }); // Add all of the files into the StorageContainer by creating new // StorageObjects for each of them and copying the data 8KB at a time foreach (string filename in Directory.GetFiles(path)) { StorageObject obj = container.Objects.Add(Path.GetFileName(filename)); using (FileStream reader = File.OpenRead(filename)) { using (StorageObjectStream writer = obj.GetWriter()) { do { read = reader.Read(buffer, 0, 8192); if (read > 0) writer.Write(buffer, 0, read); } while (read > 0); } } } // Now recursively create all of the subdirectories and process them foreach (string folder in Directory.GetDirectories(path)) { StorageContainer cont = container.Containers.Add(Path.GetFileName(folder)); ProcessStorageFolder(folder, cont, progress); } }
private bool ProcessItemChanged(Item newItem, int position, Item oldItem, StorageContainer container, bool isRemoving) { return(isRemoving? OnItemRemoved(newItem, position, oldItem) : OnItemAdded(newItem, position, oldItem, container)); }
public Task DeployAsync(StorageContainer model) { return(Wait()); }
private static bool IsCarryAll(StorageContainer __instance) { return(__instance.transform.parent != null && __instance.transform.parent.gameObject.name.StartsWith("docking_luggage_01_bag4")); }
private static bool IsWaterproofLocker(StorageContainer __instance) { return(__instance.gameObject.GetComponent <SmallStorage>() != null); }
private static bool IsCyclopsLocker(StorageContainer __instance) { return(__instance.gameObject.name.StartsWith("submarine_locker_01_door")); }
public void Clear() { View = null; Trade = null; }
public Task SuspendAsync(StorageContainer model) { return(Wait()); }
/// <summary> /// Loads the options from the XML. /// </summary> public void Load() { Program.Cutter.WriteToLog(this, "Attempting to load game data."); #if XBOX360 try { if(container == null) { if(initializing) throw new FileNotFoundException("Set Manager to null and continue along."); int? devSelRes; do { devSelRes = SimpleMessageBox.ShowMessageBox("Save", "No storage device is selected. Please select a device.", new string[] { "Select a Device", "Continue Without Saving" }, 0, MessageBoxIcon.Alert); switch(devSelRes) { case -1: // Fall through case 1: returnOptionsToDefault(); return; case 0: StorageDevice.BeginShowSelector(storageSelectEnd, null); break; } } while(devSelRes == null); } try { FileNotFound: if(!container.FileExists(filename)) { if(!container.FileExists(backupName)) { if(initializing) throw new FileNotFoundException("Set Manager to null and continue along."); int? fileResult; do { fileResult = SimpleMessageBox.ShowMessageBox("No File Found", "No options file was found on the storage device. Would you like to create a new file or select a new device?", new string[] { "Create File", "Select New Device", "Exit Without Loading" }, 0, MessageBoxIcon.Alert); switch(fileResult) { case 0: New(); return; case 1: result = StorageDevice.BeginShowSelector(null, null); result.AsyncWaitHandle.WaitOne(); device = StorageDevice.EndShowSelector(result); result.AsyncWaitHandle.Close(); result = device.BeginOpenContainer("Accelerated Delivery", null, null); result.AsyncWaitHandle.WaitOne(); container = device.EndOpenContainer(result); result.AsyncWaitHandle.Close(); goto FileNotFound; case -1: // Fall through case 2: returnOptionsToDefault(); return; } } while(fileResult == null); } } currentStream = container.OpenFile(filename, FileMode.Open); HandleEncryption(ref currentStream); file = (SaveFile)saveDataSerializer.Deserialize(currentStream); currentStream.Close(); container.Dispose(); } catch { try { if(!initializing) { int? lalala; do { lalala = SimpleMessageBox.ShowMessageBox("Warning", "The save file was missing or corrupted, but a backup file was found. Loading backup file.", new string[] { "Okay" }, 0, MessageBoxIcon.Alert); } while(lalala == null); } backupStream = container.OpenFile(backupName, FileMode.Open); HandleEncryption(ref backupStream); file = (SaveFile)saveDataSerializer.Deserialize(backupStream); currentStream = container.CreateFile(filename); backupStream.Seek(0, SeekOrigin.Begin); backupStream.CopyTo(currentStream); currentStream.Close(); backupStream.Close(); container.Dispose(); } catch(Exception ex) { if(backupStream != null) backupStream.Close(); if(currentStream != null) currentStream.Close(); if(container != null) container.Dispose(); throw ex; } } #elif WINDOWS // Attempt to load primary save try { if(!File.Exists(filename)) { if(!File.Exists(backupName)) New(); } currentStream = File.Open(filename, FileMode.Open); HandleEncryption(ref currentStream); try { file = (SaveFile)saveDataSerializer.Deserialize(currentStream); } catch { currentStream.Seek(0, SeekOrigin.Begin); HandleEncryption(ref currentStream); file = (SaveFile)saveDataSerializer.Deserialize(currentStream); } // at this point loading was successful // it will always be safe to copy to backup at this point currentStream.Seek(0, SeekOrigin.Begin); backupStream = File.Open(backupName, FileMode.Create); currentStream.CopyTo(backupStream); backupStream.Close(); //HandleEncryption(ref currentStream); // re-encrypts the file currentStream.Close(); SaveGame1 = file.save1; SaveGame2 = file.save2; SaveGame3 = file.save3; currentSave = file.currentSaveGame; SuccessfulLoad = true; Program.Cutter.WriteToLog(this, "Load successful."); } catch(Exception ex) { Program.Cutter.WriteToLog(this, "An error occurred while loading game data. Attempting to load backup save."); Program.Cutter.WriteExceptionToLog(ex, false); try { FileStream dump = File.Open(Program.SavePath + "dump.sav", FileMode.Create); currentStream.Seek(0, SeekOrigin.Begin); currentStream.CopyTo(dump); dump.Close(); } catch(Exception exc) { Program.Cutter.WriteToLog(this, "Could not dump save file."); Program.Cutter.WriteExceptionToLog(exc, false); } finally { // Attempt to load backup save and copy data to current save try { if(File.Exists(backupName)) { backupStream = File.Open(backupName, FileMode.Open); HandleEncryption(ref backupStream); file = (SaveFile)saveDataSerializer.Deserialize(backupStream); currentStream = File.Open(filename, FileMode.Create); backupStream.Seek(0, SeekOrigin.Begin); backupStream.CopyTo(currentStream); currentStream.Close(); backupStream.Close(); SaveGame1 = file.save1; SaveGame2 = file.save2; SaveGame3 = file.save3; currentSave = file.currentSaveGame; SuccessfulLoad = true; Program.Cutter.WriteToLog(this, "Load successful."); } else { Program.Cutter.WriteToLog(this, "Backup save was not there. Load failed."); DialogResult d = MessageBox.Show("The save file is corrupt. Is it okay to create a new save file? This will erase your progress.", "Error!", MessageBoxButtons.YesNo); if(d == DialogResult.Yes) New(); else Program.Game.Exit(); } } catch { // Primary and backups are faulty, throw error if(backupStream != null) backupStream.Close(); if(currentStream != null) currentStream.Close(); SuccessfulLoad = false; Program.Cutter.WriteToLog(this, "Primary and backup saves are faulty or missing. Load failed. Error is:"); Program.Cutter.WriteExceptionToLog(ex, false); DialogResult d = MessageBox.Show("The save file is corrupt. Is it okay to create a new save file? This will erase your progress.", "Error!", MessageBoxButtons.YesNo); if(d == DialogResult.Yes) New(); else Program.Game.Exit(); } } } #endif }
public string GetEscapePodStorageGuid(Transform ownerTransform) { StorageContainer SC = ownerTransform.parent.gameObject.RequireComponentInChildren <StorageContainer>(); return(GuidHelper.GetGuid(SC.gameObject)); }
public StoragePlugin(Context context) { _container = new StorageContainer(context, nameof(StoragePlugin)); }
public StoragePlugin() { _container = new StorageContainer(nameof(StoragePlugin)); }
//for editing a preexisting container public NewContainerPage(string name, string notes, List <string> tags, int id, StorageContainer prevContainer, StorageLocation location) : base() { this.location = location; InitializeComponent(); InitContent(); newContainerId = id; this.nameInput.Text = name; this.notesEditor.Text = notes; this.previousContainer = prevContainer; this.isEditing = true; if (isEditing) { this.Title = "Editing"; } tagDisplay = new TagDisplay(); this.tagDisplayWrapper.Children.Add(tagDisplay); tagDisplay.AddTagBatch(tags); //set colors this.BackgroundColor = PageColors.secondaryColor; InitContent(); //set image if (ImageTools.HasImage(previousContainer)) { if (ImageBaseHandler.current.isContainerCached(previousContainer.GetId())) { SetImageHolderContent(ImageBaseHandler.current.GetContainerImageSource(previousContainer.GetId())); } else { ImageSource imageLoadTask = ImageTools.LoadImage(System.IO.Path.Combine(Directories.locationImageDirectory, id.ToString() + ".jpg")); SetImageHolderContent(imageLoadTask); } } }
protected virtual void Start() { container = GetComponent <StorageContainer>(); Common.Debug.assert(container); }
public static bool Prefix(Constructable __instance) { if (Player.main.GetVehicle() != null && GameModeUtils.RequiresIngredients()) { Type ConstructableType = typeof(Constructable); List <TechType> resourceMapField = (List <TechType>)AccessTools.Field(ConstructableType, "resourceMap").GetValue(__instance); MethodInfo getResourceIDMethod = AccessTools.Method(ConstructableType, "GetResourceID"); MethodInfo GetConstructIntervalMethod = AccessTools.Method(ConstructableType, "GetConstructInterval"); MethodInfo updateMaterialMethod = AccessTools.Method(ConstructableType, "UpdateMaterial"); Vehicle thisVehicle = Player.main.GetVehicle(); if (__instance._constructed) { return(false); } int count = resourceMapField.Count; int resourceID = (int)getResourceIDMethod.Invoke(__instance, null); float backupConstructedAmount = __instance.constructedAmount; __instance.constructedAmount += Time.deltaTime / (count * (float)GetConstructIntervalMethod.Invoke(__instance, null)); __instance.constructedAmount = Mathf.Clamp01(__instance.constructedAmount); int resourceID2 = (int)getResourceIDMethod.Invoke(__instance, null); if (resourceID2 != resourceID) { TechType destroyTechType = resourceMapField[resourceID2 - 1]; if (thisVehicle.GetType().Equals(typeof(Exosuit))) { StorageContainer storageContainer = ((Exosuit)thisVehicle).storageContainer; if (storageContainer.container.Contains(destroyTechType)) { _ = storageContainer.container.DestroyItem(destroyTechType); } else { __instance.constructedAmount = backupConstructedAmount; return(true); } } else { var seamoth = (SeaMoth)thisVehicle; bool storageCheck = false; for (int i = 0; i < 12; i++) { try { ItemsContainer storage = seamoth.GetStorageInSlot(i, TechType.VehicleStorageModule); if (storage != null && storage.Contains(destroyTechType)) { if (storage.DestroyItem(destroyTechType)) { storageCheck = true; break; } } } catch (Exception) { continue; } } if (!storageCheck) { __instance.constructedAmount = backupConstructedAmount; return(true); } } } _ = updateMaterialMethod.Invoke(__instance, null); if (__instance.constructedAmount >= 1f) { _ = __instance.SetState(true, true); } return(false); } else { return(true); } }
void OnEntityDeath(BaseCombatEntity entity, HitInfo info) { // Check to see if the LootContainer got destroyed StorageContainer container = entity as StorageContainer; if (container != null && State.LootContainer == container) { State.LootContainer = null; return; } BasePlayer victim = entity.ToPlayer(); if (victim == null) { return; } BasePlayer attacker = null; if (info != null && info.Initiator != null) { attacker = info.Initiator.ToPlayer(); } // Handle Boss Death if (State.IsBoss(victim)) { // Killed by Player? if (attacker != null) { if (State.IsBoss(attacker)) { State.SetBoss(null); PrintToChat(Text.Broadcast_BossSuicide, attacker.displayName); } else { State.SetBoss(attacker); PrintToChat(Text.Broadcast_NewBoss, State.BossName, victim.displayName); } } else { PrintToChat("Boss {0} died foolishly. You can /claim the title.", State.BossName); State.SetBoss(null); } return; } // Handle Outlaw Death if (State.Outlaws.Contains(victim) && State.IsBoss(attacker)) { State.Outlaws.Remove(victim); PrintToChat("Boss {0} executed outlaw {1}. He died like the rebel dog he was.", State.BossName, victim.displayName); return; } // Handle Outlaw Death if (State.Outlaws.Contains(victim) && State.Henchmen.Contains(attacker)) { State.Outlaws.Remove(victim); PrintToChat("Henchman {0} made the world a better place: outlaw {1} is worm food.", attacker.displayName, victim.displayName); return; } // Spice up murder, a little bit if (!State.Outlaws.Contains(victim) && !State.IsBoss(victim) && !State.Henchmen.Contains(victim) && attacker != null && !State.IsBoss(attacker) && !State.Outlaws.Contains(attacker) && !State.Henchmen.Contains(attacker) && attacker != victim) { State.Outlaws.Add(attacker); PrintToChat("{0} has embarked on a life of crime, and is now an Outlaw.", attacker.displayName); return; } }
private bool CanMoveItemsFrom(BaseEntity entity, Item item) { StorageContainer storageContainer = entity as StorageContainer; return(!Object.op_Implicit((Object)storageContainer) || storageContainer.CanMoveFrom(this.baseEntity, item)); }
/// <summary> /// Initializes a new instance of the StorageContainerSession class. /// </summary> /// <param name="provider">The associated storage provider.</param> /// <param name="container">The associated storage container.</param> internal StorageSession(StorageProvider provider, StorageContainer container) { this.Provider = provider; this.container = container; }
protected virtual ValueTask <IEventStorage <K> > GetEventStorage() { return(StorageContainer.GetEventStorage <K, S>(this)); }
public override GameObject GetGameObject() { GameObject prefab = GameObject.Instantiate(this.GameObject); prefab.name = this.ClassID; // Update TechTag TechTag techTag = prefab.GetComponent <TechTag>(); techTag.type = this.TechType; // Update prefab ID PrefabIdentifier prefabId = prefab.GetComponent <PrefabIdentifier>(); prefabId.ClassId = this.ClassID; // Update StorageContainer StorageContainer sc = prefab.GetComponent <StorageContainer>(); sc.height = 2; // Update Planter var planter = prefab.GetComponent <Planter>(); if (planter != null) { planter.isIndoor = false; planter.environment = Planter.PlantEnvironment.Water; } // Update constructable Constructable constructable = prefab.GetComponent <Constructable>(); constructable.allowedOutside = true; constructable.allowedInBase = ConfigSwitcher.AllowOutdoorLongPlanterInside; constructable.allowedInSub = ConfigSwitcher.AllowOutdoorLongPlanterInside; constructable.placeMinDistance = 0.8f; // Update constructable bounds ConstructableBounds bounds = prefab.GetComponent <ConstructableBounds>(); bounds.bounds.extents = new Vector3(bounds.bounds.extents.x * 0.3f, bounds.bounds.extents.y * 0.4f, bounds.bounds.extents.z); bounds.bounds.position = new Vector3(bounds.bounds.position.x + 0.3f, bounds.bounds.position.y * 0.4f, bounds.bounds.position.z); float xPad = 1.22f; //0.5f; float yPad = -0.25f; float scaleRatio = 0.4f; float heightScaleRatio = 0.5f; // Update box collider GameObject objectTrigger = prefab.FindChild("collider"); BoxCollider objectCollider = objectTrigger.GetComponent <BoxCollider>(); objectCollider.size = new Vector3(objectCollider.size.x * scaleRatio, objectCollider.size.y * heightScaleRatio, objectCollider.size.z); //objectCollider.center = new Vector3(objectCollider.center.x + pad, objectCollider.center.y, objectCollider.center.z); // Update model GameObject model = prefab.FindChild("model"); model.transform.localScale = new Vector3(model.transform.localScale.x * scaleRatio, model.transform.localScale.y * heightScaleRatio, model.transform.localScale.z); //model.transform.localPosition = new Vector3(model.transform.localPosition.x + pad, model.transform.localPosition.y, model.transform.localPosition.z); //model.transform.localRotation = new Quaternion(model.transform.localRotation.x, model.transform.localRotation.y + 20.0f, model.transform.localRotation.z, model.transform.localRotation.w); GameObject slots = prefab.FindChild("slots"); foreach (Transform tr in slots.transform) { tr.localPosition = new Vector3(tr.localPosition.x + xPad, tr.localPosition.y + yPad, tr.localPosition.z); } GameObject slotsSmall = prefab.FindChild("slots_small"); foreach (Transform tr in slotsSmall.transform) { tr.localPosition = new Vector3(tr.localPosition.x + xPad, tr.localPosition.y + yPad, tr.localPosition.z); } // Update sky applier SkyApplier sa = prefab.GetComponent <SkyApplier>(); if (sa == null) { sa = prefab.GetComponentInChildren <SkyApplier>(); } if (sa == null) { sa = prefab.AddComponent <SkyApplier>(); } sa.renderers = prefab.GetComponentsInChildren <Renderer>(); sa.anchorSky = Skies.Auto; return(prefab); }
/// <summary> /// Loads the save file with the given file name, or returns an empty save /// if the file doens't exist. /// </summary> /// <param name="fileName"></param> /// <returns></returns> private SaveFile LoadFile(string fileName) { SaveFile file = new SaveFile(fileName); StorageContainer container = SmileyUtil.GetStorageContainer(); if (!container.FileExists(fileName)) { file.IsEmpty = true; return(file); } //Select the specified save file using (BitStream input = new BitStream(container, fileName, BitStreamMode.Read)) { file.TimePlayed = TimeSpan.FromTicks(input.ReadBits(64)); //Load abilties foreach (Ability ability in Enum.GetValues(typeof(Ability))) { file.HasAbility[ability] = input.ReadBit(); } //Load keys for (int i = 0; i < 5; i++) { for (int j = 0; j < 4; j++) { file.NumKeys[i, j] = input.ReadByte(); } } //Load gems foreach (Level level in Enum.GetValues(typeof(Level))) { foreach (Gem gem in Enum.GetValues(typeof(Gem))) { file.NumGems[level][gem] = input.ReadByte(); } } //Load money file.Money = input.ReadByte(); //Load upgrades foreach (Upgrade upgrade in Enum.GetValues(typeof(Upgrade))) { file.NumUpgrades[upgrade] = input.ReadByte(); } //Load which bosses have been slain foreach (Boss boss in Enum.GetValues(typeof(Boss))) { file.HasKilledBoss[boss] = input.ReadBit(); } //Load player zone and location file.Level = (Level)input.ReadByte(); file.PlayerGridX = input.ReadByte(); file.PlayerGridY = input.ReadByte(); //Health and mana file.PlayerHealth = (float)(input.ReadByte() / 4); file.PlayerMana = (float)(input.ReadByte()); //Load changed shit int numChanges = input.ReadBits(16); for (int i = 0; i < numChanges; i++) { file.ChangeTile((Level)input.ReadByte(), input.ReadByte(), input.ReadByte()); } //Load Stats file.NumTongueLicks = input.ReadByte(); file.NumEnemiesKilled = input.ReadByte(); file.PixelsTraversed = input.ReadBits(24); //Tutorial Man file.AdviceManEncounterCompleted = input.ReadBit(); for (int i = 0; i < 3; i++) { SMH.GUI.SetAbilityInSlot((Ability)input.ReadBits(5), i); } foreach (Level level in Enum.GetValues(typeof(Level))) { file.HasVisitedLevel[level] = input.ReadBit(); } file.Difficulty = (Difficulty)input.ReadByte(); //Exploration data foreach (Level level in Enum.GetValues(typeof(Level))) { for (int j = 0; j < 256; j++) { for (int k = 0; k < 256; k++) { file.Explored[level][j, k] = input.ReadBit(); } } } } file.TimeFileLoaded = DateTime.Now.TimeOfDay; return(file); }
private static void AddInventory(TechType techType, int count = 1, bool bNoMessage = false, bool bSpawnIfCantAdd = true) { // Ripped<cough>based upon MrPurple6411's method Deconstruct_Patch from the BuilderModule if (Player.main.isPiloting) { #if SUBNAUTICA_STABLE //GameObject gameObject = CraftData.InstantiateFromPrefab(techType, false); GameObject prefabForTechType = CraftData.GetPrefabForTechType(techType, true); GameObject gameObject = (prefabForTechType != null) ? global::Utils.SpawnFromPrefab(prefabForTechType, null) : global::Utils.CreateGenericLoot(techType); #elif BELOWZERO GameObject gameObject = CraftData.InstantiateFromPrefab(null, techType, false); // Coming back to this months later, I didn't think this worked in BZ, because it's not async. But apparently it does... #endif Pickupable pickup = gameObject.GetComponent <Pickupable>(); if (pickup != null) { pickup.Initialize(); // This is kind of messy but it's an easy way to get the cross-game code running. In SN1 modules will always == null so the block won't run; but it'll still compile. #if SUBNAUTICA_STABLE Equipment modules = null; #elif BELOWZERO SeaTruckUpgrades upgrades = Player.main.GetComponentInParent <SeaTruckUpgrades>(); Equipment modules = upgrades?.modules; #endif if (modules != null && TechTypeHandler.TryGetModdedTechType("SeaTruckStorage", out TechType storageType)) { //HashSet<string> TruckSlotIDs = modules.equipment.Keys.ToSet<string>(); List <string> TruckSlotIDs = null; modules.GetSlots(EquipmentType.SeaTruckModule, TruckSlotIDs); foreach (string slot in TruckSlotIDs) { InventoryItem item = modules.GetItemInSlot(slot); if (item.item.GetTechType() == storageType) { //InventoryItem item = modules.GetItemInSlot(slot); if (item.item.TryGetComponent(out SeamothStorageContainer seamothStorageContainer)) { InventoryItem newItem = new InventoryItem(pickup); if (seamothStorageContainer.container.AddItem(newItem) != null) { string name = Language.main.Get(pickup.GetTechName()); ErrorMessage.AddMessage(Language.main.GetFormat("VehicleAddedToStorage", name)); //uGUI_IconNotifier.main.Play(pickup.GetTechType(), uGUI_IconNotifier.AnimationType.From, null); uGUI_IconNotifier.main.Play(techType, uGUI_IconNotifier.AnimationType.From, null); pickup.PlayPickupSound(); #if !RELEASE Logger.Log(Logger.Level.Debug, $"Adding tech {techType} to Seatruck storage"); #endif return; } } } } } else { Vehicle thisVehicle = Player.main.GetVehicle(); if (thisVehicle != null) { if (thisVehicle is Exosuit exo) { StorageContainer storageContainer = exo.storageContainer; if (storageContainer != null) { int lastCount = storageContainer.container.GetCount(techType); storageContainer.container.AddItem(pickup); int techCount = storageContainer.container.GetCount(techType); #if !RELEASE Logger.Log(Logger.Level.Debug, $"Adding tech {techType.AsString().PadLeft(15)} to Exosuit storage; previous count {lastCount}, new count {techCount}"); #endif if (techCount - lastCount == 1) { string name = Language.main.Get(pickup.GetTechName()); ErrorMessage.AddMessage(Language.main.GetFormat("VehicleAddedToStorage", name)); uGUI_IconNotifier.main.Play(pickup.GetTechType(), uGUI_IconNotifier.AnimationType.From, null); pickup.PlayPickupSound(); return; } } } else if (thisVehicle is SeaMoth seamoth) { //bool storageCheck = false; List <IItemsContainer> containers = new List <IItemsContainer>(); seamoth.GetAllStorages(containers); //for (int i = 0; i < 12; i++) InventoryItem newItem = new InventoryItem(pickup); foreach (IItemsContainer storage in containers) { try { //ItemsContainer storage = seamoth.GetStorageInSlot(i, TechType.VehicleStorageModule); if (storage is ItemsContainer iContainer) { int lastCount = iContainer.GetCount(techType); iContainer.AddItem(pickup); int techCount = iContainer.GetCount(techType); #if !RELEASE Logger.Log(Logger.Level.Debug, $"Adding tech {techType.AsString().PadLeft(15)} to Seamoth storage; previous count {lastCount}, new count {techCount}"); #endif if (techCount - lastCount == 1) { string name = Language.main.Get(pickup.GetTechName()); ErrorMessage.AddMessage(Language.main.GetFormat("VehicleAddedToStorage", name)); uGUI_IconNotifier.main.Play(pickup.GetTechType(), uGUI_IconNotifier.AnimationType.From, null); pickup.PlayPickupSound(); //storageCheck = true; return; } } } catch (Exception e) { #if !RELEASE Logger.Log(Logger.Level.Debug, $"Exception adding tech {techType} to Seamoth storage: {e.ToString()}"); #endif continue; } } /*if (storageCheck) * { * return; * }*/ } } } } } #if !RELEASE Logger.Log(Logger.Level.Debug, $"Adding tech {techType} to player inventory"); #endif CraftData.AddToInventory(techType, count, bNoMessage, bSpawnIfCantAdd); }
void CloseBoxView(BasePlayer player, StorageContainer view) { OnlinePlayer onlinePlayer; if (!onlinePlayers.TryGetValue(player, out onlinePlayer)) { return; } if (onlinePlayer.View == null) { return; } HideTrade(player); if (onlinePlayer.Trade != null) { OpenTrade t = onlinePlayer.Trade; t.closing = true; if (t.sourcePlayer == player && t.targetPlayer != player && t.target.View != null) { t.target.Trade = null; CloseBoxView(t.targetPlayer, t.target.View); } else if (t.targetPlayer == player && t.sourcePlayer != player && t.source.View != null) { t.source.Trade = null; CloseBoxView(t.sourcePlayer, t.source.View); } if (openTrades.Contains(t)) { openTrades.Remove(t); } } if (view.inventory.itemList.Count > 0) { foreach (Item item in view.inventory.itemList.ToArray()) { if (item.position != -1) { item.MoveToContainer(player.inventory.containerMain); } } } if (player.inventory.loot.entitySource != null) { player.inventory.loot.Invoke("SendUpdate", 0.1f); view.SendMessage("PlayerStoppedLooting", player, SendMessageOptions.DontRequireReceiver); player.SendConsoleCommand("inventory.endloot", null); } player.inventory.loot.entitySource = null; player.inventory.loot.itemSource = null; player.inventory.loot.containers = new List <ItemContainer>(); view.inventory = new ItemContainer(); onlinePlayer.Clear(); view.Kill(BaseNetworkable.DestroyMode.None); if (onlinePlayers.Values.Count(p => p.View != null) <= 0) { Unsubscribe(nameof(CanNetworkTo)); } }
/// <summary> /// Create new replay for a specific track number. /// </summary> /// <param name="setTrackNum">Set track number</param> public Replay(int setTrackNum, bool createNew, Track track) { trackNum = setTrackNum; // if creating new, we're done if (createNew == true) { return; } bool replayFileFound = false; FileHelper.StorageContainerMRE.WaitOne(); FileHelper.StorageContainerMRE.Reset(); try { StorageDevice storageDevice = FileHelper.XnaUserDevice; if ((storageDevice != null) && storageDevice.IsConnected) { using (StorageContainer container = storageDevice.OpenContainer("RacingGame")) { string fullPath = Path.Combine( container.Path, ReplayFilenames[trackNum]); if (File.Exists(fullPath)) { replayFileFound = true; using (FileStream stream = File.Open(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (BinaryReader reader = new BinaryReader(stream)) { // Load total lap time lapTime = reader.ReadSingle(); // Load matrix values int numOfMatrixValues = reader.ReadInt32(); for (int num = 0; num < numOfMatrixValues; num++) { trackMatrixValues.Add( FileHelper.ReadMatrix(reader)); } // Load checkpoint times int numOfCheckpointTimes = reader.ReadInt32(); for (int num = 0; num < numOfCheckpointTimes; num++) { checkpointTimes.Add(reader.ReadSingle()); } } } } } } } catch (Exception exc) { System.Diagnostics.Trace.WriteLine("Settings Load Failure: " + exc.ToString()); } FileHelper.StorageContainerMRE.Set(); // Load if possible if (!replayFileFound && File.Exists(Path.Combine( Directories.ContentDirectory, ReplayFilenames[trackNum]))) { using (FileStream stream = FileHelper.LoadGameContentFile( "Content\\" + ReplayFilenames[trackNum])) { using (BinaryReader reader = new BinaryReader(stream)) { // Load total lap time lapTime = reader.ReadSingle(); // Load matrix values int numOfMatrixValues = reader.ReadInt32(); for (int num = 0; num < numOfMatrixValues; num++) { trackMatrixValues.Add( FileHelper.ReadMatrix(reader)); } // Load checkpoint times int numOfCheckpointTimes = reader.ReadInt32(); for (int num = 0; num < numOfCheckpointTimes; num++) { checkpointTimes.Add(reader.ReadSingle()); } } } } if (!replayFileFound) { // Create new default replay for this track! // Get all track positions based on the current top highscore time! lapTime = Highscores.GetTopLapTime(trackNum); int numOfMatrixValues = 1 + (int)(lapTime / TrackMatrixIntervals); float lastTrackPos = 0.0f; int oldTrackSegmentNumber = 0; // Go twice as long and abort when we reach the finish line! for (int num = 0; num < numOfMatrixValues * 2; num++) { // See Landscape.TestRenderLandscape for more details. float carTrackPos = 0.00001f + ((float)num / (float)(numOfMatrixValues - 1));// * //not needed, scaled in GetTrackPositionMatrix: track.Length; float difference = carTrackPos - lastTrackPos; carTrackPos = lastTrackPos + difference * 0.1f; lastTrackPos = carTrackPos; float roadWidth, nextRoadWidth; Matrix carMatrix = track.GetTrackPositionMatrix(carTrackPos, out roadWidth, out nextRoadWidth); // Store trackMatrixValues.Add(carMatrix); // Also check if we passed a checkpoint int trackSegmentNumber = (int)(carTrackPos * track.NumberOfSegments); // Segment changed if (trackSegmentNumber != oldTrackSegmentNumber) { // Check if we passed a checkpoint. for (int checkpointNum = 0; checkpointNum < track. CheckpointSegmentPositions.Count; checkpointNum++) { // We have to check if we are between the old // and the current track segement numbers, we // might skip one or two in 200ms. if (track.CheckpointSegmentPositions[checkpointNum] > oldTrackSegmentNumber && track.CheckpointSegmentPositions[checkpointNum] <= trackSegmentNumber) { // We passed that checkpoint, add the simulated time checkpointTimes.Add( lapTime * (float)num / (float)(numOfMatrixValues - 1)); break; } } } oldTrackSegmentNumber = trackSegmentNumber; // Reached finish? if (carTrackPos >= 1.0f) { // Then abort, do not add more. break; } } // Add the final checkpoint for the laptime checkpointTimes.Add(lapTime); } }
private void ShowTrade(BasePlayer player, OpenTrade trade, string status) { HideTrade(player); OnlinePlayer onlinePlayer; if (!onlinePlayers.TryGetValue(player, out onlinePlayer)) { return; } if (onlinePlayer.View == null) { return; } StorageContainer sourceContainer = onlinePlayer.View; StorageContainer targetContainer = null; BasePlayer target = null; if (trade.sourcePlayer == player && trade.target.View != null) { targetContainer = trade.target.View; target = trade.targetPlayer; if (target is BasePlayer) { if (trade.targetAccept) { status += string.Format(GetMsg("Trade: They Accepted", player), CleanName(target.displayName)); } else if (trade.sourceAccept) { status += GetMsg("Trade: You Accepted", player); } } else { return; } } else if (trade.targetPlayer == player && trade.source.View != null) { targetContainer = trade.source.View; target = trade.sourcePlayer; if (target is BasePlayer) { if (trade.sourceAccept) { status += string.Format(GetMsg("Trade: They Accepted", player), CleanName(target.displayName)); } else if (trade.targetAccept) { status += GetMsg("Trade: You Accepted", player); } } else { return; } } if (targetContainer == null || target == null) { return; } string send = jsonTrade; for (int i = 1; i < 100; i++) { send = send.Replace("{" + i + "}", Oxide.Core.Random.Range(9999, 99999).ToString()); } send = send.Replace("{sourcename}", CleanName(player.displayName)); if (target != null) { send = send.Replace("{targetname}", CleanName(target.displayName)); } else { send = send.Replace("{targetname}", GetMsg("Player: Unknown", player)); } send = send.Replace("{targetstatus}", status); List <string> sourceItems = new List <string>(); foreach (Item i in sourceContainer.inventory.itemList) { string n = ""; if (i.IsBlueprint()) { n = i.amount + " x <color=lightblue>" + i.blueprintTargetDef.displayName.english + " [" + GetMsg("Item: BP", player) + "]</color>"; } else { n = i.amount + " x " + i.info.displayName.english; } sourceItems.Add(n); } send = send.Replace("{sourceitems}", string.Join("\n", sourceItems.ToArray())); if (player != target) { List <string> targetItems = new List <string>(); if (targetContainer != null) { foreach (Item i in targetContainer.inventory.itemList) { string n2 = ""; if (i.IsBlueprint()) { n2 = i.amount + " x <color=lightblue>" + i.blueprintTargetDef.displayName.english + " [" + GetMsg("Item: BP", player) + "]</color>"; } else { n2 = i.amount + " x " + i.info.displayName.english; } targetItems.Add(n2); } } send = send.Replace("{targetitems}", string.Join("\n", targetItems.ToArray())); } else { send = send.Replace("{targetitems}", ""); } var obj2 = new Facepunch.ObjectList(send); CommunityEntity.ServerInstance.ClientRPCEx(new Network.SendInfo { connection = player.net.connection }, null, "AddUI", obj2); }
private Item CreateComplexItem(ItemID itemId, Material material, Vector3 position) { Item newItem; List<Item> components; if (itemId == ItemID.Bag || itemId == ItemID.Barrel || itemId == ItemID.Crate || itemId == ItemID.Wheelbarrow) { components = CreateComponents(itemId, material, position); newItem = new StorageContainer(position, itemId.ToString(), components) {CrafterHistory = creator.History}; } else { components = CreateComponents(itemId, material, position); if (components.Any()) { newItem = new Item(position, itemId.ToString(), components) { CrafterHistory = creator.History }; } else { newItem = new Item(position, itemId.ToString(), material.ToString()); } } GnomanEmpire.Instance.EntityManager.SpawnEntityImmediate(newItem); GnomanEmpire.Instance.Fortress.AddItem(newItem); RemoveComponents(components); return newItem; }
private void GetStorageBoxCode(BasePlayer player, StorageContainer box) { if (box.HasSlot(BaseEntity.Slot.Lock)) { BaseLock thelock = box.GetSlot(BaseEntity.Slot.Lock) as BaseLock; if (thelock as CodeLock) { List<ulong> whitelisted = codelockwhitelist.GetValue(thelock as CodeLock) as List<ulong>; SendReply(player, codeLockList); if (whitelisted.Count == 0) { SendReply(player, noCodeAccess); return; } foreach (ulong userid in whitelisted) { SendBasePlayerFind(player, userid); } return; } } SendReply(player, boxNeedsCode); }
/// <summary> /// Special case version of ProcessStorage folder to deal with the root ASP.NET /// folder exclusions like web.config, \bin, \app_code, etc. /// </summary> /// <param name="path">The current physical path to load</param> /// <param name="container">The StorageContainer to be loaded</param> void ProcessRootStorageFolderSpecial(string path, StorageContainer container, WorkerProgressHandler progress) { byte[] buffer = new byte[8192]; // Local file buffer array int read; // Bytes read from the file string nameOnly; // File name only portion of the path Invoke(progress, new object[] { "Processing folder " + path }); // Add all of the files into the StorageContainer by creating new // StorageObjects for each of them and copying the data 8KB at a time foreach (string filename in Directory.GetFiles(path)) { nameOnly = Path.GetFileName(filename); // Get the file name // SPECIAL CASE FILES if (nameOnly.StartsWith("global.asax", StringComparison.OrdinalIgnoreCase)) continue; if (nameOnly.Equals("web.config", StringComparison.OrdinalIgnoreCase)) continue; if ((Path.GetExtension(nameOnly) == ".xml") && (IsFileSiteMapXml(filename))) continue; StorageObject obj = container.Objects.Add(Path.GetFileName(nameOnly)); using (FileStream reader = File.OpenRead(filename)) { using (StorageObjectStream writer = obj.GetWriter()) { do { read = reader.Read(buffer, 0, 8192); if (read > 0) writer.Write(buffer, 0, read); } while (read > 0); } } } // Now recursively create all of the subdirectories and process them foreach (string folder in Directory.GetDirectories(path)) { nameOnly = Path.GetFileName(folder); // Get the folder name // SPECIAL CASE FOLDERS if (nameOnly.Equals("bin", StringComparison.OrdinalIgnoreCase)) continue; if (nameOnly.Equals("app_code", StringComparison.OrdinalIgnoreCase)) continue; if (nameOnly.Equals("app_data", StringComparison.OrdinalIgnoreCase)) continue; if (nameOnly.Equals("app_globalresources", StringComparison.OrdinalIgnoreCase)) continue; if (nameOnly.Equals("app_localresources", StringComparison.OrdinalIgnoreCase)) continue; StorageContainer cont = container.Containers.Add(Path.GetFileName(nameOnly)); ProcessStorageFolder(folder, cont, progress); } }