Exemple #1
0
    // Special wrapper method for the generic Monobehaviour#Destroy
    // Manages saving the destruction state of a RO
    public static void Destroy(GameObject go)
    {
        RegisteredObject ro = go.GetComponent <RegisteredObject> ();

        if (ro != null)
        {
            ro.SaveDestruction();
        }
        UnityEngine.Object.Destroy(go);
    }
Exemple #2
0
 public void OnEnable()
 {
     ro = (RegisteredObject)target;
     try
     {
         so = new SerializedObject(ro);
     }
             #pragma warning disable 0168
     catch (System.NullReferenceException nre) { }
             #pragma warning restore 0168
 }
Exemple #3
0
    public void OnTriggerEnter2D(Collider2D col)
    {
        Player p = col.GetComponent <Player> ();

        if (p != null)
        {
            Apply(p.Data);
            //TODO play pickup sound?
            RegisteredObject.Destroy(gameObject);
        }
    }
Exemple #4
0
        private object GetInstance(RegisteredObject registeredObject)
        {
            object instance = registeredObject.SingletonInstance;

            if (instance == null)
            {
                var parameters = ResolveConstructorParameters(registeredObject);
                instance = registeredObject.CreateInstance(parameters.ToArray());
            }
            return(instance);
        }
 public void spawnRegisteredPrefabs(int amount)
 {
     for (int i = 0; i < amount; i++)
     {
         RegisteredObject.Create(
             "core/prefabs/entities",
             "TestEntityPrefab",
             (Vector3)Random.insideUnitCircle,
             Quaternion.identity);
     }
 }
Exemple #6
0
 /// <summary>
 /// Tries to add an object to the creation queue, retuning true if it was added
 /// or false if the queue was full.
 /// </summary>
 public bool tryAddToQueue(RegisteredObject obj)
 {
     if (!this.isQueueFull())
     {
         this.trainingQueue.Add(obj);
         return(true);
     }
     else
     {
         return(false);
     }
 }
Exemple #7
0
 /// <summary>
 /// Tries to add an object to the creation queue, retuning true if it was added
 /// or false if the queue was full.
 /// </summary>
 public bool tryAddToQueue(RegisteredObject obj)
 {
     if (this.trainingQueue.Count < this.getQueueSize())
     {
         this.trainingQueue.Add(obj);
         return(true);
     }
     else
     {
         return(false);
     }
 }
Exemple #8
0
        public ActionButtonBuild(string actionName, RegisteredObject obj) : base(actionName)
        {
            this.setMainActionFunction((unit) => {
                BuildOutline.instance().enableOutline(obj, (UnitBuilder)unit);
            });
            this.buildingData = obj.getPrefab().GetComponent <BuildingBase>().getData();
            this.buttonText   = this.buildingData.getName() + " (" + this.buildingData.getCost() + ")";

            this.setShouldDisableFunction((entity) => {
                int cost = this.buildingData.getCost();
                return(cost > entity.getTeam().getResources());
            });
        }
        private object GetInstance(RegisteredObject registeredObject)
        {
            if (registeredObject.Instance != null && !registeredObject.IsTransient)
            {
                return(registeredObject.Instance);
            }

            var parameters = this.ResolveConstructorParameters(registeredObject);
            var instance   = Activator.CreateInstance(registeredObject.ConcreteType, parameters.ToArray());

            registeredObject.Instance = instance;
            return(instance);
        }
Exemple #10
0
    private RegisteredObject register(int id, GameObject prefab)
    {
        RegisteredObject registerObject = new RegisteredObject(id, prefab);

        int i = registerObject.getId();

        if (Registry.objectRegistry[i] != null)
        {
            throw new Exception("Two objects were registered with the same ID!");
        }
        Registry.objectRegistry[i] = registerObject;
        return(registerObject);
    }
Exemple #11
0
        /// <summary>
        /// Called to enable the outline effect.
        /// </summary>
        public void enableOutline(RegisteredObject registeredBuilding, UnitBuilder builder)
        {
            // Note, this could be called multiple times if multiple builders are in the same party.
            this.gameObject.SetActive(true);

            this.buildingToPlace = registeredBuilding;
            this.cachedBuilders.Add(builder);

            this.setSize(this.buildingToPlace.getPrefab().GetComponent <BuildingBase>());

            // Gray out the action buttons while the outline is being shown.
            CameraMover.instance().actionButtons.setForceDisabled(true);
        }
Exemple #12
0
        /// <summary>
        /// Expected behavior: before the first Console.ReadLine returns,
        /// the timer is continuously invoked every second.
        /// After the first Console.ReadLine returns, the timer is no
        /// longer invoked (because its "target" is garbage collected).
        /// </summary>
        static void Main(string[] args)
        {
            RegisteredObject registeredObject = new RegisteredObject();
            WeakTimer timer = new WeakTimer(1000, registeredObject);

            GC.Collect();
            Console.ReadLine();

            GC.KeepAlive(registeredObject);

            GC.Collect();
            Console.ReadLine();
        }
Exemple #13
0
    // This Entity has died
    public void OnDeath()
    {
        foreach (Status s in statuses.Values)
        {
            s.OnDeath(this);
        }

        if (died != null)
        {
            died();
        }

        RegisteredObject.Destroy(gameObject);
    }
Exemple #14
0
        /// <summary>
        /// Spawns a MapObject into the World, loading it's state from NBT, then returns it object.
        /// </summary>
        public MapObject spawnEntity(RegisteredObject obj, NbtCompound tag)
        {
            MapObject mapObject = GameObject.Instantiate(obj.getPrefab()).GetComponent <MapObject>();

            #if UNITY_EDITOR
            mapObject.name += mapObject.getPos().ToString();
            #endif
            mapObject.readFromNbt(tag);

            this.addToList(mapObject);
            this.placeInWrapper(mapObject);

            return(mapObject);
        }
Exemple #15
0
        /// <summary>
        /// Resolve constructor parameters for the Implementation type <see cref="RegisteredObject"/>
        /// </summary>
        /// <param name="registeredObject"><see cref="RegisteredObject"/></param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException">If the <see cref="RegisteredObject.ConcreteType"/> does not have a public constructor</exception>
        private IEnumerable <object> ResolveConstructorParameters(RegisteredObject registeredObject)
        {
            var constructorInfo = registeredObject.Implementation.GetConstructors().FirstOrDefault();

            if (constructorInfo == null)
            {
                throw new InvalidOperationException($"A public constructor not found for {registeredObject.Implementation.FullName}");
            }

            foreach (var parameter in constructorInfo.GetParameters())
            {
                yield return(ResolveType(parameter.ParameterType));
            }
        }
Exemple #16
0
    /*
     * Time Tether
     */

    // Internal State Methods
    bool addState()
    {
        if (m_curState + 1 > maxNumStates)
        {
            return(false);
        }

        // Create a new Dictionary to save at the current state
        // Actually, maybe don't do this because store() might need to use the next dictionary
        //stateSeeds[m_curState] = new Dictionary<string, SeedBase> ();

        // Increment the current state
        m_curState++;

        // Check if a Dictionary doesn't exist because the count of stateSeeds is too low/zero
        if (m_curState + 1 > stateSeeds.Count)
        {
            Debug.LogError("Trying to access an out-of-bounds state in stateSeeds. stateSeeds.count = " + stateSeeds.Count + "; m_curState = " + m_curState);
            //stateSeeds.Add(new Dictionary<string, SeedBase> ());
            return(false);
        }

        // Check if the Dictionary position of curState is null, and instantiate a new dictionary if so
        if (stateSeeds[m_curState] == null)
        {
            Debug.LogError("Trying to access a null Dictionary in stateSeeds");
            //stateSeeds[m_curState] = new Dictionary<string, SeedBase> ();
            return(false);
        }

        //add each RO's data to the dictionary
        foreach (RegisteredObject ro in RegisteredObject.getObjects())
        {
            //Debug.Log("RegisteredObject name: " + ro.gameObject.name + "; ID: " + ro.rID);

            stateSeeds[m_curState].Remove(ro.rID);
            stateSeeds[m_curState].Add(ro.rID, ro.reap());
        }

        // Tell ScreenshotManager to take a screenshot
        ScreenshotManager.createScreenshot(m_curState);

        if (stateAdded != null)
        {
            stateAdded(true);
        }

        return(true);
    }
Exemple #17
0
    public ActionButtonBuild(string actionName, RegisteredObject obj) : base(actionName)
    {
        this.setMainActionFunction((unit) => {
            Player.localPlayer.enableBuildOutline(obj, (UnitBuilder)unit);
        });
        this.setExecuteOnClientSide();

        this.buildingData = obj.getPrefab().GetComponent <BuildingBase>().getData();
        this.buttonText   = this.buildingData.getName() + " (" + this.buildingData.getCost() + ")";

        this.setShouldDisableFunction((entity) => {
            int cost = this.buildingData.getCost();
            return(cost > Player.localPlayer.currentTeamResources);
        });
    }
        private object ResolveConstructor(RegisteredObject resolvingType)
        {
            object result = null;

            foreach (var constructor in resolvingType.ConcreteType.GetConstructors().OrderBy(c => c.GetParameters().Count()))
            {
                var constructorParams = constructor.GetParameters();
                if (!constructorParams.Select(p => p.ParameterType).Except(_registeredTypes.Keys).Any())
                {
                    var paramInfos = constructorParams.Select(c => Resolve(c.ParameterType)).ToArray();
                    result = resolvingType.CreateInstance(paramInfos);
                }
            }
            return(result);
        }
Exemple #19
0
 public static void readList(NbtCompound rootTag, string tagName, Map map)
 {
     foreach (NbtCompound compound in rootTag.getList(tagName))
     {
         int id = compound.getInt("id");
         RegisteredObject registeredObject = Registry.getObjectFromRegistry(id);
         if (registeredObject != null)
         {
             map.spawnEntity(registeredObject, compound);
         }
         else
         {
             Debug.Log("Error!  MapObject with an unknown ID of " + id + " was found!  Ignoring!");
         }
     }
 }
Exemple #20
0
    public SpawnInstructions <T> spawnEntity <T>(RegisteredObject registeredObj, Vector3 position, Quaternion?rotation = null, Vector3?scale = null) where T : MapObject
    {
        if (rotation == null)
        {
            rotation = Quaternion.identity;
        }
        GameObject gameObj = GameObject.Instantiate(registeredObj.getPrefab(), position, (Quaternion)rotation);

        if (scale != null)
        {
            gameObj.transform.localScale = (Vector3)scale;
        }
        T newObject = setupMapObj <T>(gameObj);

        return(new SpawnInstructions <T>(newObject));
    }
    // Load saved data into ROs in the new scene
    private void ActiveSceneTransitioned(Scene prev, Scene curr)
    {
        GameManager.instance.currentScene = curr.name;

        //create a player object from saved data
        if (curr.name != "main")         //TODO see if there's a better way to do this
        {
            GameManager.instance.createPlayer();
        }

        Console.println("[SSM] Loading values for \"" + curr.name + "\"", Console.Tag.info, Console.nameToChannel("SSM"));

        Dictionary <string, SeedCollection> currData;

        //if no data is saved, exit the method
        if (!scenes.TryGetValue(curr.name, out currData))
        {
            Console.println("[SSM] No data to load for \"" + curr.name + "\"", Console.Tag.info, Console.nameToChannel("SSM"));
            return;
        }

        //spawn prefabs before starting sow cycle
        foreach (SeedCollection sb in currData.Values)
        {
            if (sb.prefabPath != "")
            {
                if (RegisteredObject.Recreate(sb.prefabPath, sb.prefabName, sb.registeredID, sb.parentID) != null)
                {
                    Console.println("[SSM] Respawned prefab object: \"" + sb.registeredID + "\"", Console.Tag.info, Console.nameToChannel("SSM"));
                }
                else
                {
                    Console.println("[SSM] Failed to respawn prefab object: \"" + sb.registeredID + "\"", Console.Tag.error, Console.nameToChannel("SSM"));
                }
            }
        }

        //iterate over the list of ROs and pass them data
        foreach (RegisteredObject ro in RegisteredObject.GetObjects())
        {
            SeedCollection data;
            if (currData.TryGetValue(ro.RID, out data))
            {
                ro.Sow(data);
            }
        }
    }
Exemple #22
0
        public void Register <T, TU>() where TU : T
        {
            var typeToResolve = typeof(T);

            if (_configItems.ContainsKey(typeToResolve))
            {
                _configItems.Remove(typeToResolve);
            }

            var configItem = new RegisteredObject
            {
                TypeToResolve = typeToResolve,
                ConcreteType  = typeof(TU)
            };

            _configItems.Add(typeof(T), configItem);
        }
Exemple #23
0
            private IEnumerable <object> ResolveConstructorParameters(RegisteredObject registeredObject)
            {
                ConstructorInfo constructorInfo = registeredObject.ConcreteType.GetConstructors().FirstOrDefault();

                if (constructorInfo == null)
                {
                    Debug.LogFormat(
                        "No constructor to resolve object of {0} found, will use the default constructor",
                        registeredObject.ConcreteType);
                    yield break;
                }

                foreach (var parameter in constructorInfo.GetParameters())
                {
                    yield return(ResolveObject(parameter.ParameterType));
                }
            }
Exemple #24
0
    // Get the reapable scripts attached to this GO and return their seeds
    public SeedCollection Reap()
    {
        IReapable[] blades = GetComponents <IReapable> ();
        if (blades.Length <= 0)
        {
            Console.println(ToString() + " has no additional values to reap", Console.Tag.info);
        }
        else
        {
            Console.println(ToString() + " reaped values.", Console.Tag.info);
        }

        SeedCollection collection = new SeedCollection(gameObject, blades);

        collection.ignoreReset = ignoreReset;

        //pass in a prefabPath so that if this RO is a prefab, it can be spawned again later
        collection.prefabPath = prefabPath;
        collection.prefabName = prefabName;
        if (prefabPath != "" && prefabName != "")
        {
            collection.registeredID = registeredID;
        }

        //pass in this RO's parent object, ifex
        Transform parent = gameObject.transform.parent;

        if (parent != null)
        {
            RegisteredObject parentRO = parent.GetComponent <RegisteredObject> ();
            if (parentRO != null)
            {
                collection.parentID = parentRO.registeredID;
            }
            else
            {
                Console.println(ToString() + " is under a non-RO. Make its parent an RO to save its data properly.", Console.Tag.error);
            }
        }
        else
        {
            collection.parentID = "";
        }

        return(collection);
    }
        public ActionButtonTrain(RegisteredObject obj) : base(string.Empty)
        {
            this.entityData = obj.getPrefab().GetComponent <UnitBase>().getData();
            this.buttonText = this.entityData.getUnitTypeName() + " (" + this.entityData.cost + ")";

            this.setMainActionFunction((unit) => {
                BuildingTrainingHouse trainingHouse = (BuildingTrainingHouse)unit;
                if (trainingHouse.tryAddToQueue(obj))
                {
                    // Remove resources
                    trainingHouse.getTeam().reduceResources(this.entityData.cost);
                }
            });

            this.setShouldDisableFunction((entity) => {
                return(this.entityData.cost > entity.getTeam().getResources());
            });
        }
Exemple #26
0
        public void Register <T>(Func <T> createInstance)
        {
            var typeToResolve = typeof(T);

            if (_configItems.ContainsKey(typeToResolve))
            {
                _configItems.Remove(typeToResolve);
            }

            var instance   = createInstance();
            var configItem = new RegisteredObject
            {
                TypeToResolve = typeToResolve,
                ConcreteType  = instance.GetType(),
                Instance      = instance
            };

            _configItems.Add(typeof(T), configItem);
        }
Exemple #27
0
    public static GameObject create(string prefabPath, Vector3 position, Quaternion rotation, Transform parent)
    {
        GameObject go = Resources.Load <GameObject> ("Prefabs/" + prefabPath);
        GameObject inst;

        if (parent == null)
        {
            inst = Instantiate(go, position, rotation);
        }
        else
        {
            inst = Instantiate(go, position, rotation, parent);
        }
        RegisteredObject ro = inst.GetComponent <RegisteredObject> ();

        ro.generateID();
        ro.prefabPath = prefabPath;
        return(inst);
    }
Exemple #28
0
    public ActionButtonTrain(RegisteredObject obj) : base(string.Empty)
    {
        this.unitData   = obj.getPrefab().GetComponent <UnitBase>().unitData;
        this.buttonText = this.unitData.unitName + " (" + 0 + ")";

        this.setMainActionFunction((unit) => {
            BuildingTrainingHouse trainingHouse = (BuildingTrainingHouse)unit;
            if (trainingHouse.tryAddToQueue(obj))
            {
                // Remove resources
                trainingHouse.map.reduceResources(trainingHouse.getTeam(), 0);
            }
        });

        this.setShouldDisableFunction((entity) => {
            BuildingTrainingHouse trainingHouse = ((BuildingTrainingHouse)entity);
            return(0 > Player.localPlayer.currentTeamResources || trainingHouse.isQueueFull());
        });
    }
Exemple #29
0
        public void Register <T>(string objectId, T obj, params Type[] nestedTypes)
        {
            // Create registered object
            var registeredObect = RegisteredObject.Create(objectId, obj);

            // Register property objects
            foreach (var property in typeof(T).GetContractProperties().Where(p => nestedTypes.Contains(p.PropertyType))
                     )
            {
                object value = property.GetValue(obj);
                if (value != null)
                {
                    var genericRegisterMethod = GetType().GetMethods().First(m => m.Name == nameof(Register) && m.GetParameters().Count() == 1);
                    genericRegisterMethod.MakeGenericMethod(property.PropertyType).Invoke(this, new object[] { value });
                }
            }

            // Store registered object
            _registeredObjects.Add(objectId, registeredObect);
        }
Exemple #30
0
        /// <summary>
        /// Resolve object hierarchy for the Implementation type of <see cref="RegisteredObject"/>
        /// </summary>
        /// <param name="regObject"><see cref="RegisteredObject"/></param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException">If the <see cref="RegisteredObject.ConcreteType"/> does not have a public constructor</exception>
        private object ResolveObject(RegisteredObject regObject)
        {
            var constructor = regObject.Implementation.GetConstructors().FirstOrDefault();

            if (constructor == null)
            {
                throw new InvalidOperationException($"A public constructor not found for {regObject.Implementation.FullName}");
            }

            var parameters = constructor.GetParameters();

            if (!parameters.Any())
            {
                return(CreateInstance(regObject.Implementation));
            }
            else
            {
                var instances = ResolveConstructorParameters(regObject);
                return(CreateInstance(regObject.Implementation, instances.ToArray()));
            }
        }
        //  sqlite migrations are not as good as sql server
        //  https://docs.microsoft.com/en-us/aspnet/core/data/ef-rp/migrations?view=aspnetcore-5.0&tabs=visual-studio

        public RegistryQueryController(ILogger <RegistryQueryController> logger, RegistryDemo.Models.SqliteDBContext context)
        {
            _logger    = logger;
            _dbContext = context;
            Console.WriteLine();
            context.Database.EnsureCreated();
            Console.WriteLine("DB has been Created - pre migrate");
            //       context.Database.Migrate();
            //       Console.WriteLine("Post migrate");
            if (context.RegisteredObjects.Any())
            {
                Console.WriteLine("context created - we have Registered Objects");
                return;
            }
            string      dbPath   = context.Database.GetConnectionString();
            string      tdPath   = "TestData.json";
            string      testData = System.IO.File.ReadAllText(tdPath, Encoding.UTF8);
            List <Maas> Ldo;

            Ldo = GetJsonGenericType <List <Maas> >(testData);
            foreach (Maas maas in Ldo)
            {
                RegisteredObject ro = new RegisteredObject
                {
                    Name           = maas.name,
                    Version        = maas.version,
                    Platform       = maas.platform,
                    Min_platform   = maas.min_platform,
                    Source         = maas.source,
                    Jurisdiction   = maas.jurisdiction,
                    User_authn     = maas.user_authn,
                    DateRegistered = maas.date,
                    Url            = maas.url,
                    Trust_registry = maas.trust_registry
                };
                context.Add(ro);
            }
            context.SaveChanges();
            Console.WriteLine("Completed Creation of base Registered Objtecs");
        }