Ejemplo n.º 1
0
        public void LoadData()
        {
            if (!Root.ZoneSystem.Loaded)
            {
                Root.ZoneSystem.LoadData();
            }

            SparseTwinIndex <float> distances = Root.ZoneSystem.Distances;

            if (!ConvertToKM)
            {
                Data = distances;
            }
            else
            {
                var flatDistances = distances.GetFlatData();
                Data = distances.CreateSimilarArray <float>();
                var local = Data.GetFlatData();
                if (VectorHelper.IsHardwareAccelerated)
                {
                    for (int i = 0; i < local.Length; i++)
                    {
                        VectorHelper.Multiply(local[i], 0, flatDistances[i], 0, 0.001f, local.Length);
                    }
                }
                else
                {
                    for (int i = 0; i < local.Length; i++)
                    {
                        for (int j = 0; j < local[i].Length; j++)
                        {
                            local[i][j] = flatDistances[i][j] * 0.001f;
                        }
                    }
                }
            }
        }
Ejemplo n.º 2
0
    public static int WriteLights(List <Light> lights, int maxLights, Vector3 center, Transform directionTransform, Transform positionTransform, params Material[] materials)
    {
        var lightCount = 0;

        if (lights != null)
        {
            for (var i = 1; i <= lights.Count; i++)
            {
                var index = i - 1;
                var light = lights[index];

                if (Enabled(light) == true && light.intensity > 0.0f && lightCount < maxLights)
                {
                    var prefix    = "_Light" + (++lightCount);
                    var direction = default(Vector3);
                    var position  = default(Vector3);
                    var color     = default(Color);

                    CalculateLight(light, center, directionTransform, positionTransform, ref position, ref direction, ref color);

                    for (var j = materials.Length - 1; j >= 0; j--)
                    {
                        var material = materials[j];

                        if (material != null)
                        {
                            material.SetVector(prefix + "Direction", direction);
                            material.SetVector(prefix + "Position", VectorHelper.MakeFrom(position, 1.0f));
                            material.SetColor(prefix + "Color", color);
                        }
                    }
                }
            }
        }

        return(lightCount);
    }
 internal void IterationFinished()
 {
     // normalize the data by the number of household iterations
     VectorHelper.Multiply(DataStorage, 0, DataStorage, 0, (1.0f / Root.HouseholdIterations), DataStorage.Length);
     // now we can store the results
     using (var writer = new StreamWriter(SaveTo))
     {
         writer.WriteLine("AgeCategory,Occupation,EmploymentStatus,Mode,ExpandedTrips");
         var allModes   = Root.Root.AllModes;
         var ageString  = Root.AgeRanges.Select(r => r.ToString()).ToArray();
         var occString  = Root.Occupations.Select(o => Enum.GetName(typeof(Occupation), o)).ToArray();
         var empString  = Root.EmploymentStatuses.Select(e => Enum.GetName(typeof(TTSEmploymentStatus), e)).ToArray();
         var modeString = allModes.Select(m => m.ModeName).ToArray();
         for (int ageCat = 0; ageCat < Root.AgeRanges.Count; ageCat++)
         {
             for (int occCat = 0; occCat < Root.Occupations.Length; occCat++)
             {
                 for (int empCat = 0; empCat < Root.EmploymentStatuses.Length; empCat++)
                 {
                     int offset = GetDataOffset(ageCat, Root.Occupations[occCat], Root.EmploymentStatuses[empCat]);
                     for (int mode = 0; mode < allModes.Count; mode++)
                     {
                         writer.Write(ageString[ageCat]);
                         writer.Write(',');
                         writer.Write(occString[occCat]);
                         writer.Write(',');
                         writer.Write(empString[empCat]);
                         writer.Write(',');
                         writer.Write(modeString[mode]);
                         writer.Write(',');
                         writer.WriteLine(DataStorage[offset + mode]);
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 4
0
    private void UpdateAnimation(Vector3 _playerPosition, Vector3 _playerDelta)
    {
        ratio = VectorHelper.Divide(_playerDelta, LookPositionOnPlane.Instance.Size) * animateSensitivity;

        float _absRatioX = Mathf.Abs(ratio.x);
        float _absRatioY = Mathf.Abs(ratio.y);

        if (_absRatioX > turnAnimateThreshold && _absRatioX > _absRatioY)
        {
            playingMiddleState = false;
            if (ratio.x > 0)
            {
                animator.Play(rightStateIndex, 0, ratio.x);
            }
            else
            {
                animator.Play(leftStateIndex, 0, ratio.x * -1);
            }
        }
        else if (_absRatioY > turnAnimateThreshold)
        {
            playingMiddleState = false;
            if (ratio.y > 0)
            {
                animator.Play(upStateIndex, 0, ratio.y);
            }
            else
            {
                animator.Play(downStateIndex, 0, ratio.y * -1);
            }
        }
        else if (!playingMiddleState)
        {
            playingMiddleState = true;
            animator.Play(middleStateIndex);
        }
    }
Ejemplo n.º 5
0
        public override void DetermineWeaponReadiness()
        {
            if (!_weaponSystem.UseStaticGuns)
            {
                _readyToFire = false;
                return;
            }

            RefreshAmmoDetails();

            _readyToFire = RAI_SessionCore.Instance.WeaponCore.IsWeaponReadyToFire(_weaponBlock, _weaponIndex, false, true);

            if (!_readyToFire && _ammoReloadPending)
            {
                _readyToFire = true;
            }
            else if (!_readyToFire)
            {
                Logger.MsgDebug(_weaponBlock.CustomName + " Ready: " + _readyToFire.ToString(), DebugTypeEnum.WeaponStaticCore);
                return;
            }

            _currentDistance = Vector3D.Distance(_weaponBlock.GetPosition(), _currentTargetWaypoint);
            _currentAngle    = VectorHelper.GetAngleBetweenDirections(_weaponBlock.WorldMatrix.Forward, Vector3D.Normalize(_currentTargetWaypoint - _weaponBlock.GetPosition()));


            _angleCheckPassed    = _currentAngle < _weaponSystem.WeaponMaxAngleFromTarget && _waypointIsTarget;
            _currentAmmoIsHoming = IsCurrentAmmoHoming();
            _currentAmmoIsBeam   = IsCurrentAmmoLaser();

            if (!_angleCheckPassed && !_currentAmmoIsHoming)
            {
                _readyToFire = false;
            }

            //Logger.MsgDebug(_weaponBlock.CustomName + " Ready: " + _readyToFire.ToString(), DebugTypeEnum.WeaponStaticCore);
        }
        /// <summary>
        /// Update
        /// </summary>
        /// <param name="timestep"></param>
        /// <param name="universe"></param>
        public override void Update(Timestep timestep, EntityUniverseFacade universe)
        {
            // Following check is taken from Daemons mod
            // Don't let this logic do anything if tile does not exist. Might be accessed after removal of tile.
            if (!universe.ReadTile(Location, TileAccessFlags.None, out Tile tile))
            {
                return;
            }

            // Following check is taken from Daemons mod
            // If the tile/variant has changed, or it doesn't have a Sprinkler Component set this logic to be removed.
            if ((tile.Configuration != this._configuration) || this._variant != tile.Variant() || this._signComponent == null)
            {
                this._isRemoved = true;

                if (tile.Configuration == this._configuration)
                {
                    universe.RemoveTile(base.Entity, base.Location, TileAccessFlags.None);
                }

                return;
            }

            // If the centerPos is not set lets set it
            if (this._centerPos == Vector3D.Zero)
            {
                uint     rotation = tile.Configuration.Rotation(tile.Variant());
                Vector3D offset   = VectorHelper.RotatePosition(rotation, this._signComponent.offsetFromCenter);
                this._centerPos = tile.Configuration.TileCenter(this.Location, tile.Variant()) + offset;

                Vector3F tileOffset = default(Vector3F);
                if (universe.TileOffset(base.Location, TileAccessFlags.None, out tileOffset))
                {
                    this._centerPos += tileOffset.ToVector3D();
                }
            }
        }
Ejemplo n.º 7
0
        public void Min_Max_Vectors_given___correct_Min_Max()
        {
            var    rnd    = new Random();
            var    minArr = new double[Vector <double> .Count];
            var    maxArr = new double[Vector <double> .Count];
            double min    = double.MaxValue;
            double max    = double.MinValue;

            for (int j = 0; j < Vector <double> .Count; ++j)
            {
                minArr[j] = rnd.NextDouble();
                maxArr[j] = rnd.NextDouble();

                if (minArr[j] < min)
                {
                    min = minArr[j];
                }
                if (maxArr[j] > max)
                {
                    max = maxArr[j];
                }
            }

            double expectedMin = min;
            double expectedMax = max;

            var minVec = new Vector <double>(minArr);
            var maxVec = new Vector <double>(maxArr);

            VectorHelper.ReduceMinMax(minVec, maxVec, ref min, ref max);

            Assert.Multiple(() =>
            {
                Assert.AreEqual(expectedMin, min, 1e-10);
                Assert.AreEqual(expectedMax, max, 1e-10);
            });
        }
Ejemplo n.º 8
0
    private void LateUpdate()
    {
        Vector2 speed = new Vector2(scrollSpeed.x * Time.deltaTime * 60f, scrollSpeed.y * Time.deltaTime * 60f);

        foreach (var sprRenderer in allSpriteRenderers)
        {
            sprRenderer.transform.localPosition += new Vector3(speed.x, speed.y);
        }

        positionDelta += VectorHelper.Absolute(speed);

        if (Mathf.Abs(scrollSpeed.x) > 0 && positionDelta.x >= (int)(sprite.bounds.size.x))
        {
            positionDelta.x = 0;
            for (int c = 0; c < columns; c++)
            {
                for (int r = 0; r < rows; r++)
                {
                    var sprRenderer = allSpriteRenderers[c * rows + r];
                    sprRenderer.transform.localPosition = new Vector3(GetTilePosition(c, r).x, sprRenderer.transform.localPosition.y);
                }
            }
        }

        if (Mathf.Abs(scrollSpeed.y) > 0 && positionDelta.y >= (int)(sprite.bounds.size.y))
        {
            positionDelta.y = 0;
            for (int c = 0; c < columns; c++)
            {
                for (int r = 0; r < rows; r++)
                {
                    var sprRenderer = allSpriteRenderers[c * rows + r];
                    sprRenderer.transform.localPosition = new Vector3(sprRenderer.transform.localPosition.x, GetTilePosition(c, r).y);
                }
            }
        }
    }
Ejemplo n.º 9
0
    // Update is called once per frame
    void Update()
    {
        if (Vector3.Distance(transform.position, currentTarget.transform.position) < .1f && !aggro)
        {
            currIndex++;
            if (currIndex > path.Count - 1)
            {
                currIndex = 0;
            }
            currentPortal      = path[currIndex];
            transform.position = currentPortal.transform.position;
            currentTarget      = currentPortal.GetComponent <enemyPortal>().end;
        }
        aggro = DetectPlayer();

        CalcSteering();

        velocity           += acceleration;
        velocity            = VectorHelper.Clamp(velocity, maxSpeed);
        transform.position += velocity * Time.deltaTime;
        transform.rotation  = Quaternion.LookRotation(velocity);

        acceleration = Vector3.zero;
    }
Ejemplo n.º 10
0
        public void LoadData()
        {
            var zoneArray            = this.Root.ZoneSystem.ZoneArray;
            var zones                = zoneArray.GetFlatData();
            var firstRate            = this.FirstRateToApply.AquireResource <SparseArray <float> >();
            var secondRate           = this.SecondRateToApply.AquireResource <SparseArray <float> >();
            SparseArray <float> data = firstRate.CreateSimilarArray <float>();
            var flatFirst            = firstRate.GetFlatData();
            var flatSecond           = secondRate.GetFlatData();
            var flat = data.GetFlatData();

            if (VectorHelper.IsHardwareAccelerated)
            {
                VectorHelper.Divide(flat, 0, flatFirst, 0, flatSecond, 0, flat.Length);
            }
            else
            {
                for (int i = 0; i < flat.Length; i++)
                {
                    flat[i] = flatFirst[i] / flatSecond[i];
                }
            }
            this.Data = data;
        }
Ejemplo n.º 11
0
    [Fact] public void MinMax()
    {
        Data_Generator dg = new Data_Generator();
        Hand_Generator hg = new Hand_Generator(dg);

        (Joints min, Joints max, Joints j)dat;
        dat.j   = hg.newJoints();
        dat.min = new Joints(dg.newMinVectors(5), dg.newMinVectors(5), dg.newMinVectors(5), dg.newMinVectors(5),
                             dg.newMinVectors(5), dg.newMinVector(), dg.newFloat(100));
        dat.max = new Joints(dg.newZeroVectors(5), dg.newZeroVectors(5), dg.newZeroVectors(5), dg.newZeroVectors(5),
                             dg.newZeroVectors(5), dg.newZeroVector(), dg.newFloat(100));

        (Joints min, Joints max)exp;
        exp.min = dat.min;
        exp.max = dat.j;

        var vH = new VectorHelper();
        var jH = new JointsHelper(vH);

        var act = jH.minMax(dat.min, dat.max, dat.j);

        test.jointsEqual(exp.min, act.min);
        test.jointsEqual(exp.max, act.max);
    }
Ejemplo n.º 12
0
        public void CalculateShine(ref Matrix4x4 soc1, ref Matrix4x4 soc2, ref Matrix4x4 sc1, ref Matrix4x4 sp1)
        {
            for (var i = 0; i < Mathf.Min(4, ShineCasters.Count); i++)
            {
                if (ShineCasters[i] == null)
                {
                    Debug.Log("Atmosphere: Shine problem!"); break;
                }

                var shineCaster = ShineCasters[i];

                // TODO : Planetshine distance based shine influence...
                // TODO : Planetshine distance don't gonna work correctly on screenspace, e.g Atmosphere...
                // NOTE : Distance is inversed.
                var distance = 0.0f;

                soc1.SetRow(i, VectorHelper.MakeFrom((shineCaster.transform.position - Origin).normalized, 1.0f));
                soc2.SetRow(i, VectorHelper.MakeFrom((Origin - shineCaster.transform.position).normalized, 1.0f));

                sc1.SetRow(i, VectorHelper.FromColor(Helper.Enabled(shineCaster) ? ShineColors[i] : new Color(0, 0, 0, 0)));

                sp1.SetRow(i, new Vector4(0.0f, 0.0f, 0.0f, distance));
            }
        }
Ejemplo n.º 13
0
    public void SpawnDebris(RandomDungeon dungeon, CollisionMap collisionMap, Vector2 avatarStartPosition)
    {
        List <Vector2Int> positions = collisionMap.EmptyPositions();

        positions.RemoveAll((pos) => VectorHelper.OrthogonalDistance(pos, avatarStartPosition) < 3);

        int numDebris = Random.Range(positions.Count / 5, positions.Count / 4);

        for (int i = 0; i < numDebris; ++i)
        {
            if (positions.Count == 0)
            {
                return;
            }

            Vector2Int pos = positions.Sample();

            // todo bdsowers - ensure that this position is valid
            GameObject newDebris = PrefabManager.instance.InstantiatePrefabByName(PrefabManager.instance.debrisPrefabs.Sample().name);
            newDebris.transform.position = MapCoordinateHelper.MapToWorldCoords(pos);
            collisionMap.MarkSpace(pos.x, pos.y, newDebris.GetComponent <SimpleMovement>().uniqueCollisionIdentity);
            positions.Remove(pos);
        }
    }
Ejemplo n.º 14
0
        public void TestSelectIfFinite()
        {
            Vector <float> alternate = new Vector <float>(1.0f);

            float[] temp = new float[Vector <float> .Count];
            for (int i = 0; i < temp.Length; i++)
            {
                temp[i] = i + 5.0f;
            }
            temp[temp.Length - 1] = float.NaN;
            temp[temp.Length - 2] = float.PositiveInfinity;
            temp[temp.Length - 3] = float.NegativeInfinity;
            Vector <float> v      = new Vector <float>(temp);
            var            result = new float[Vector <float> .Count];

            VectorHelper.SelectIfFinite(v, alternate).CopyTo(result);
            for (int i = 0; i < temp.Length - 3; i++)
            {
                Assert.AreEqual(temp[i], result[i]);
            }
            Assert.AreEqual(1.0f, result[result.Length - 1], "NaN wasn't change to 1!");
            Assert.AreEqual(1.0f, result[result.Length - 2], "Positive Infinity wasn't change to 1!");
            Assert.AreEqual(1.0f, result[result.Length - 3], "Negative Infinity wasn't change to 1!");
        }
Ejemplo n.º 15
0
        private void CreateAndMoveToOffset()
        {
            if (NewAutoPilot.InGravity())
            {
                if (NewAutoPilot.Targeting.Target.CurrentAltitude() > NewAutoPilot.OffsetPlanetMinTargetAltitude)
                {
                    //Logger.MsgDebug("Target Is High", DebugTypeEnum.General);
                    NewAutoPilot.SetRandomOffset(VectorHelper.RandomDistance(NewAutoPilot.OffsetPlanetMinTargetAltitude, NewAutoPilot.OffsetPlanetMaxTargetAltitude), 0, NewAutoPilot.Targeting.Target.GetEntity());
                }
                else
                {
                    //Logger.MsgDebug("Target Is Low", DebugTypeEnum.General);
                    NewAutoPilot.SetRandomOffset(NewAutoPilot.Targeting.Target.GetEntity());
                }
            }
            else
            {
                //Logger.MsgDebug("Target Is Space", DebugTypeEnum.General);
                NewAutoPilot.SetRandomOffset(NewAutoPilot.Targeting.Target.GetEntity());
            }

            LastOffsetCalculation = MyAPIGateway.Session.GameDateTime;
            NewAutoPilot.ActivateAutoPilot(AutoPilotType.RivalAI, NewAutoPilotMode.RotateToWaypoint | NewAutoPilotMode.ThrustForward, RemoteControl.GetPosition(), true, true, true);
        }
Ejemplo n.º 16
0
        public void LoadData()
        {
            var zoneArray = Root.ZoneSystem.ZoneArray;
            var zones     = zoneArray.GetFlatData();
            var resources = ResourcesToAdd.Select(resource => resource.AcquireResource <SparseArray <float> >().GetFlatData()).Union(
                ResourcesToAddRaw.Select(source =>
            {
                source.LoadData();
                var ret = source.GiveData();
                source.UnloadData();
                return(ret.GetFlatData());
            })
                ).ToArray();
            SparseArray <float> data;

            data = SaveRatesBasedOnPD ? ZoneSystemHelper.CreatePDArray <float>(zoneArray) : zoneArray.CreateSimilarArray <float>();
            var flatData = data.GetFlatData();

            for (int j = 0; j < resources.Length; j++)
            {
                VectorHelper.Add(flatData, 0, flatData, 0, resources[j], 0, flatData.Length);
            }
            Data = data;
        }
    protected virtual GameObject FindCloseObjectInRange(Vector2 p_globalPoint, float p_radius)
    {
        GameObject v_returnObject = null;

        if (PressRadius > 0)
        {
            float v_currentDistance = 9999999f;
            float v_angleStep       = 10f;
            for (float j = 0; j < 360.0f; j += v_angleStep)
            {
                Vector3      v_rotatedVector = VectorHelper.RotateZ(new Vector2(1, 0), j);
                RaycastHit2D v_hit           = Physics2D.Raycast(p_globalPoint, v_rotatedVector, p_radius);
                if (v_hit.transform != null && v_hit.transform.gameObject != null)
                {
                    if (v_hit.distance < v_currentDistance)
                    {
                        v_returnObject    = v_hit.transform.gameObject;
                        v_currentDistance = v_hit.distance;
                    }
                }
            }
        }
        return(v_returnObject);
    }
Ejemplo n.º 18
0
        public static List <Bullet> Spawn5Bullets(GeomCloneLevel currentLevel, Vector2 position, Vector2 direction)
        {
            Vector2 direction1 = Vector2.Transform(direction, Matrix.CreateRotationZ((float)(Math.PI / 180.0 * 1.1)));
            Vector2 direction2 = Vector2.Transform(direction, Matrix.CreateRotationZ((float)(-Math.PI / 180.0 * 1.1)));
            Vector2 direction3 = Vector2.Transform(direction, Matrix.CreateRotationZ((float)(Math.PI / 180.0 * 2.8)));
            Vector2 direction4 = Vector2.Transform(direction, Matrix.CreateRotationZ((float)(-Math.PI / 180.0 * 2.8)));

            Vector2 perp = VectorHelper.Perpendicular(direction);

            perp.Normalize();

            Vector2 transformedPosition = new Vector2(position.X * referenceWidth, position.Y * referenceHeight);

            Vector2 pos0 = transformedPosition + 5 * direction;
            Vector2 pos1 = transformedPosition + 5 * perp + 3 * direction;
            Vector2 pos2 = transformedPosition - 5 * perp + 3 * direction;
            Vector2 pos3 = transformedPosition + 6 * perp;
            Vector2 pos4 = transformedPosition - 6 * perp;

            Vector2 scale = new Vector2((float)1.0f / referenceWidth, (float)1.0f / referenceHeight);

            pos0 *= scale;
            pos1 *= scale;
            pos2 *= scale;
            pos3 *= scale;
            pos4 *= scale;

            List <Bullet> list = new List <Bullet>(2);

            list.Add(new Bullet(currentLevel, pos0, direction, 650));
            list.Add(new Bullet(currentLevel, pos1, direction1, 650));
            list.Add(new Bullet(currentLevel, pos2, direction2, 650));
            list.Add(new Bullet(currentLevel, pos3, direction3, 650));
            list.Add(new Bullet(currentLevel, pos4, direction4, 650));
            return(list);
        }
Ejemplo n.º 19
0
 public void IterationFinished(int iteration, int totalIterations)
 {
     //Min each OD to Zero
     MinZero(Matrix[0]);
     MinZero(Matrix[1]);
     // Apply the special generators
     if (SpecialGenerators.Length > 0)
     {
         var specialGenerationResults = Root.ZoneSystem.ZoneArray.CreateSquareTwinArray <float>().GetFlatData();
         for (int i = 0; i < SpecialGenerators.Length; i++)
         {
             SpecialGenerators[i].IncludeTally(specialGenerationResults);
         }
         // Now scale the by household iterations and integrate it back into the result matrix
         Parallel.For(0, specialGenerationResults.Length, i =>
         {
             VectorHelper.Multiply(specialGenerationResults[i], 0, specialGenerationResults[i], 0, _householdIterations, specialGenerationResults[i].Length);
             VectorHelper.Add(Matrix[0][i], 0, Matrix[0][i], 0, specialGenerationResults[i], 0, specialGenerationResults.Length);
         });
     }
     // write to disk
     new EmmeMatrix(ZoneSystem, Matrix[0]).Save(SOVMatrixSaveLocation, true);
     new EmmeMatrix(ZoneSystem, Matrix[1]).Save(HOVMatrixSaveLocation, true);
 }
Ejemplo n.º 20
0
                private float GetTotalLinkages(float[] row, float[] assigned, float[] total)
                {
                    int i    = 0;
                    var acc  = 0.0f;
                    var accV = Vector <float> .Zero;
                    var one  = Vector <float> .One;
                    var zero = Vector <float> .Zero;

                    for (; i < row.Length - Vector <float> .Count; i += Vector <float> .Count)
                    {
                        var eV    = new Vector <float>(total, i);
                        var aV    = new Vector <float>(assigned, i);
                        var ratio = VectorHelper.SelectIfFinite(aV / eV, Vector <float> .Zero);
                        accV += new Vector <float>(row, i) * Vector.Max((one - ratio), Vector <float> .Zero);
                    }
                    for (; i < row.Length; i++)
                    {
                        if (total[i] > 0)
                        {
                            acc += row[i] * Math.Max((1.0f - assigned[i] / total[i]), 0f);
                        }
                    }
                    return(acc + Vector.Dot(accV, one));
                }
        public override Vector2 Calculate(GameTime time)
        {
            CreateFeelers();

            float distToThisIP    = 0;
            float distToCLosestIP = float.MaxValue;
            Wall  closestWall     = null;

            Vector2 steeringForce, point, closestPoint;

            steeringForce = Vector2.Zero;
            closestPoint  = Vector2.Zero;

            foreach (Vector2 f in feelers)
            {
                foreach (Wall w in walls)
                {
                    if (VectorHelper.LineIntersection2D(Owner.Position, f, w.From, w.To, out distToThisIP, out point))
                    {
                        if (distToThisIP < distToCLosestIP)
                        {
                            closestWall  = w;
                            closestPoint = point;
                        }
                    }
                }

                if (closestWall != null)
                {
                    Vector2 overShoot = f - closestPoint;
                    steeringForce = closestWall.Normal * overShoot.Length();
                }
            }

            return(steeringForce);
        }
Ejemplo n.º 22
0
    int CalcSelected(Vector2 delta)
    {
        float dist = delta.magnitude;

        if (dist < minDist || dist > maxDist)
        {
            return(-1);
        }

        var startDelta = mouseStartDelta.ToVector2();

        if (Mathf.Approximately(delta.x, startDelta.x) && Mathf.Approximately(delta.y, startDelta.y))
        {
            return(-1);
        }
        else
        {
            mouseStartDelta = Vector3.zero;
        }

        float angle = VectorHelper.ToDegrees(delta) + angleOffset;

        return((Mathf.FloorToInt((angle + 360) % 360 / 90) * (clockwise ? -1 : 1) + intOffset + leaves.Length) % leaves.Length);
    }
Ejemplo n.º 23
0
        public NavStatus CalculatePath(Vec3 start, Vec3 end, out Vec3[] corners)
        {
            corners = null;

            NavStatus status = this._query.GetNearestPoint(start.ToVector3(), DEFAULT_SEARCH_EXTENTS, QUERY_FILTER,
                                                           out NavmeshPoint startNavmeshPoint);

            if (status != NavStatus.Sucess)
            {
                return(status);
            }

            status = this._query.GetNearestPoint(end.ToVector3(), DEFAULT_SEARCH_EXTENTS, QUERY_FILTER,
                                                 out NavmeshPoint endNavmeshPoint);
            if (status != NavStatus.Sucess)
            {
                return(status);
            }

            status = this._query.FindPath(startNavmeshPoint, endNavmeshPoint, QUERY_FILTER, this._tmpPath1, out int pathCount);
            if (status != NavStatus.Sucess)
            {
                return(status);
            }

            status = this._query.GetStraightPath(startNavmeshPoint.point, endNavmeshPoint.point, this._tmpPath1, 0, pathCount,
                                                 this._tmpPoints, null, null, out int straightCount);
            if (status != NavStatus.Sucess)
            {
                return(status);
            }

            corners = VectorHelper.ToVec3Array(ref this._tmpPoints, straightCount);

            return(NavStatus.Sucess);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Make a player explore a new tile (if possible)
        /// </summary>
        /// <param name="player">Player to explore</param>
        /// <returns>Was a tile explored?</returns>
        public bool PlayerExplore(Player player)
        {
            Vector3[] directions = VectorHelper.Vector3FlatDirections;
            directions = directions.OrderBy(a => UnityEngine.Random.value).ToArray();

            // Check if there is anything in each direction
            foreach (Vector3 direction in directions)
            {
                Vector3 newPos3 = VectorHelper.RoundVector(player.transform.position) + direction;
                Vector2 newPos  = new Vector2(newPos3.x, newPos3.z);

                List <GameObject> objects = Game.GridController.GetObjectsAt(newPos);
                if (objects.Count == 0)
                {
                    // Nothing here, generate tile here.
                    Vector3 pos = GetGameTilePositionFor(newPos);
                    Generator.GenerateTile((int)pos.x, (int)pos.y);

                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 25
0
    void OnDrawGizmosSelected()
    {
        if (!Application.isPlaying || !isOpen)
        {
            return;
        }

        Vector3 center = centerWorldPoint;

        UnityEditor.Handles.color = new Color(1, 1, 1, 0.1f);
        UnityEditor.Handles.DrawSolidDisc(center, Camera.main.transform.forward, minDist);
        UnityEditor.Handles.color = Color.red;
        UnityEditor.Handles.DrawWireDisc(center, Camera.main.transform.forward, minDist);
        UnityEditor.Handles.DrawWireDisc(center, Camera.main.transform.forward, maxDist);

        Gizmos.color = Color.red;
        Gizmos.DrawRay(center, Camera.main.transform.TransformVector(VectorHelper.FromDegrees(angleOffset)));
        Gizmos.DrawRay(center, Camera.main.transform.TransformVector(VectorHelper.FromDegrees(90 + angleOffset)));
        Gizmos.DrawRay(center, Camera.main.transform.TransformVector(VectorHelper.FromDegrees(180 + angleOffset)));
        Gizmos.DrawRay(center, Camera.main.transform.TransformVector(VectorHelper.FromDegrees(270 + angleOffset)));

        Gizmos.color = Color.white;
        Gizmos.DrawLine(center, Camera.main.transform.TransformPoint(centerLocalWorldPoint + mouseDelta));
    }
        public void Test()
        {
            JoystickOutput output;

            output.Pitch = 0.312312432f;
            output.Roll  = 0.512312432f;
            output.Yaw   = 0.912312432f;
            const float dt = 0.017001f;

            float pitchRate = output.Pitch * PhysicsConstants.MaxPitchRate;
            float rollRate  = output.Roll * PhysicsConstants.MaxRollRate;
            float yawRate   = output.Yaw * PhysicsConstants.MaxYawRate;

            Quaternion orient1 = Quaternion.Identity;
            Quaternion orient2 = Quaternion.Identity;

            for (int i = 0; i < 10000; i++)
            {
                float deltaPitch = (output.Pitch * PhysicsConstants.MaxPitchRate) * dt;
                float deltaRoll  = (output.Roll * PhysicsConstants.MaxRollRate) * dt;
                float deltaYaw   = (output.Yaw * PhysicsConstants.MaxYawRate) * dt;

                // Add deltas of pitch, roll and yaw to the rotation matrix
                orient1 = VectorHelper.AddPitchRollYaw(orient1, deltaPitch, deltaRoll, deltaYaw);

                deltaPitch = pitchRate * dt;
                deltaRoll  = rollRate * dt;
                deltaYaw   = yawRate * dt;
                orient2    = VectorHelper.AddPitchRollYaw(orient2, deltaPitch, deltaRoll, deltaYaw);
            }

            Assert.AreEqual(orient1.X, orient2.X, "X");
            Assert.AreEqual(orient1.Y, orient2.Y, "Y");
            Assert.AreEqual(orient1.Z, orient2.Z, "Z");
            Assert.AreEqual(orient1.W, orient2.W, "W");
        }
Ejemplo n.º 27
0
    // Update is called once per frame
    void Update()
    {
        prevPlayerPos = playerPos;
        playerPos     = rigidScript.Rig3D.position;

        if (Vector3.Distance(prevPlayerPos, playerPos) >= 5)
        {
            Destroy(this.gameObject);
        }

        //seek player
        Vector3 toTarget        = playerPos - transform.position;
        Vector3 desiredVelocity = toTarget.normalized * maxSpeed;
        Vector3 steeringForce   = desiredVelocity - velocity;

        ApplyForce(steeringForce);


        velocity           += acceleration;
        velocity            = VectorHelper.Clamp(velocity, maxSpeed);
        transform.position += velocity;

        gameObject.transform.rotation = Quaternion.LookRotation(velocity);
    }
Ejemplo n.º 28
0
    [Fact] public void Average()
    {
        Data_Generator dg  = new Data_Generator();
        int            len = dg.newInt(100);

        Vector[] vL = dg.newVectors(len);

        Vector exp = new Vector(0, 0, 0);

        for (int i = 0; i < len; i++)
        {
            exp.x += vL[i].x;
            exp.y += vL[i].y;
            exp.z += vL[i].z;
        }
        exp.x /= (float)len;
        exp.y /= (float)len;
        exp.z /= (float)len;

        VectorHelper vh  = new VectorHelper();
        Vector       act = vh.average(vL);

        test.vectorEqual(exp, act);
    }
Ejemplo n.º 29
0
    //delay goes from -90 to 90
    //-90 = all the way left
    //90 = all the way right
    void OnDrawGizmosSelected()
    {
        if (Application.isPlaying)
        {
            return;
        }
        else
        {
            if (isPlaying)
            {
                UnityEditor.Selection.objects = new UnityEngine.Object[0];
                UnityEditor.Selection.selectionChanged();
                isPlaying = false;
            }
        }

        if (startTime < 0f)
        {
            startTime = (Time.time + actualDelay);
        }



        if ((objects.Count == 0 || (objects.Count - 1) != GetEntireChildCount(transform)))
        {
            makeEditorPreviewTree(transform);
            GeneratePath();
        }

        //This gets us our world scale for an accurate rendering of the object
        Vector3   worldScale = transform.localScale;
        Transform parent     = transform.parent;

        while (parent != null)
        {
            worldScale = Vector3.Scale(worldScale, parent.localScale);
            parent     = parent.parent;
        }

        //We now have a world scale

        Vector3 position = this.transform.position;

        if (startPosition != Vector3.zero)
        {
            position = startPosition;
        }



        startTime += (Time.deltaTime / 2f);

        //startTime = startTime;
        float modifier = VectorHelper.HandleCurveList(path, startTime);

        objects[0].transform.position = position + ((horizontal) ? objects[0].transform.right * modifier : Vector3.zero) + ((vertical) ? objects[0].transform.up * modifier : Vector3.zero) + ((depth) ? objects[0].transform.forward * modifier : Vector3.zero);


        foreach (var obj in objects)
        {
            MeshFilter filter = obj.GetComponent <MeshFilter>();
            if (filter != null)
            {
                Gizmos.color = Color.red;
                Gizmos.DrawWireMesh(filter.sharedMesh, obj.transform.position, obj.transform.rotation, obj.transform.lossyScale);
            }
        }



        Gizmos.color = Color.green;
        Gizmos.DrawWireSphere(position + ((horizontal) ? this.transform.right * amplitude * Mathf.Sin(-90f * Mathf.Deg2Rad) : Vector3.zero) + ((vertical) ? this.transform.up * amplitude * Mathf.Sin(-90f * Mathf.Deg2Rad) : Vector3.zero) + ((depth) ? this.transform.forward * amplitude * Mathf.Sin(-90f * Mathf.Deg2Rad) : Vector3.zero), 0.5f);
        Gizmos.DrawWireSphere(position + ((horizontal) ? this.transform.right * amplitude * Mathf.Sin(90f * Mathf.Deg2Rad) : Vector3.zero) + ((vertical) ? this.transform.up * amplitude * Mathf.Sin(90f * Mathf.Deg2Rad) : Vector3.zero) + ((depth) ? this.transform.forward * amplitude * Mathf.Sin(90f * Mathf.Deg2Rad) : Vector3.zero), 0.5f);

        objectsGreen[0].transform.position = position + ((horizontal) ? transform.right * amplitude * Mathf.Sin(-90f * Mathf.Deg2Rad + delay * Mathf.Deg2Rad) : Vector3.zero) + ((vertical) ? transform.up * amplitude * Mathf.Sin(-90f * Mathf.Deg2Rad + delay * Mathf.Deg2Rad) : Vector3.zero) + ((depth) ? transform.forward * amplitude * Mathf.Sin(-90f * Mathf.Deg2Rad + delay * Mathf.Deg2Rad) : Vector3.zero);
        foreach (var obj in objectsGreen)
        {
            MeshFilter filter = obj.GetComponent <MeshFilter>();
            if (filter != null)
            {
                Gizmos.DrawWireMesh(filter.sharedMesh, obj.transform.position, obj.transform.rotation, obj.transform.lossyScale);
            }
        }
        Gizmos.color = Color.white;
        Gizmos.DrawLine(position + ((horizontal) ? this.transform.right * amplitude * Mathf.Sin(-90f * Mathf.Deg2Rad) : Vector3.zero) + ((vertical) ? this.transform.up * amplitude * Mathf.Sin(-90f * Mathf.Deg2Rad) : Vector3.zero) + ((depth) ? this.transform.forward * amplitude * Mathf.Sin(-90f * Mathf.Deg2Rad) : Vector3.zero), position + ((horizontal) ? this.transform.right * amplitude * Mathf.Sin(90f * Mathf.Deg2Rad) : Vector3.zero) + ((vertical) ? this.transform.up * amplitude * Mathf.Sin(90f * Mathf.Deg2Rad) : Vector3.zero) + ((depth) ? this.transform.forward * amplitude * Mathf.Sin(90f * Mathf.Deg2Rad) : Vector3.zero));
    }
Ejemplo n.º 30
0
        public override void MainBehavior()
        {
            if (RAI_SessionCore.IsServer == false)
            {
                return;
            }

            base.MainBehavior();

            //Logger.MsgDebug(Mode.ToString(), DebugTypeEnum.General);

            if (Mode != BehaviorMode.Retreat && Despawn.DoRetreat == true)
            {
                ChangeCoreBehaviorMode(BehaviorMode.Retreat);
                AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), NewAutoPilotMode.RotateToWaypoint | NewAutoPilotMode.LevelWithGravity | NewAutoPilotMode.ThrustForward | NewAutoPilotMode.WaterNavigation);
            }

            if (Mode == BehaviorMode.Init)
            {
                if (!AutoPilot.Targeting.HasTarget())
                {
                    ChangeCoreBehaviorMode(BehaviorMode.WaitingForTarget);
                    BehaviorTriggerD = true;
                }
                else
                {
                    ChangeCoreBehaviorMode(BehaviorMode.ApproachTarget);
                    AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), NewAutoPilotMode.RotateToWaypoint | NewAutoPilotMode.LevelWithGravity | NewAutoPilotMode.ThrustForward | NewAutoPilotMode.WaypointFromTarget | NewAutoPilotMode.WaterNavigation);
                }
            }

            if (Mode == BehaviorMode.WaitingForTarget)
            {
                if (AutoPilot.CurrentMode != AutoPilot.UserCustomModeIdle)
                {
                    AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), NewAutoPilotMode.LevelWithGravity);
                }

                if (AutoPilot.Targeting.HasTarget())
                {
                    ChangeCoreBehaviorMode(BehaviorMode.ApproachTarget);
                    AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), NewAutoPilotMode.RotateToWaypoint | NewAutoPilotMode.LevelWithGravity | NewAutoPilotMode.ThrustForward | NewAutoPilotMode.WaypointFromTarget | NewAutoPilotMode.WaterNavigation);
                }
                else if (Despawn.NoTargetExpire == true)
                {
                    Despawn.Retreat();
                    BehaviorTriggerD = true;
                }
            }

            if (!AutoPilot.Targeting.HasTarget() && Mode != BehaviorMode.Retreat && Mode != BehaviorMode.WaitingForTarget)
            {
                ChangeCoreBehaviorMode(BehaviorMode.WaitingForTarget);
                AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), NewAutoPilotMode.LevelWithGravity);
                BehaviorTriggerD = true;
            }

            //A - Stop All Movement
            if (BehaviorActionA)
            {
                BehaviorActionA = false;
                ChangeCoreBehaviorMode(BehaviorMode.WaitAtWaypoint);
                AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), NewAutoPilotMode.LevelWithGravity);
                WaitTime         = MyAPIGateway.Session.GameDateTime;
                BehaviorTriggerC = true;
            }

            //WaitAtWaypoint
            if (Mode == BehaviorMode.WaitAtWaypoint)
            {
                var timespan = MyAPIGateway.Session.GameDateTime - WaitTime;

                if (timespan.TotalSeconds >= AutoPilot.Data.WaypointWaitTimeTrigger)
                {
                    ChangeCoreBehaviorMode(BehaviorMode.WaitingForTarget);
                    BehaviorTriggerD = true;
                }
            }

            //Approach
            if (Mode == BehaviorMode.ApproachTarget)
            {
                bool inRange = false;

                if (!AutoPilot.InGravity() && AutoPilot.DistanceToTargetWaypoint < AutoPilot.Data.EngageDistanceSpace)
                {
                    inRange = true;
                }

                if (AutoPilot.InGravity() && AutoPilot.DistanceToTargetWaypoint < AutoPilot.Data.EngageDistancePlanet)
                {
                    inRange = true;
                }

                if (inRange)
                {
                    AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), NewAutoPilotMode.RotateToTarget | NewAutoPilotMode.LevelWithGravity | NewAutoPilotMode.WaypointFromTarget | NewAutoPilotMode.WaterNavigation);
                    ChangeCoreBehaviorMode(BehaviorMode.EngageTarget);
                    BehaviorTriggerA = true;
                }
            }

            //Engage
            if (Mode == BehaviorMode.EngageTarget)
            {
                bool outRange = false;

                if (!AutoPilot.InGravity() && AutoPilot.DistanceToTargetWaypoint > AutoPilot.Data.DisengageDistanceSpace)
                {
                    outRange = true;
                }

                if (AutoPilot.InGravity() && AutoPilot.DistanceToTargetWaypoint > AutoPilot.Data.DisengageDistancePlanet)
                {
                    outRange = true;
                }

                if (outRange)
                {
                    AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), NewAutoPilotMode.RotateToWaypoint | NewAutoPilotMode.LevelWithGravity | NewAutoPilotMode.ThrustForward | NewAutoPilotMode.WaypointFromTarget | NewAutoPilotMode.WaterNavigation);
                    ChangeCoreBehaviorMode(BehaviorMode.ApproachTarget);
                    BehaviorTriggerB = true;
                }
            }

            //Retreat
            if (Mode == BehaviorMode.Retreat)
            {
                if (Despawn.NearestPlayer?.Controller?.ControlledEntity?.Entity != null)
                {
                    //Logger.AddMsg("DespawnCoordsCreated", true);
                    AutoPilot.SetInitialWaypoint(VectorHelper.GetDirectionAwayFromTarget(this.RemoteControl.GetPosition(), Despawn.NearestPlayer.GetPosition()) * 1000 + this.RemoteControl.GetPosition());
                }
            }
        }