Beispiel #1
0
        /// <summary>
        /// The view type has changed.
        /// </summary>
        /// <param name="activate">Should the current view type be activated?</param>
        /// <param name="pitch">The pitch of the camera (in degrees).</param>
        /// <param name="yaw">The yaw of the camera (in degrees).</param>
        /// <param name="characterRotation">The rotation of the character.</param>
        public override void ChangeViewType(bool activate, float pitch, float yaw, Quaternion characterRotation)
        {
            base.ChangeViewType(activate, pitch, yaw, characterRotation);

            if (activate)
            {
                // Work with the handler to listen for any input events.
                if (m_Handler != null)
                {
                    m_StartFreeMovementInputEvent = GenericObjectPool.Get <ActiveInputEvent>();
                    m_StartFreeMovementInputEvent.Initialize(ActiveInputEvent.Type.ButtonDown, m_CameraFreeMovementInputName, "OnRPGViewTypeStartFreeMovement");

                    m_StopFreeMovementInputEvent = GenericObjectPool.Get <ActiveInputEvent>();
                    m_StopFreeMovementInputEvent.Initialize(ActiveInputEvent.Type.ButtonUp, m_CameraFreeMovementInputName, "OnRPGViewTypeStopFreeMovement");

                    m_Handler.RegisterInputEvent(m_StartFreeMovementInputEvent);
                }
                EventHandler.RegisterEvent(m_GameObject, "OnRPGViewTypeStartFreeMovement", OnStartFreeMovement);
                EventHandler.RegisterEvent(m_GameObject, "OnRPGViewTypeStopFreeMovement", OnStopFreeMovement);
                EventHandler.RegisterEvent(m_Character, "OnRPGMovementTypeStartRotate", OnStartCharacterRotate);
                EventHandler.RegisterEvent(m_Character, "OnRPGMovementTypeStopRotate", OnStopCharacterRotate);
            }
            else
            {
                // The ViewType no longer needs to listen for input events when to ViewType is no longer active.
                if (m_Handler != null)
                {
                    if (m_FreeMovement)
                    {
                        m_Handler.UnregisterAbilityInputEvent(m_StopFreeMovementInputEvent);
                    }
                    else
                    {
                        m_Handler.UnregisterAbilityInputEvent(m_StartFreeMovementInputEvent);
                    }

                    GenericObjectPool.Return(m_StartFreeMovementInputEvent);
                    GenericObjectPool.Return(m_StopFreeMovementInputEvent);
                }
                EventHandler.UnregisterEvent(m_GameObject, "OnRPGViewTypeStartFreeMovement", OnStartFreeMovement);
                EventHandler.UnregisterEvent(m_GameObject, "OnRPGViewTypeStopFreeMovement", OnStopFreeMovement);
                EventHandler.UnregisterEvent(m_Character, "OnRPGMovementTypeStartRotate", OnStartCharacterRotate);
                EventHandler.UnregisterEvent(m_Character, "OnRPGMovementTypeStopRotate", OnStopCharacterRotate);
            }
        }
Beispiel #2
0
        /// <summary>
        /// The ability has started.
        /// </summary>
        protected override void AbilityStarted()
        {
            m_ApplyHoldForce = true;
            m_HoldForce      = 0;

            // If the jump has already been applied then it is a repeated jump.
            if (m_JumpApplied)
            {
                OnAirborneJump();
            }
            else
            {
                if (!m_JumpEvent.WaitForAnimationEvent || m_ForceImmediateJump)
                {
                    SchedulerBase.ScheduleFixed(m_ForceImmediateJump ? 0 : m_JumpEvent.Duration, ApplyJumpForce);
                }
            }

            if (m_ForceHold > 0)
            {
                if (m_Handler != null && InputIndex != -1)
                {
                    m_HoldInput = GenericObjectPool.Get <ActiveInputEvent>();
                    m_HoldInput.Initialize(ActiveInputEvent.Type.ButtonUp, InputNames[InputIndex], "OnJumpAbilityReleaseHold");
                    m_Handler.RegisterInputEvent(m_HoldInput);
                }
                EventHandler.RegisterEvent(m_GameObject, "OnJumpAbilityReleaseHold", OnReleaseHold);
            }

            // The character can do a repeated jump after the character is already in the air.
            if (!m_AirborneJumpRegistered)
            {
                if (m_Handler != null && InputIndex != -1)
                {
                    m_AirborneJumpInput = GenericObjectPool.Get <ActiveInputEvent>();
                    m_AirborneJumpInput.Initialize(ActiveInputEvent.Type.ButtonDown, InputNames[InputIndex], "OnJumpAbilityAirborneJump");
                    m_Handler.RegisterInputEvent(m_AirborneJumpInput);
                }
                EventHandler.RegisterEvent(m_GameObject, "OnJumpAbilityAirborneJump", OnPerformAirborneJump);
                m_AirborneJumpRegistered = true;
            }
            m_ForceImmediateJump = false;

            base.AbilityStarted();
        }
Beispiel #3
0
        public HierarchicalTimerWheel(TimerWheel[] wheels)
        {
            m_TaskPool = new GenericObjectPool <TimerTask>(() => new TimerTask(), null, (task) => task.Reset());

            if (wheels != null && wheels.Length > 0)
            {
                m_Wheels = wheels;
                for (int i = 0; i < wheels.Length; ++i)
                {
                    TimerWheel wheel = wheels[i];
                    wheel.Level            = i;
                    wheel.completeEvent    = OnCompleted;
                    wheel.slotTriggerEvent = OnSoltTrigger;
                }

                m_LowLevelWheel = wheels[0];
            }
        }
Beispiel #4
0
    public virtual void DoFixedUpdate()
    {
        //TODO moveStep skillStep etc...
        unitFrameInfo = GenericObjectPool <UnitFrameInfo> .Get();

        unitFrameInfo.frame     = FrameManager.currentNetworkFrame;
        unitFrameInfo.canMove   = canMove;
        unitFrameInfo.canRotate = canRotation;
        if (canMove)
        {
            unitFrameInfo.position = position;
        }
        if (canRotation)
        {
            unitFrameInfo.rotation = rotation;
        }
        Debug.Log("DoFixedUpdate...");
    }
Beispiel #5
0
            /// <summary>
            /// Stops managing the character.
            /// </summary>
            public void UnregisterCharacter()
            {
                if (m_CompleteInitEvent != null)
                {
                    Scheduler.Cancel(m_CompleteInitEvent);
                    m_CompleteInitEvent = null;
                }

                if (m_SmoothedBones != null)
                {
                    for (int i = 0; i < m_SmoothedBones.Length; ++i)
                    {
                        GenericObjectPool.Return(m_SmoothedBones[i]);
                    }
                    m_SmoothedBones = null;
                }
                EventHandler.UnregisterEvent <ILookSource>(m_CharacterLocomotion.gameObject, "OnCharacterAttachLookSource", OnAttachLookSource);
            }
Beispiel #6
0
        /// <summary>
        /// Updates the shader to support a fade.
        /// </summary>
        /// <param name="material">The material to update.</param>
        private void EnableFadeMaterial(Material material)
        {
            // If the character's materials change at runtime then the values need to be saved every time fading is enabled.
            if (!m_CacheCharacterMaterials && !m_OriginalMaterialValuesMap.ContainsKey(material))
            {
                var originalMaterialValues = GenericObjectPool.Get <OriginalMaterialValue>();
                originalMaterialValues.Initialize(material, m_ColorID, m_MaterialModeSet.Contains(material));
                m_OriginalMaterialValuesMap.Add(material, originalMaterialValues);
            }

            if (m_MaterialModeSet.Contains(material))
            {
                material.SetFloat(OriginalMaterialValue.ModeID, 2);
                material.SetInt(OriginalMaterialValue.SrcBlendID, (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
                material.SetInt(OriginalMaterialValue.DstBlendID, (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
            }
            material.EnableKeyword(OriginalMaterialValue.AlphaBlendString);
            material.renderQueue = 3000;
        }
        private static void TestGenericPool()
        {
            ConsoleWriter.Instance.WriteEmphasis("Generic Pool Test\n");

            IGenericObjectPool <TestPoolItem> testPool = new GenericObjectPool <TestPoolItem>(10, BalancingMethods.RoundRobin);

            List <TestPoolItem> items = new List <TestPoolItem>();

            for (var i = 0; i < 5; i++)
            {
                items.Add(testPool.AcquireItem().Result);
            }
            ConsoleWriter.Instance.WriteInformation($"Count: {testPool.Count}\tSize: {testPool.Size}");

            ConsoleWriter.Instance.WriteEmphasis("Press any key to acquire one more", true);

            var itemAdded = testPool.AcquireItem().Result;

            items.Add(itemAdded);
            ConsoleWriter.Instance.WriteInformation($"Count: {testPool.Count}\tSize: {testPool.Size}");

            ConsoleWriter.Instance.WriteEmphasis("Press any key to deactivate last added", true);
            itemAdded.Deactivate();

            ConsoleWriter.Instance.WriteInformation($"Count: {testPool.Count}\tSize: {testPool.Size}");

            ConsoleWriter.Instance.WriteEmphasis("Press any key to release all", true);

            for (var i = 0; i < items.Count; i++)
            {
                testPool.ReleaseItem(items[i]).Wait();
            }

            testPool.ContractItemPool();
            Thread.Sleep(10);

            ConsoleWriter.Instance.WriteInformation($"Count: {testPool.Count}\tSize: {testPool.Size}");

            ConsoleWriter.Instance.WriteEmphasis("Press any key to quit", true);

            testPool.Dispose();
            ConsoleWriter.Instance.Dispose();
        }
        /// <summary>
        /// The object has taken damage.
        /// </summary>
        /// <param name="amount">The amount of damage taken.</param>
        /// <param name="position">The position of the damage.</param>
        /// <param name="force">The amount of force applied to the object while taking the damage.</param>
        /// <param name="attacker">The GameObject that did the damage.</param>
        /// <param name="hitCollider">The Collider that was hit.</param>
        private void OnDamage(float amount, Vector3 position, Vector3 force, GameObject attacker, Collider hitCollider)
        {
            // Don't show a hit indicator if the force is 0 or there is no attacker. This prevents damage such as fall damage from showing the damage indicator.
            if ((!m_AlwaysShowIndicator && force.sqrMagnitude == 0) || attacker == null || m_ActiveDamageIndicatorCount == m_ActiveDamageIndicators.Length)
            {
                return;
            }

            var direction = Vector3.ProjectOnPlane(m_CharacterTransform.position - ((m_FollowAttacker && m_Character != attacker) ? attacker.transform.position : position),
                                                   m_CharacterLocomotion.Up);

            // The hit indicator is shown on a 2D canvas so the y direction should be ignored.
            direction.y = 0;
            direction.Normalize();

            // Determine the angle of the damage position to determine if a new damage indicator should be shown.
            var angle = Vector3.Angle(direction, m_CameraTransform.forward) * Mathf.Sign(Vector3.Dot(direction, m_CameraTransform.right));

            // Do not show a new damage indicator if the angle is less than a threshold compared to the already displayed indicators.
            DamageIndicator damageIndicator;

            for (int i = 0; i < m_ActiveDamageIndicatorCount; ++i)
            {
                damageIndicator = m_ActiveDamageIndicators[i];
                if (Mathf.Abs(angle - damageIndicator.Angle) < m_IndicatorAngleThreshold)
                {
                    damageIndicator.DisplayTime = Time.time;
                    m_ActiveDamageIndicators[i] = damageIndicator;
                    return;
                }
            }

            // Add the indicator to the active hit indicators list and enable the component.
            damageIndicator = GenericObjectPool.Get <DamageIndicator>();
            damageIndicator.Initialize(attacker.transform, position, angle, m_StoredIndicators[m_DamageIndicatorIndex]);
            m_ActiveDamageIndicators[m_ActiveDamageIndicatorCount] = damageIndicator;
            m_ActiveDamageIndicatorCount++;
            m_DamageIndicatorIndex = (m_DamageIndicatorIndex + 1) % m_StoredIndicators.Length;

            // Allow the indicators to move/fade.
            m_GameObject.SetActive(true);
        }
Beispiel #9
0
        static void Main(string[] args)
        {
            var connectionString = "Data Source=DESKTOP-QMR3K93;Initial Catalog=Testing;Integrated Security=True";

            Loaders = new GenericObjectPool <DbLoader>(100, BalancingMethods.Random);

            int rowCnt = 5000;

            int loaderCnt = 0;

            DateTime start = DateTime.Now;

            for (var row = 0; row < rowCnt; row++)
            {
                List <string> columns = new List <string>();
                for (var col = 0; col < 25; col++)
                {
                    columns.Add($"somevalue{col}");
                }

                var loader = Loaders.AcquireItem(connectionString).Result;
                if (string.IsNullOrEmpty(loader.Name))
                {
                    loaderCnt++;
                    loader.Name = $"Loader {loaderCnt}";
                }
                loader.MaxCount = 500;
                loader.Activate(connectionString);

                loader.LoadIntoDatabase(columns);
            }
            var end = DateTime.Now;

            Console.WriteLine($"{Loaders.Count} loaders started in {end - start}");

            Console.WriteLine("\nPress any key to quit");
            Console.ReadKey();


            Loaders.Dispose();
        }
    //``````````````````````````````````````````````````````````````````````````````````````````````````````````````
    //``````````````````````````````````````````````````````````````````````````````````````````````````````````````
    private void Awake()
    {
        if (Instance != this)
        {
            Destroy(Instance);
        }

        Instance = this;

        foreach (var item in PoolList)
        {
            for (int i = 0; i < item.size; i++)
            {
                GameObject obj = Instantiate(item.prefab);
                obj.transform.SetParent(parentObject, true);
                obj.SetActive(false);
                gameObjectQueue.Enqueue(obj);
            }
            //poolDictionary.Add(item.name, gameObjectQueue);
        }
    }
Beispiel #11
0
        /// <summary>
        /// The ability has stopped running.
        /// </summary>
        /// <param name="force">Was the ability force stopped?</param>
        protected override void AbilityStopped(bool force)
        {
            base.AbilityStopped(force);

            // Update one last time with an axis value of 0 to return to the starting position.
            m_AxisValue = 0;
            UpdateLean(true);

            // The collider is no longer needed.
            if (m_ColliderGameObject != null)
            {
                m_ColliderGameObject.SetActive(false);
            }

            if (m_Handler != null)
            {
                m_Handler.UnregisterInputEvent(m_LeanInput);
                GenericObjectPool.Return(m_LeanInput);
            }
            EventHandler.UnregisterEvent <float>(m_GameObject, "OnLeanInputUpdate", OnInputUpdate);
        }
Beispiel #12
0
 /// <summary>
 /// The view type has changed.
 /// </summary>
 /// <param name="activate">Should the current view type be activated?</param>
 /// <param name="pitch">The pitch of the camera (in degrees).</param>
 /// <param name="yaw">The yaw of the camera (in degrees).</param>
 /// <param name="characterRotation">The rotation of the character.</param>
 public override void ChangeViewType(bool activate, float pitch, float yaw, Quaternion characterRotation)
 {
     if (activate)
     {
         m_Pitch             = pitch;
         m_Yaw               = yaw;
         m_CharacterRotation = characterRotation;
         if (m_CharacterLocomotion.Platform != null)
         {
             UpdatePlatformRotationOffset(m_CharacterLocomotion.Platform);
         }
         if (m_Camera.fieldOfView != m_FieldOfView)
         {
             m_FieldOfViewChangeTime = Time.time + m_FieldOfViewDamping / m_CharacterLocomotion.TimeScale;
         }
         if (m_StepZoomSensitivity > 0)
         {
             if (m_Handler != null)
             {
                 m_StepZoomInputEvent = GenericObjectPool.Get <ActiveInputEvent>();
                 m_StepZoomInputEvent.Initialize(ActiveInputEvent.Type.Axis, m_StepZoomInputName, "OnThirdPersonViewTypeStepZoom");
                 m_Handler.RegisterInputEvent(m_StepZoomInputEvent);
             }
             EventHandler.RegisterEvent <float>(m_GameObject, "OnThirdPersonViewTypeStepZoom", OnStepZoom);
         }
     }
     else
     {
         if (m_StepZoomSensitivity > 0)
         {
             if (m_Handler != null)
             {
                 m_StepZoomInputEvent = GenericObjectPool.Get <ActiveInputEvent>();
                 m_Handler.UnregisterAbilityInputEvent(m_StepZoomInputEvent);
                 GenericObjectPool.Return(m_StepZoomInputEvent);
             }
             EventHandler.UnregisterEvent <float>(m_GameObject, "OnThirdPersonViewTypeStepZoom", OnStepZoom);
         }
     }
 }
        public void ReturnObject(IDatabase db, IDbConnection conn)
        {
            GenericObjectPool <IDbConnection> pool = GetOrCreatePool(db);

            pool.ReturnObject(conn);

            if (db != null && db.Config.EnableLogConnectionPool == true)
            {
                db.LogHelper.Debug("-------------------ReturnObject IDbConnection:" + conn.GetHashCode() + "; status:" + conn.State);
                db.LogHelper.Debug("CreatedCount:" + pool.CreatedCount + "; ActiveCount:" + pool.ActiveCount + "; BorrowedCount:" + pool.BorrowedCount
                                   + "; ReturnedCount:" + pool.ReturnedCount
                                   + "; MaxTotal:" + pool.MaxTotal
                                   + "; IdleCount:" + pool.IdleCount
                                   + "; NumIdle:" + pool.NumIdle
                                   + "; ActiveCount:" + pool.ActiveCount
                                   + "; NumActive:" + pool.NumActive
                                   + "; NumTests:" + pool.NumTests
                                   + "; DestroyedCount:" + pool.DestroyedCount
                                   + "; DestroyedByBorrowValidationCount:" + pool.DestroyedByBorrowValidationCount
                                   );
            }
        }
Beispiel #14
0
        /// <summary>
        /// Perform the impact action.
        /// </summary>
        /// <param name="castID">The ID of the cast.</param>
        /// <param name="source">The object that caused the cast.</param>
        /// <param name="target">The object that was hit by the cast.</param>
        /// <param name="hit">The raycast that caused the impact.</param>
        protected override void ImpactInternal(uint castID, GameObject source, GameObject target, RaycastHit hit)
        {
            var damageTarget = DamageUtility.GetDamageTarget(target);

            if (damageTarget == null || !damageTarget.IsAlive())
            {
                if (m_InterruptImpactOnNullHealth)
                {
                    m_MagicItem.InterruptImpact();
                }
                return;
            }
            var pooledDamageData = GenericObjectPool.Get <DamageData>();

            pooledDamageData.SetDamage(m_Amount, source.transform.position, (source.transform.position - target.transform.position), m_ForceMagnitude, m_ForceFrames, 0, source, this, null);
            if (m_DamageProcessor == null)
            {
                m_DamageProcessor = DamageProcessor.Default;
            }
            m_DamageProcessor.Process(damageTarget, pooledDamageData);
            GenericObjectPool.Return(pooledDamageData);
        }
        static QuadPool()
        {
            sm_ObjectListPool = new GenericObjectPool <List <IQuadObject> >(() =>
            {
                return(new List <IQuadObject>());
            },
                                                                            null,
                                                                            (list) =>
            {
                list.Clear();
            });

            sm_NodeListPool = new GenericObjectPool <List <QuadNode> >(() =>
            {
                return(new List <QuadNode>());
            },
                                                                       null,
                                                                       (list) =>
            {
                list.Clear();
            });
        }
    /***** MONOBEHAVIOUR FUNCTIONS *****/

    private void Awake()
    {
        Instance = this;
        AddObject(initCount);
    }
Beispiel #17
0
 private void Awake()
 {
     Instance = this;
     AddObjects(15);
 }
 private void Awake() => Instance = this;
 void Awake()
 {
     Instance = this;
 }
Beispiel #20
0
    /***** MONOBEHAVIOUR FUNCTIONS *****/

    protected override void Start()
    {
        base.Start();

        virusPool = VirusPool.Instance;
    }
Beispiel #21
0
 public static T Pop <T>() where T : new()
 {
     return(GenericObjectPool <T> .Pop());
 }
Beispiel #22
0
        /// <summary>
        /// Fade any objects that get in the way between the character and the camera.
        /// </summary>
        /// <param name="immediateFade">Should the fade material be changed immediately?</param>
        private void FadeObstructingObjects(bool immediateFade)
        {
            if (!m_ObstructingObjectsFade)
            {
                return;
            }

            // Disable any obstructing colliders so the sphere cast can detect which objects are obstructing.
            for (int i = 0; i < m_ObstructingCollidersCount; ++i)
            {
                m_ObstructingColliders[i].enabled = true;
            }
            m_ObstructingCollidersCount = 0;

            var characterPosition = m_CharacterTransform.TransformPoint(m_TransformOffset);
            var direction         = (m_Transform.position - characterPosition);
            var start             = characterPosition - direction.normalized * m_CollisionRadius;

            m_CharacterLocomotion.EnableColliderCollisionLayer(false);
            // Fire a sphere to prevent the camera from colliding with other objects.
            var hitCount = Physics.SphereCastNonAlloc(start, m_CollisionRadius, direction.normalized, m_RaycastsHit,
                                                      direction.magnitude, m_CharacterLayerManager.IgnoreInvisibleCharacterWaterLayers, QueryTriggerInteraction.Ignore);

            m_CharacterLocomotion.EnableColliderCollisionLayer(true);

            m_ObstructionHitSet.Clear();
            if (hitCount > 0)
            {
                // Loop through all of the hit colliders. For any collider that has been hit get all of the renderers. The materials that are used on the
                // renderers then need to be checked to determine if they can be faded. If the material can be faded place it in a set which will then
                // be checked in the next block to determine if the material should be faded.
                for (int i = 0; i < hitCount; ++i)
                {
                    var renderers   = m_RaycastsHit[i].transform.gameObject.GetCachedComponents <Renderer>();
                    var obstructing = false;
                    for (int j = 0; j < renderers.Length; ++j)
                    {
                        var materials = renderers[j].materials;
                        for (int k = 0; k < materials.Length; ++k)
                        {
                            if (!m_CanObstructionFade.TryGetValue(materials[k], out var canFade))
                            {
                                // Objects can fade if they have the color property and can be transparent.
                                canFade = materials[k].HasProperty(m_ColorID) && (m_AutoSetMode || materials[k].renderQueue >= (int)UnityEngine.Rendering.RenderQueue.Transparent);
                                m_CanObstructionFade.Add(materials[k], canFade);
                            }

                            if (canFade)
                            {
                                var material = materials[k];
                                // Any material contained within the hit set should be faded.
                                m_ObstructionHitSet.Add(material);
                                if (m_DisableCollider && !obstructing)
                                {
                                    obstructing = CanMaterialFade(material);
                                }

                                // The same material may be applied to multiple renderers.
                                if (!m_OriginalMaterialValuesMap.ContainsKey(material))
                                {
                                    // Don't set the mode automatically just because it has the property - not all objects in the environment should fade.
                                    if (m_AutoSetMode && material.HasProperty(OriginalMaterialValue.ModeID))
                                    {
                                        m_MaterialModeSet.Add(material);
                                    }
                                    var originalMaterialValues = GenericObjectPool.Get <OriginalMaterialValue>();
                                    originalMaterialValues.Initialize(material, m_ColorID, m_MaterialModeSet.Contains(material));
                                    m_OriginalMaterialValuesMap.Add(material, originalMaterialValues);

                                    m_ObstructingMaterials[m_ObstructingMaterialsCount] = material;
                                    m_ObstructingMaterialsCount++;

                                    EnableFadeMaterial(material);
                                }
                            }
                        }
                    }

                    // If the object is faded then the collider has the option of being disabled to prevent it from causing collisions.
                    if (m_DisableCollider && obstructing)
                    {
                        m_RaycastsHit[i].collider.enabled = false;
                        m_ObstructingColliders[m_ObstructingCollidersCount] = m_RaycastsHit[i].collider;
                        m_ObstructingCollidersCount++;
                    }
                }
            }

            // Once the obstructing objects have been found they should be faded. Note that this can cause a lot of overdraw so the FadeObject method can be
            // overridden to provide a custom effect such as the one described on https://madewith.unity.com/stories/dissolving-the-world-part-1.
            for (int i = m_ObstructingMaterialsCount - 1; i >= 0; --i)
            {
                if (!FadeMaterial(m_ObstructingMaterials[i], m_ObstructionHitSet.Contains(m_ObstructingMaterials[i]), immediateFade))
                {
                    RemoveObstructingMaterial(i);
                }
            }
        }
Beispiel #23
0
    /***** MONOBEHAVIOUR FUNCTIONS *****/

    protected override void Start()
    {
        base.Start();

        bacteriaCellPool = BacteriaCellPool.Instance;
    }
 private void Awake()
 {
     Instance = this;
 }
Beispiel #25
0
    public static GenericObjectPool <T> CreatePool(T prefab, int numPoolItems = 10)
    {
        GenericObjectPool <T> pool = new GenericObjectPool <T>(prefab, numPoolItems);

        return(pool);
    }
Beispiel #26
0
        /// <summary>
        /// Initializes the materials on the renderers for character fade.
        /// </summary>
        /// <param name="renderers">The renderers that should be initilaizes for character fade.</param>
        private void InitializeCharacterFadeRenderers(Renderer[] renderers)
        {
            var count = 0;

            for (int i = 0; i < renderers.Length; ++i)
            {
                // The renderer fade can be ignored.
                if (renderers[i].gameObject.GetCachedComponent <IgnoreFadeIdentifier>() != null)
                {
                    continue;
                }
                var materials = renderers[i].materials;
                for (int j = 0; j < materials.Length; ++j)
                {
                    if (!m_RegisteredMaterial.Contains(materials[j]) && materials[j].HasProperty(m_ColorID))
                    {
                        count++;
                    }
                }
            }

            if (count > 0)
            {
                var totalCount = m_CharacterFadeMaterialsCount + count;
                if (m_CharacterFadeMaterials == null)
                {
                    m_CharacterFadeMaterials = new Material[totalCount];
                }
                else if (totalCount >= m_CharacterFadeMaterials.Length)
                {
                    System.Array.Resize(ref m_CharacterFadeMaterials, totalCount);
                }

                // Cache a reference to all of the faded materials.
                for (int i = 0; i < renderers.Length; ++i)
                {
                    // The renderer fade can be ignored.
                    if (renderers[i].gameObject.GetCachedComponent <IgnoreFadeIdentifier>() != null)
                    {
                        continue;
                    }
                    var materials = renderers[i].materials;
                    for (int j = 0; j < materials.Length; ++j)
                    {
                        if (!m_RegisteredMaterial.Contains(materials[j]) && materials[j].HasProperty(m_ColorID))
                        {
                            if (materials[j].HasProperty(OriginalMaterialValue.ModeID))
                            {
                                m_MaterialModeSet.Add(materials[j]);
                            }
                            m_CharacterFadeMaterials[m_CharacterFadeMaterialsCount] = materials[j];
                            m_RegisteredMaterial.Add(materials[j]);
                            m_CharacterFadeMaterialsCount++;

                            if (m_CacheCharacterMaterials && !m_OriginalMaterialValuesMap.ContainsKey(materials[j]))
                            {
                                var originalMaterialValues = GenericObjectPool.Get <OriginalMaterialValue>();
                                originalMaterialValues.Initialize(materials[j], m_ColorID, m_MaterialModeSet.Contains(materials[j]));
                                m_OriginalMaterialValuesMap.Add(materials[j], originalMaterialValues);
                            }
                        }
                    }
                }
            }
        }
Beispiel #27
0
 public static void Push <T>(T obj) where T : new()
 {
     GenericObjectPool <T> .Push(obj);
 }
Beispiel #28
0
        /// <summary>
        /// Attaches the component to the specified character.
        /// </summary>
        /// <param name="character">The handler to attach the camera to.</param>
        protected virtual void OnAttachCharacter(GameObject character)
        {
            enabled = character != null && !m_CameraController.ActiveViewType.FirstPersonPerspective;

            // Disable the fade on the previous active character.
            if (m_CharacterFade)
            {
                if (m_Character != null && m_Character != character)
                {
                    DisableFades();

                    // Clear the previous mappings.
                    if (m_CharacterFadeMaterials != null)
                    {
                        if (m_CacheCharacterMaterials)
                        {
                            for (int i = 0; i < m_CharacterFadeMaterials.Length; ++i)
                            {
                                if (!m_OriginalMaterialValuesMap.ContainsKey(m_CharacterFadeMaterials[i]))
                                {
                                    continue;
                                }
                                GenericObjectPool.Return(m_OriginalMaterialValuesMap[m_CharacterFadeMaterials[i]]);
                                m_OriginalMaterialValuesMap.Remove(m_CharacterFadeMaterials[i]);
                            }
                        }
                        m_CharacterFadeMaterials = null;
                    }
                    m_OriginalMaterialValuesMap.Clear();

                    EventHandler.UnregisterEvent <bool>(m_Character, "OnCameraChangePerspectives", OnChangePerspectives);
                    EventHandler.UnregisterEvent <bool, bool>(m_Character, "OnCharacterIndependentFade", OnIndependentFade);
                    EventHandler.UnregisterEvent <Item>(m_Character, "OnInventoryAddItem", OnAddItem);
                    EventHandler.UnregisterEvent <GameObject, bool>(m_Character, "OnShootableWeaponShowProjectile", OnShowProjectile);
                    EventHandler.UnregisterEvent(m_Character, "OnRespawn", OnRespawn);
                }
            }

            m_Character = character;

            if (m_Character != null)
            {
                m_CharacterTransform    = m_Character.transform;
                m_CharacterLocomotion   = m_Character.GetCachedComponent <UltimateCharacterLocomotion>();
                m_CharacterLayerManager = m_Character.GetCachedComponent <CharacterLayerManager>();
                if (m_CharacterFade)
                {
                    // Determine the number of renderers that will be faded so their materials can be cached.
                    m_RegisteredMaterial.Clear();
                    var count     = 0;
                    var renderers = m_Character.GetComponentsInChildren <Renderer>(true);
                    for (int i = 0; i < renderers.Length; ++i)
                    {
                        // The renderer fade can be ignored.
                        if (renderers[i].gameObject.GetCachedComponent <IgnoreFadeIdentifier>() != null)
                        {
                            continue;
                        }
                        var materials = renderers[i].materials;
                        for (int j = 0; j < materials.Length; ++j)
                        {
                            if (materials[j].HasProperty(m_ColorID))
                            {
                                count++;
                            }
                        }
                    }

                    if (count > 0)
                    {
                        if (m_CharacterFadeMaterials == null)
                        {
                            m_CharacterFadeMaterials = new Material[count];
                        }
                        else if (m_CharacterFadeMaterials.Length != count)
                        {
                            if (m_CacheCharacterMaterials)
                            {
                                // The mapping may exist from a previous character.
                                for (int i = 0; i < m_CharacterFadeMaterials.Length; ++i)
                                {
                                    GenericObjectPool.Return(m_OriginalMaterialValuesMap[m_CharacterFadeMaterials[i]]);
                                    m_OriginalMaterialValuesMap.Remove(m_CharacterFadeMaterials[i]);
                                }
                            }
                            System.Array.Resize(ref m_CharacterFadeMaterials, count);
                        }

                        // Cache a reference to all of the faded materials.
                        m_CharacterFadeMaterialsCount = 0;
                        for (int i = 0; i < renderers.Length; ++i)
                        {
                            // The renderer fade can be ignored.
                            if (renderers[i].gameObject.GetCachedComponent <IgnoreFadeIdentifier>() != null)
                            {
                                continue;
                            }

                            var materials = renderers[i].materials;
                            for (int j = 0; j < materials.Length; ++j)
                            {
                                if (m_RegisteredMaterial.Contains(materials[j]))
                                {
                                    continue;
                                }
                                if (materials[j].HasProperty(m_ColorID))
                                {
                                    if (materials[j].HasProperty(OriginalMaterialValue.ModeID))
                                    {
                                        m_MaterialModeSet.Add(materials[j]);
                                    }
                                    m_CharacterFadeMaterials[m_CharacterFadeMaterialsCount] = materials[j];
                                    m_RegisteredMaterial.Add(materials[j]);
                                    m_CharacterFadeMaterialsCount++;

                                    if (m_CacheCharacterMaterials)
                                    {
                                        var originalMaterialValues = GenericObjectPool.Get <OriginalMaterialValue>();
                                        originalMaterialValues.Initialize(materials[j], m_ColorID, m_MaterialModeSet.Contains(materials[j]));
                                        m_OriginalMaterialValuesMap.Add(materials[j], originalMaterialValues);
                                    }
                                }
                            }
                        }
                    }

                    EventHandler.RegisterEvent <bool>(m_Character, "OnCameraChangePerspectives", OnChangePerspectives);
                    EventHandler.RegisterEvent <Item>(m_Character, "OnInventoryAddItem", OnAddItem);
                    EventHandler.RegisterEvent <GameObject, bool>(m_Character, "OnShootableWeaponShowProjectile", OnShowProjectile);
                    EventHandler.RegisterEvent <bool, bool>(m_Character, "OnCharacterIndependentFade", OnIndependentFade);
                    EventHandler.RegisterEvent(m_Character, "OnRespawn", OnRespawn);
                }

                // Fade the obstructing objects immediately after the character has been assigned.
                if (m_ObstructingObjectsFade)
                {
                    FadeObstructingObjects(true);
                }
            }
        }
Beispiel #29
0
        /// <summary>
        /// The object has collided with another object.
        /// </summary>
        /// <param name="hit">The RaycastHit of the object. Can be null.</param>
        protected override void OnCollision(RaycastHit?hit)
        {
            base.OnCollision(hit);

            var forceDestruct = false;

            if (m_CollisionMode == CollisionMode.Collide)
            {
                // When there is a collision the object should move to the position that was hit so if it's not destroyed then it looks like it
                // is penetrating the hit object.
                if (hit != null && hit.HasValue && m_Collider != null)
                {
                    var closestPoint = m_Collider.ClosestPoint(hit.Value.point);
                    m_Transform.position += (hit.Value.point - closestPoint);
                    // Only set the parent to the hit transform on uniform objects to prevent stretching.
                    if (MathUtility.IsUniform(hit.Value.transform.localScale))
                    {
                        // The parent layer must be within the sticky layer mask.
                        if (MathUtility.InLayerMask(hit.Value.transform.gameObject.layer, m_StickyLayers))
                        {
                            m_Transform.parent = hit.Value.transform;

                            // If the destructible sticks to a character then the object should be added as a sub collider so collisions will be ignored.
                            m_StickyCharacterLocomotion = hit.Value.transform.gameObject.GetCachedComponent <UltimateCharacterLocomotion>();
                            if (m_StickyCharacterLocomotion != null)
                            {
                                m_StickyCharacterLocomotion.AddIgnoredCollider(m_Collider);
                            }
                        }
                        else
                        {
                            forceDestruct = true;
                        }
                    }
                }
                if (m_TrailRenderer != null)
                {
                    m_TrailRenderer.enabled = false;
                }
            }

            var destructionDelay = m_DestructionDelay;

            if (m_ParticleSystem != null && m_WaitForParticleStop)
            {
                destructionDelay = m_ParticleSystem.main.duration;
                m_ParticleSystem.Stop(true, ParticleSystemStopBehavior.StopEmitting);
                Stop();
            }

            // The object may not have been initialized before it collides.
            if (m_GameObject == null)
            {
                InitializeComponentReferences();
            }

            if (hit != null && hit.HasValue)
            {
                var hitValue      = hit.Value;
                var hitGameObject = hitValue.collider.gameObject;
                // The shield can absorb some (or none) of the damage from the destructible.
                var damageAmount = m_DamageAmount;
#if ULTIMATE_CHARACTER_CONTROLLER_MELEE
                ShieldCollider shieldCollider;
                if ((shieldCollider = hitGameObject.GetCachedComponent <ShieldCollider>()) != null)
                {
                    damageAmount = shieldCollider.Shield.Damage(this, damageAmount);
                }
#endif

                // Allow a custom event to be received.
                EventHandler.ExecuteEvent <float, Vector3, Vector3, GameObject, object, Collider>(hitGameObject, "OnObjectImpact", damageAmount, hitValue.point, m_Velocity.normalized * m_ImpactForce, m_Originator, this, hitValue.collider);
                if (m_OnImpactEvent != null)
                {
                    m_OnImpactEvent.Invoke(damageAmount, hitValue.point, m_Velocity.normalized * m_ImpactForce, m_Originator);
                }

                // If the shield didn't absorb all of the damage then it should be applied to the character.
                if (damageAmount > 0)
                {
                    var damageTarget = DamageUtility.GetDamageTarget(hitGameObject);
                    if (damageTarget != null)
                    {
                        var pooledDamageData = GenericObjectPool.Get <DamageData>();
                        pooledDamageData.SetDamage(this, damageAmount, hitValue.point, -hitValue.normal, m_ImpactForce, m_ImpactForceFrames, 0, hitValue.collider);
                        var damageProcessorModule = hitGameObject.GetCachedComponent <DamageProcessorModule>();
                        if (damageProcessorModule != null)
                        {
                            damageProcessorModule.ProcessDamage(m_DamageProcessor, damageTarget, pooledDamageData);
                        }
                        else
                        {
                            if (m_DamageProcessor == null)
                            {
                                m_DamageProcessor = DamageProcessor.Default;
                            }
                            m_DamageProcessor.Process(damageTarget, pooledDamageData);
                        }
                        GenericObjectPool.Return(pooledDamageData);
                    }
                    else if (m_ImpactForce > 0)
                    {
                        // If the damage target exists it will apply a force to the rigidbody in addition to procesing the damage. Otherwise just apply the force to the rigidbody.
                        var collisionRigidbody = hitGameObject.GetCachedParentComponent <Rigidbody>();
                        if (collisionRigidbody != null && !collisionRigidbody.isKinematic)
                        {
                            collisionRigidbody.AddForceAtPosition(m_ImpactForce * MathUtility.RigidbodyForceMultiplier * -hitValue.normal, hitValue.point);
                        }
                        else
                        {
                            var forceObject = hitGameObject.GetCachedParentComponent <IForceObject>();
                            if (forceObject != null)
                            {
                                forceObject.AddForce(m_Transform.forward * m_ImpactForce);
                            }
                        }
                    }
                }

                // An optional state can be activated on the hit object.
                if (!string.IsNullOrEmpty(m_ImpactStateName))
                {
                    StateManager.SetState(hitGameObject, m_ImpactStateName, true);
                    // If the timer isn't -1 then the state should be disabled after a specified amount of time. If it is -1 then the state
                    // will have to be disabled manually.
                    if (m_ImpactStateDisableTimer != -1)
                    {
                        StateManager.DeactivateStateTimer(hitGameObject, m_ImpactStateName, m_ImpactStateDisableTimer);
                    }
                }
            }

            // The object can destroy itself after a small delay.
            if (m_DestroyEvent == null && (m_DestroyOnCollision || forceDestruct || destructionDelay > 0))
            {
                m_DestroyEvent = SchedulerBase.ScheduleFixed(destructionDelay, Destruct, hit);
            }
        }
Beispiel #30
0
 /**
  * Create a new GenericObjectPoolFactory.
  *
  * @param factory the PoolableObjectFactory used by created pools.
  * @param config a non-<code>null</code> GenericObjectPool<T>.Config describing the configuration.
  * @throws NullPointerException when config is <code>null</code>.
  * @see GenericObjectPool#GenericObjectPool(PoolableObjectFactory, GenericObjectPool<T>.Config)
  */
 public GenericObjectPoolFactory(PoolableObjectFactory <T> factory, GenericObjectPool <T> .Config config) :// throws NullPointerException {
     this(factory, config.maxActive, config.whenExhaustedAction, config.maxWait, config.maxIdle, config.minIdle, config.testOnBorrow, config.testOnReturn, config.timeBetweenEvictionRunsMillis, config.numTestsPerEvictionRun, config.minEvictableIdleTimeMillis, config.testWhileIdle, config.softMinEvictableIdleTimeMillis, config.lifo)
 {
 }