public Optional <GameObject> Spawn(Entity entity, Optional <GameObject> parent)
        {
            TechType       techType = entity.TechType.Enum();
            GameObject     prefab;
            IPrefabRequest prefabRequest = PrefabDatabase.GetPrefabAsync(entity.ClassId);

            if (!prefabRequest.TryGetPrefab(out prefab)) // I realize its more code but Sorry couldnt stand all the warnings
            {
                prefab = CraftData.GetPrefabForTechType(techType, false);
                if (prefab == null)
                {
                    return(Optional <GameObject> .Of(Utils.CreateGenericLoot(techType)));
                }
            }

            GameObject gameObject = Utils.SpawnFromPrefab(prefab, null);

            gameObject.transform.position   = entity.Position;
            gameObject.transform.localScale = entity.Scale;

            if (parent.IsPresent())
            {
                gameObject.transform.SetParent(parent.Get().transform, true);
            }

            gameObject.transform.localRotation = entity.Rotation;
            gameObject.SetActive(true);

            NitroxIdentifier.SetNewId(gameObject, entity.Id);
            LargeWorldEntity.Register(gameObject);
            CrafterLogic.NotifyCraftEnd(gameObject, techType);

            return(Optional <GameObject> .Of(gameObject));
        }
Beispiel #2
0
        public void ConstructionComplete(GameObject ghost)
        {
            NitroxId          baseId            = null;
            Optional <object> opConstructedBase = TransientLocalObjectManager.Get(TransientObjectType.BASE_GHOST_NEWLY_CONSTRUCTED_BASE_GAMEOBJECT);

            NitroxId id = NitroxIdentifier.GetId(ghost);

            if (opConstructedBase.IsPresent())
            {
                GameObject constructedBase = (GameObject)opConstructedBase.Get();
                baseId = NitroxIdentifier.GetId(constructedBase);
            }

            // For base pieces, we must switch the id from the ghost to the newly constructed piece.
            // Furniture just uses the same game object as the ghost for the final product.
            if (ghost.GetComponent <ConstructableBase>() != null)
            {
                Optional <object> opBasePiece   = TransientLocalObjectManager.Get(TransientObjectType.LATEST_CONSTRUCTED_BASE_PIECE);
                GameObject        finishedPiece = (GameObject)opBasePiece.Get();

                UnityEngine.Object.Destroy(ghost);
                NitroxIdentifier.SetNewId(finishedPiece, id);

                if (baseId == null)
                {
                    baseId = NitroxIdentifier.GetId(finishedPiece.GetComponentInParent <Base>().gameObject);
                }
            }

            ConstructionCompleted constructionCompleted = new ConstructionCompleted(id, baseId);

            packetSender.Send(constructionCompleted);
        }
Beispiel #3
0
        /**
         * Wait for some time so the CrashHome can load and spawn the Crash fish.
         * If we try to manually spawn the crash fish (and assign to the CrashHome) it will be at
         * the wrong orientation.  Maybe someone can figure out why this happens to we can create
         * it without leveraging this hack.
         */
        private IEnumerator WaitToAssignId(NitroxId id, CrashHome crashHome)
        {
            yield return(new WaitForSeconds(0.25f));

            GameObject crash = ((Crash)crashHome.ReflectionGet("crash")).gameObject;

            NitroxIdentifier.SetNewId(crash, id);
        }
        public override void Process(StorageSlotItemAdd packet)
        {
            ItemData   itemData = packet.ItemData;
            GameObject item     = SerializationHelper.GetGameObject(itemData.SerializedData);

            NitroxIdentifier.SetNewId(item, itemData.ItemId);

            storageSlots.AddItem(item, itemData.ContainerId);
        }
 public override void Process(InitialPlayerSync packet)
 {
     using (packetSender.Suppress <StorageSlotItemAdd>())
     {
         foreach (ItemData itemData in packet.StorageSlots)
         {
             GameObject item = SerializationHelper.GetGameObject(itemData.SerializedData);
             NitroxIdentifier.SetNewId(item, itemData.ItemId);
             slots.AddItem(item, itemData.ContainerId, true);
         }
     }
 }
        /**
         * On base pieces we need to have special logic during deconstruction to transfer the id from the main
         * object to the ghost.  This method will see if we have a stored LATEST_DECONSTRUCTED_BASE_PIECE_GUID
         * (set from deconstructor patch).  If we do, then we'll copy the id to the new ghost.  This is in
         * amount changed as we don't currently have a good hook for 'startDeconstruction'; this method will
         * run its logic on the first amount changed instead - effectively the same thing.
         */
        public static void CheckToCopyIdToGhost(Constructable __instance)
        {
            Optional <object> opId = TransientLocalObjectManager.Get(TransientObjectType.LATEST_DECONSTRUCTED_BASE_PIECE_GUID);

            if (opId.IsPresent())
            {
                TransientLocalObjectManager.Add(TransientObjectType.LATEST_DECONSTRUCTED_BASE_PIECE_GUID, null);

                NitroxId id = (NitroxId)opId.Get();
                Log.Info("Setting ghost id " + id);
                NitroxIdentifier.SetNewId(__instance.gameObject, id);
            }
        }
Beispiel #7
0
        /**
         * This function is called directly after the game clears all base pieces (to update
         * the view model - this is done in Base.ClearGeometry, see that patch).  The game will
         * respawn each object and we need to copy over their ids.  We reference the dictionary
         * in the ClearGemometry patch so know what ids to update.
         */
        public static void Postfix(Base __instance, Transform __result)
        {
            if (__instance == null || __result == null)
            {
                return;
            }

            NitroxId id;

            string key = Base_ClearGeometry_Patch.getObjectKey(__result.name, __result.position);

            if (Base_ClearGeometry_Patch.NitroxIdByObjectKey.TryGetValue(key, out id))
            {
                NitroxIdentifier.SetNewId(__result.gameObject, id);
            }
        }
        public static void SetInteractiveChildrenIds(GameObject constructedObject, List <InteractiveChildObjectIdentifier> interactiveChildIdentifiers)
        {
            foreach (InteractiveChildObjectIdentifier childIdentifier in interactiveChildIdentifiers)
            {
                Transform transform = constructedObject.transform.Find(childIdentifier.GameObjectNamePath);

                if (transform != null)
                {
                    GameObject gameObject = transform.gameObject;
                    NitroxIdentifier.SetNewId(gameObject, childIdentifier.Id);
                }
                else
                {
                    Log.Error("Error GUID tagging interactive child due to not finding it: " + childIdentifier.GameObjectNamePath);
                }
            }
        }
Beispiel #9
0
        public override void Process(InitialPlayerSync packet)
        {
            using (packetSender.Suppress <ItemContainerAdd>())
            {
                foreach (EquippedItemData equippedItem in packet.EquippedItems)
                {
                    GameObject gameObject = SerializationHelper.GetGameObject(equippedItem.SerializedData);
                    NitroxIdentifier.SetNewId(gameObject, equippedItem.ItemId);

                    Pickupable            pickupable   = gameObject.RequireComponent <Pickupable>();
                    Optional <GameObject> opGameObject = NitroxIdentifier.GetObjectFrom(equippedItem.ContainerId);

                    if (opGameObject.IsPresent())
                    {
                        GameObject owner = opGameObject.Get();

                        Optional <Equipment> opEquipment = EquipmentHelper.GetBasedOnOwnersType(owner);

                        if (opEquipment.IsPresent())
                        {
                            Equipment     equipment     = opEquipment.Get();
                            InventoryItem inventoryItem = new InventoryItem(pickupable);
                            inventoryItem.container = equipment;
                            inventoryItem.item.Reparent(equipment.tr);

                            Dictionary <string, InventoryItem> itemsBySlot = (Dictionary <string, InventoryItem>)equipment.ReflectionGet("equipment");
                            itemsBySlot[equippedItem.Slot] = inventoryItem;

                            equipment.ReflectionCall("UpdateCount", false, false, new object[] { pickupable.GetTechType(), true });
                            Equipment.SendEquipmentEvent(pickupable, 0, owner, equippedItem.Slot);
                            equipment.ReflectionCall("NotifyEquip", false, false, new object[] { equippedItem.Slot, inventoryItem });
                        }
                        else
                        {
                            Log.Info("Could not find equipment type for " + gameObject.name);
                        }
                    }
                    else
                    {
                        Log.Info("Could not find Container for " + gameObject.name);
                    }
                }
            }
        }
Beispiel #10
0
        public GameObject CreateNewEscapePod(EscapePodModel model)
        {
            SURPRESS_ESCAPE_POD_AWAKE_METHOD = true;

            GameObject escapePod;

            if (model.Id == MyEscapePodId)
            {
                escapePod = EscapePod.main.gameObject;
            }
            else
            {
                escapePod = Object.Instantiate(EscapePod.main.gameObject);
            }

            escapePod.transform.position = model.Location;


            StorageContainer storageContainer = escapePod.RequireComponentInChildren <StorageContainer>();

            using (packetSender.Suppress <ItemContainerRemove>())
            {
                storageContainer.container.Clear();
            }

            NitroxIdentifier.SetNewId(storageContainer.gameObject, model.StorageContainerId);

            MedicalCabinet medicalCabinet = escapePod.RequireComponentInChildren <MedicalCabinet>();

            NitroxIdentifier.SetNewId(medicalCabinet.gameObject, model.MedicalFabricatorId);

            Fabricator fabricator = escapePod.RequireComponentInChildren <Fabricator>();

            NitroxIdentifier.SetNewId(fabricator.gameObject, model.FabricatorId);

            Radio radio = escapePod.RequireComponentInChildren <Radio>();

            NitroxIdentifier.SetNewId(radio.gameObject, model.RadioId);

            DamageEscapePod(model.Damaged, model.RadioDamaged);

            return(escapePod);
        }
Beispiel #11
0
        public Optional <GameObject> Spawn(Entity entity, Optional <GameObject> parent)
        {
            GameObject gameObject = SerializationHelper.GetGameObject(entity.SerializedGameObject);

            gameObject.transform.position   = entity.Position;
            gameObject.transform.rotation   = entity.Rotation;
            gameObject.transform.localScale = entity.Scale;

            if (entity.WaterParkId != null)
            {
                AssignToWaterPark(gameObject, entity.WaterParkId);
            }

            EnableRigidBody(gameObject);
            ExecuteDropItemAction(entity.TechType.Enum(), gameObject);

            NitroxIdentifier.SetNewId(gameObject, entity.Id);

            return(Optional <GameObject> .Of(gameObject));
        }
Beispiel #12
0
        public void SpawnedArm(Exosuit exosuit)
        {
            NitroxId     id           = NitroxIdentifier.GetId(exosuit.gameObject);
            ExosuitModel exosuitModel = vehicles.GetVehicles <ExosuitModel>(id);

            IExosuitArm rightArm = (IExosuitArm)exosuit.ReflectionGet("rightArm");
            IExosuitArm leftArm  = (IExosuitArm)exosuit.ReflectionGet("leftArm");

            try
            {
                GameObject rightArmGameObject = rightArm.GetGameObject();
                NitroxIdentifier.SetNewId(rightArmGameObject, exosuitModel.RightArmId);

                GameObject leftArmGameObject = leftArm.GetGameObject();
                NitroxIdentifier.SetNewId(leftArmGameObject, exosuitModel.LeftArmId);
            }
            catch (Exception e)
            {
                Log.Warn("Got error setting arm GameObjects. This is probably due to docking sync and can be ignored\nErromessage: " + e.Message + "\n" + e.StackTrace);
            }

            Log.Debug("Spawn exosuit arms for: " + id);
        }
Beispiel #13
0
        public override void Process(ConstructorBeginCrafting packet)
        {
            GameObject gameObject = NitroxIdentifier.RequireObjectFrom(packet.ConstructorId);
            Crafter    crafter    = gameObject.RequireComponentInChildren <Crafter>(true);

            vehicles.AddVehicle(VehicleModelFactory.BuildFrom(packet));
            MethodInfo onCraftingBegin = typeof(Crafter).GetMethod("OnCraftingBegin", BindingFlags.NonPublic | BindingFlags.Instance);

            Validate.NotNull(onCraftingBegin);
            onCraftingBegin.Invoke(crafter, new object[] { packet.TechType.Enum(), packet.Duration }); //TODO: take into account latency for duration

            Optional <object> opConstructedObject = TransientLocalObjectManager.Get(TransientObjectType.CONSTRUCTOR_INPUT_CRAFTED_GAMEOBJECT);

            if (opConstructedObject.IsPresent())
            {
                GameObject constructedObject = (GameObject)opConstructedObject.Get();
                NitroxIdentifier.SetNewId(constructedObject, packet.ConstructedItemId);
                VehicleChildObjectIdentifierHelper.SetInteractiveChildrenIds(constructedObject, packet.InteractiveChildIdentifiers);
            }
            else
            {
                Log.Error("Could not find constructed object!");
            }
        }
Beispiel #14
0
        private void OnVehiclePrefabLoaded(TechType techType, GameObject prefab, NitroxId id, Vector3 spawnPosition, Quaternion spawnRotation, Optional<List<InteractiveChildObjectIdentifier>> interactiveChildIdentifiers, Optional<NitroxId> dockingBayId, string name, Vector3[] hsb, Vector3[] colours)
        {
            // Partially copied from SubConsoleCommand.OnSubPrefabLoaded
            GameObject gameObject = Utils.SpawnPrefabAt(prefab, null, spawnPosition);
            gameObject.transform.rotation = spawnRotation;
            gameObject.SetActive(true);
            gameObject.SendMessage("StartConstruction", SendMessageOptions.DontRequireReceiver);
            CrafterLogic.NotifyCraftEnd(gameObject, CraftData.GetTechType(gameObject));
            Rigidbody rigidBody = gameObject.GetComponent<Rigidbody>();
            rigidBody.isKinematic = false;
            NitroxIdentifier.SetNewId(gameObject, id);
            // Updates names and colours with persisted data
            if (techType == TechType.Seamoth || techType == TechType.Exosuit)
            {
                Vehicle vehicle = gameObject.GetComponent<Vehicle>();
                if (dockingBayId.IsPresent())
                {
                    GameObject dockingBayBase = NitroxIdentifier.RequireObjectFrom(dockingBayId.Get());
                    VehicleDockingBay dockingBay = dockingBayBase.GetComponentInChildren<VehicleDockingBay>();
                    dockingBay.DockVehicle(vehicle);
                } else if(techType == TechType.Exosuit)
                {
                    // exosuits tend to fall through the ground after spawning. This should prevent that
                    vehicle.ReflectionSet("onGround", true);
                }

                if (!string.IsNullOrEmpty(name))
                {
                    vehicle.vehicleName = name;
                    vehicle.subName.DeserializeName(vehicle.vehicleName);
                }

                if (colours != null)
                {
                    Vector3[] colour = new Vector3[5];

                    for (int i = 0; i < hsb.Length; i++)
                    {
                        colour[i] = hsb[i];
                    }
                    vehicle.vehicleColors = colour;
                    vehicle.subName.DeserializeColors(vehicle.vehicleColors);
                }
            }
            else if(techType == TechType.Cyclops)
            {
                GameObject target = NitroxIdentifier.RequireObjectFrom(id);
                SubNameInput subNameInput = target.RequireComponentInChildren<SubNameInput>();
                SubName subNameTarget = (SubName)subNameInput.ReflectionGet("target");
                subNameInput.OnNameChange(name);
                for (int i = 0; i < hsb.Length; i++)
                {
                    subNameInput.SetSelected(i);
                    Color tmpColour = new Vector4(colours[i].x, colours[i].y, colours[i].z);
                    subNameTarget.SetColor(i, hsb[i], tmpColour);
                    subNameTarget.DeserializeColors(hsb);
                }

                // Set internal and external lights
                SetCyclopsModes(id);
            }
            if (interactiveChildIdentifiers.IsPresent())
            {
                VehicleChildObjectIdentifierHelper.SetInteractiveChildrenIds(gameObject, interactiveChildIdentifiers.Get()); //Copy From ConstructorBeginCraftingProcessor
            }            

            // Send event after everthing is created            
            if (VehicleCreated != null)
            {
                VehicleCreated(gameObject);
            }
        }
Beispiel #15
0
 private void SetPlayerGameObjectId(NitroxId id)
 {
     NitroxIdentifier.SetNewId(Player.mainObject, id);
     Log.Info("Received initial sync Player GameObject Id: " + id);
 }
Beispiel #16
0
        /// <summary>
        /// Create a new <see cref="Fire"/>. Majority of code copied from <see cref="SubFire.CreateFire(SubFire.RoomFire)"/>. Currently does not support Fires created outside of a Cyclops
        /// </summary>
        /// <param name="fireGuid">Id of the Fire. Used for identification when dousing the fire</param>
        /// <param name="subRootGuid">Id of the Cyclops <see cref="SubRoot"/></param>
        /// <param name="room">The room the Fire will be spawned in</param>
        /// <param name="spawnNodeIndex">Each <see cref="CyclopsRooms"/> has multiple static Fire spawn points called spawnNodes. If the wrong index is provided,
        ///     the clients will see fires in different places from the owner</param>
        public void Create(CyclopsFireData fireData)
        {
            SubFire subFire = NitroxIdentifier.RequireObjectFrom(fireData.CyclopsId).GetComponent <SubRoot>().damageManager.subFire;
            Dictionary <CyclopsRooms, SubFire.RoomFire> roomFiresDict = (Dictionary <CyclopsRooms, SubFire.RoomFire>)subFire.ReflectionGet("roomFires");
            // Copied from SubFire_CreateFire_Patch, which copies from SubFire.CreateFire()
            Transform transform2 = roomFiresDict[fireData.Room].spawnNodes[fireData.NodeIndex];

            // If a fire already exists at the node, replace the old Id with the new one
            if (transform2.childCount > 0)
            {
                Fire existingFire = transform2.GetComponentInChildren <Fire>();

                if (NitroxIdentifier.GetId(existingFire.gameObject) != fireData.CyclopsId)
                {
                    Log.Error("[Fires.Create Fire already exists at node index " + fireData.NodeIndex
                              + "! Replacing existing Fire Id " + NitroxIdentifier.GetId(existingFire.gameObject)
                              + " with Id " + fireData.CyclopsId
                              + "]");

                    NitroxIdentifier.SetNewId(existingFire.gameObject, fireData.CyclopsId);
                }

                return;
            }

            List <Transform> availableNodes = (List <Transform>)subFire.ReflectionGet("availableNodes");

            availableNodes.Clear();
            foreach (Transform transform in roomFiresDict[fireData.Room].spawnNodes)
            {
                if (transform.childCount == 0)
                {
                    availableNodes.Add(transform);
                }
            }
            roomFiresDict[fireData.Room].fireValue++;
            PrefabSpawn component = transform2.GetComponent <PrefabSpawn>();

            if (component == null)
            {
                return;
            }
            else
            {
                Log.Error("[FireCreatedProcessor Cannot create new Cyclops fire! PrefabSpawn component could not be found in fire node!"
                          + " Fire Id: " + fireData.FireId
                          + " SubRoot Id: " + fireData.CyclopsId
                          + " Room: " + fireData.Room
                          + " NodeIndex: " + fireData.NodeIndex
                          + "]");
            }
            GameObject gameObject          = component.SpawnManual();
            Fire       componentInChildren = gameObject.GetComponentInChildren <Fire>();

            if (componentInChildren)
            {
                componentInChildren.fireSubRoot = subFire.subRoot;
                NitroxIdentifier.SetNewId(componentInChildren.gameObject, fireData.FireId);
            }

            subFire.ReflectionSet("roomFires", roomFiresDict);
            subFire.ReflectionSet("availableNodes", availableNodes);
        }