Exemple #1
0
 static void Main(string[] args)
 {
     Vectors route = new Vectors (); 
     route.Add(new Vector (2.0, 90.0)); 
     route.Add(new Vector (1.0, 180.0)) ; 
     route.Add(new Vector (0.5, 45.0)); 
     route.Add(new Vector (2.5, 315.0)); 
     Console.WriteLine(route.Sum()); 
     Comparison<Vector> sorter = new Comparison<Vector>(VectorDelegates.Compare); 
     route.Sort(sorter); 
     Console.WriteLine(route.Sum ()); 
     Predicate<Vector> searcher = new Predicate<Vector>(VectorDelegates.TopRightQuadrant); 
     Vectors topRightQuadrantRoute = new Vectors(route.FindAll(searcher)); 
     Console.WriteLine(topRightQuadrantRoute.Sum()); 
     Console.ReadKey(); 
 }
Exemple #2
0
        public override void Update(GameTime gameTime)
        {
            Vector2 loc = Vectors.ConvertPointToVector2(DstRect.Center);

            //Add Smoke and fire
            TGPAContext.Instance.ParticleManager.AddParticle(new Smoke(loc, RandomMachine.GetRandomVector2(-1f, 1f, -2f, 2f),
                                                                       0.30f, 0.30f, 0.30f, 1f,
                                                                       RandomMachine.GetRandomFloat(0.01f, .03f),
                                                                       RandomMachine.GetRandomInt(0, 4)), true);

            Fire f = new Fire(loc, RandomMachine.GetRandomVector2(-1f, 1f, -2f, 2f),
                              0.25f, RandomMachine.GetRandomInt(0, 4));

            TGPAContext.Instance.ParticleManager.AddParticle(f, true);

            base.Update(gameTime);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ProbabilityDistribution"/> class.
        /// </summary>
        /// <param name="weights">The probabilities of possible outcomes.</param>
        /// <param name="random">The random number generator.</param>
        public ProbabilityDistribution(IList <float> weights, Random random)
        {
            if (weights == null)
            {
                throw new ArgumentNullException(nameof(weights));
            }

            this.random = new RandomGeneratorF(random);

            this.pdf = weights.ToArray();
            float sum = Vectors.CumulativeSum(this.pdf.Length, this.pdf, 0);

            if (sum != 0.0f)
            {
                Mathematics.DivC(this.pdf.Length, sum, this.pdf, 0);
            }
        }
Exemple #4
0
    // Dot Product
    public static float DotProduct(Vectors A, Vectors B, bool Normalise = false)
    {
        float r = 0.0f;

        Vectors TempA = A;
        Vectors TempB = B;

        // Normalise vectors if needed
        if (Normalise)
        {
            TempA = TempA.Normalize();
            TempB = TempB.Normalize();
        }

        r = (TempA.x * TempB.x) + (TempA.y * TempB.y) + (TempA.z * TempB.z);
        return(r);
    }
Exemple #5
0
        public void Test_Others() // TODO
        {
            Vector v1 = new Vector(1, 2, 3, 4, 5);

            // 出力
            Assert.That(v1.ToArray(), Is.EqualTo(new[] { 1.0, 2, 3, 4, 5 }));
            string s   = v1.ToString();
            string csv = Vectors.ToCsv(v1);

            v1 = Vector.Fill(10, 1);
            Assert.AreEqual(10, v1.Size);
            Assert.AreEqual(new Vector(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), v1);

            v1.Flip();          // 符号反転
            v1.Zero();          // 全ての要素を0
            Assert.AreEqual(new Vector(new Size(10)).Zero(), v1);
        }
Exemple #6
0
        /// <summary>
        ///  Returns the next bond vector needed for drawing an extended linear chain of
        ///  atoms. It assumes an angle of 120 deg for a nice chain layout and
        ///  calculates the two possible placments for the next atom. It returns the
        ///  vector pointing farmost away from a given start atom.
        /// </summary>
        /// <param name="atom">An atom for which the vector to the next atom to draw is calculated</param>
        /// <param name="previousAtom">The preceding atom for angle calculation</param>
        /// <param name="distanceMeasure">A point from which the next atom is to be farmost away</param>
        /// <param name="trans">if true E (trans) configurations are built, false makes Z (cis) configurations</param>
        /// <returns>A vector pointing to the location of the next atom to draw</returns>
        public Vector2 GetNextBondVector(IAtom atom, IAtom previousAtom, Vector2 distanceMeasure, bool trans)
        {
            Debug.WriteLine("Entering AtomPlacer.GetNextBondVector()");
            Debug.WriteLine($"Arguments are atom: {atom}, previousAtom: {previousAtom}, distanceMeasure: {distanceMeasure}");
            var a = previousAtom.Point2D;
            var b = atom.Point2D;

            if (IsColinear(atom, Molecule.GetConnectedBonds(atom)))
            {
                return(b.Value - a.Value);
            }

            var angle    = GeometryUtil.GetAngle(previousAtom.Point2D.Value.X - atom.Point2D.Value.X, previousAtom.Point2D.Value.Y - atom.Point2D.Value.Y);
            var addAngle = Vectors.DegreeToRadian(120);

            if (!trans)
            {
                addAngle = Vectors.DegreeToRadian(60);
            }
            if (IsColinear(atom, Molecule.GetConnectedBonds(atom)))
            {
                addAngle = Vectors.DegreeToRadian(180);
            }

            angle += addAngle;
            var vec1   = new Vector2(Math.Cos(angle), Math.Sin(angle));
            var point1 = atom.Point2D.Value;

            point1 += vec1;
            var distance1 = Vector2.Distance(point1, distanceMeasure);

            angle += addAngle;
            var vec2   = new Vector2(Math.Cos(angle), Math.Sin(angle));
            var point2 = atom.Point2D.Value;

            point2 += vec2;
            var distance2 = Vector2.Distance(point2, distanceMeasure);

            if (distance2 > distance1)
            {
                Debug.WriteLine("Exiting AtomPlacer.GetNextBondVector()");
                return(vec2);
            }
            Debug.WriteLine("Exiting AtomPlacer.GetNextBondVector()");
            return(vec1);
        }
        /// <summary>
        /// Битовая инверсия.
        /// </summary>
        private static Vectors InversionBit(Vectors Child)
        {
            Vectors MutantChild = Child; /// Ребенок мутант.

            for (int i = 0; i < Child.Size; i++)
            {
                for (int j = 0; j < Vectors.BitsCount; j++)
                {
                    if (InversionProbability > RandomNumber.NextDouble())
                    {
                        int swapMask = 1 << j;
                        MutantChild[i] = Convert.ToInt32(MutantChild[i]) ^ swapMask;
                    }
                }
            }
            return(MutantChild);
        }
Exemple #8
0
 //------------------------------------------------------------------------------
 // modify
 public void modify(double x, double y, double z)
 {
     _point[_v][_u] += new Vectors(x, y, z);
     for (int v = _v - 2; v < _v + 2; v++)
     {
         if (v >= 0 && v < _n - 1)
         {
             for (int u = _u - 2; u < _u + 2; u++)
             {
                 if (u >= 0 && u < _m - 1)
                 {
                     _patch[v][u].modify();
                 }
             }
         }
     }
 }
Exemple #9
0
        /*
         *
         * Options:
         * - ground (water, traps)
         * - recursion
         * - size / depth (puis avant)
         * - other content : Z, animal, torch, lights ...
         *
         */


        public static IEnumerator Rift(EntityPlayer player, Emplacement place, OptionEffect options)
        {
            /*
             * Laisse des blocks tomber au dessus ? just changed  erase="yes"
             * (longueur 1, hauteur (profonfeur), replicats)
             */
            EntityPlayerLocal epl = player as EntityPlayerLocal;

            epl.cameraTransform.SendMessage("ShakeBig");
            yield return(new WaitForSeconds(1f));

            BlockSetter setter    = new BlockSetter(options.OptionBlock);
            Vector3     direction = Vectors.Copy(place.direction);

            direction.y = 0;
            direction   = direction.normalized;

            Vector3i start = Geo3D.Surface(place.ipos);

            for (int k = 0; k < options.OptionShape.shape.z; k++)
            {
                Vector3 kdirection = direction + Vectors.Float.Randomize(GameManager.Instance.World.GetGameRandom(), 0.2f);
                // IntLine traj = new IntLine(start, direction); //east
                IEnumerable <Vector3i> segment = IntLine.Segment(Vectors.ToFloat(start), kdirection, 0, options.OptionShape.shape.x);
                Vector3i prev    = new Vector3i();
                bool     hasprev = false;
                foreach (Vector3i where in segment)
                {
                    Vector3i Swhere = Geo3D.Surface(where);
                    setter.Apply(Swhere);
                    if (hasprev)
                    {
                        for (int creuse = 1; creuse < options.OptionShape.shape.y; creuse++)
                        {
                            setter.Apply(prev + creuse * Vectors.Down);
                        }
                    }
                    setter.Push();
                    start = Swhere;
                    yield return(new WaitForEndOfFrame());

                    hasprev = true; prev = Swhere;
                }
                yield return(new WaitForSeconds(1f));
            }
        }
Exemple #10
0
        public override IEnumerator Regen(EntityPlayer player, Vector3i zchunk, int iniguess)
        {
            Bounds        bounds   = ZChunk.Bounds4(zchunk, iniguess);
            List <Entity> existing = GameManager.Instance.World.GetEntitiesInBounds(
                EntityGhost.Concretes[this.concreteIdx],
                bounds,
                new List <Entity>()
                );

            yield return(Iterating.Repeater.Frame); // listent may be costly

            Vector3i min = Vectors.ToInt(bounds.min);
            Vector3i max = Vectors.ToInt(bounds.max);

            int current = existing.Count;
            int gen     = ZChunk.Size(this.gen);
            // gen = 1; // DEBUG
            int regen = ZChunk.Size(this.regen);
            int iniy  = (int)Math.Floor(player.GetPosition().y);

            Zombiome.Routines.Start(Routines.IfNotRunning(
                                        LockRenew,
                                        EffectExisting(player, existing)
                                        ), "Ghost-Existing");

            int nnew = Math.Min(limit_new, gen - current);

            Entity[] Tracker = new Entity[] { null };
            if (current < regen)
            {
                Printer.Log(45, "Ghost regen", regen, current, gen, "=>", gen - current);
                for (int k = 0; k < nnew; k++)
                {
                    Vector3i pos = new Vector3i(rand.RandomRange(min.x, max.x), 0, rand.RandomRange(min.z, max.z));
                    pos = Geo3D.Surface(pos, iniy);
                    if (GameManager.Instance.World.GetTerrainHeight(pos.x, pos.z) > 2)
                    {
                        Printer.Log(40, "Ghost", pos, opt.OptionEntity.entity, opt.OptionEntity.buff);
                        Emplacement place = Emplacement.At(Vectors.ToFloat(pos) + 2f * Vectors.Float.UnitY, Vectors.Float.UnitY);
                        GhostData   gdata = (ghost_type == "") ? this.GhostData : GhostData.Ghosts[ghost_type];
                        yield return(EntityGhost.Create(gdata, place, opt.OptionEntity.entity));
                    }
                    yield return(Repeater.Yield);
                }
            }
        }
Exemple #11
0
    public override void Effect1(EntityPlayer player, Emplacement place,  OptionEffect opt) {
        DecoSearch.Search(player, 20, 3);

        int nsteps = Math.Min(3, DecoSearch.Count);
        for (int k=0; k<nsteps; k++) {
            BlockPos deco = DecoSearch.Dequeue();
            if (deco == null) continue;
            Vector3i ppos = Vectors.ToInt(player.GetPosition());
            if (Math.Abs(ppos.x - deco.Pos.x) + Math.Abs(ppos.z - deco.Pos.z) > DecoSearch.radius){
                Printer.Log(85, "MovingDeco: too far !", deco, ppos);
                continue;
            }
            string item = Deco2Proj(deco.Value.Block);
            if (item == "") continue;
            Zombiome.Routines.Start(Fly(deco, item), "FlyDeco");
        }
    }
Exemple #12
0
        /// <summary>
        /// Reduces the height of the <see cref="Image"/> by the factor of 4.
        /// </summary>
        /// <returns>The scaled <see cref="Image"/>.</returns>
        public Image Reduce1x4()
        {
            if (this.BitsPerPixel != 1)
            {
                throw new NotSupportedException(Properties.Resources.E_UnsupportedDepth_1bpp);
            }

            Image dst = new Image(
                this.Width,
                (this.Height + 3) / 4,
                this.BitsPerPixel,
                this.HorizontalResolution,
                this.VerticalResolution / 4);

            int stride = this.Stride;

            ulong[] bitssrc = this.Bits;
            ulong[] bitsdst = dst.Bits;

            int offsrc = 0;
            int offdst = 0;

            for (int i = 0, ii = this.Height / 4; i < ii; i++, offsrc += 4 * stride, offdst += stride)
            {
                Vectors.Or(stride, bitssrc, offsrc, bitssrc, offsrc + stride, bitssrc, offsrc + (2 * stride), bitssrc, offsrc + (3 * stride), bitsdst, offdst);
            }

            switch (this.Height % 4)
            {
            case 1:
                Vectors.Copy(stride, bitssrc, offsrc, bitsdst, offdst);
                break;

            case 2:
                Vectors.Or(stride, bitssrc, offsrc, bitssrc, offsrc + stride, bitsdst, offdst);
                break;

            case 3:
                Vectors.Or(stride, bitssrc, offsrc, bitssrc, offsrc + stride, bitssrc, offsrc + (2 * stride), bitsdst, offdst);
                break;
            }

            dst.AppendTransform(new MatrixTransform(1.0, 0.25));
            return(dst);
        }
        void Section4_2()
        {
            // triangle pattern
            int     s                 = 63468;
            int     e                 = 63939;
            float   patternRadius     = 300;
            float   scale             = 0.6f;
            float   relativeRingScale = 0.5f;
            Vector2 patternPosition   = Vectors.Centre + Vectors.polar(-Math.PI / 6, patternRadius);

            SpriteSet outer = MakeOuterRing(s, e, patternPosition, patternRadius, scale);
            SpriteSet inner = MakeInnerRing(s, e, patternPosition, patternRadius * relativeRingScale, scale);

            SpriteSet extension = layer.CreateSpriteSet();

            for (int i = 0; i < 6; i++)
            {
                var ring = Patterns.Circle2D(
                    patternPosition,
                    patternRadius * 3,
                    (float)-Math.PI / 3,
                    5 * (float)Math.PI / 6
                    );
                extension += MakeOuterRing(s, e, ring(i), patternRadius, scale);
            }
            for (int i = 0; i < 6; i++)
            {
                var ring = Patterns.Circle2D(
                    patternPosition,
                    patternRadius * (float)Math.Sqrt(3),
                    (float)-Math.PI / 3,
                    4 * (float)Math.PI / 6
                    );
                extension += MakeInnerRing(s, e, ring(i), patternRadius * relativeRingScale, scale);
            }

            SpriteSet trianglePattern = inner + outer + extension;

            float zoomScale = 0.9f;
            float cutScale  = 0.9f;

            //trianglePattern.MoveRelative(s, Vector2.Zero);
            trianglePattern.Scale(OsbEasing.None, s, s + 3 * Timing.beat(s) / 2, cutScale, cutScale * zoomScale, Vectors.Centre);
            //trianglePattern.MoveRelative(OsbEasing.None, s, s + 3 * Timing.beat(s) / 2, Vector2.Zero, Vectors.down(patternRadius));
        }
Exemple #14
0
        public void ReCalibrateCells()
        {
            //Log.Message("Recalibrate");
            this.CellsToProtect = new List <IntVec3>();

            if (this.m_StructuralIntegrityMode)
            {
                IEnumerable <IntVec3> _AllSquares = GenRadial.RadialCellsAround(this.Position, this.m_Field_Radius, false);

                foreach (IntVec3 _Square in _AllSquares)
                {
                    // Log.Message("Testing:" + _Square.ToString());
                    List <Thing> _Things = this.Map.thingGrid.ThingsListAt(_Square);

                    for (int i = 0, l = _Things.Count(); i < l; i++)
                    {
                        if (_Things[i] is Building)
                        {
                            Building building = (Building)_Things[i];

                            if (isBuildingValid(building))
                            {
                                this.CellsToProtect.Add(_Square);
                                i = int.MaxValue - 1;
                            }
                        }
                    }
                }
            }
            else
            {
                IEnumerable <IntVec3> _AllSquares = GenRadial.RadialCellsAround(this.Position, this.m_Field_Radius, false);

                foreach (IntVec3 _Square in _AllSquares)
                {
                    //if (Vectors.VectorSize(_Square) >= (float)this.m_Field_Radius - 1.5f)
                    if (Vectors.EuclDist(_Square, this.Position) >= (float)this.m_Field_Radius - 1.5f)
                    {
                        this.CellsToProtect.Add(_Square);
                    }
                }
            }
            //this.m_CellsToProtect
            //if (Vectors.VectorSize(square) >= (float)this.m_shieldShieldRadius - 1.5f)
        }
Exemple #15
0
        public static void VectorExamples()
        {
            var v = new Vectors(5);

            v.Show(); // (       0       0       0       0       0       )

            v = new Vectors(5, 1.0);
            v.Show(); // (       1       1       1       1       1       )

            v = new Vectors(1, 2, 3, 4, 5, 6, 7, 9.5, -2, 3);
            v.Show(); // (       1       2       3       4       5       6       7       9,5     -2      3       )

            v = new Vectors(new double[] { 1, 2, 3, -3, -2, -1, 0 });
            v.Show(); // (       1       2       3       -3      -2      -1      0       )


            v[6].Show();                                         // 0

            v.EuqlidNorm.Show();                                 // 0,7559289460184545

            v.Normalize(0, 1).Show();                            // (       0,6666666666666666      0,8333333333333333      1       0       0,16666666666666666     0,3333333333333333     0,5      )

            v.Range.Show();                                      // 6

            v.SubVector(4).Show();                               // (       1       2       3       -3      )

            v.Average.Show();                                    // 1,7142857142857142

            v.Contain(3).Show();                                 // True

            v.Normalize(-0.5, 0.5).ToRationalStringTab().Show(); // (       1/6     1/3     1/2     -1/2    -1/3    -1/6    0       )

            var p = Vectors.Create(dim: 7, min: 0, max: 2);

            p.Show(); // (       1,4585359040647745      1,7510524201206863      1,4706563879735768      0,45403700647875667     0,022686069831252098    1,9943826524540782      0,3851787596940994      )

            Vectors.Mix(v, p).Show();
            // (       1       1,4585359040647745      2       1,7510524201206863      3       1,4706563879735768      -3      0,45403700647875667      -2      0,022686069831252098    -1      1,9943826524540782      0       0,3851787596940994      )

            (v + p).Show();                                                  // (       2,4585359040647745      3,7510524201206863      4,470656387973577       -2,5459629935212433     -1,977313930168748      0,9943826524540782      0,3851787596940994      )
            (v * p).Show();                                                  // 5,970744096674025
            Vectors.CompMult(v, p).Show();                                   // (       1,4585359040647745      3,5021048402413726      4,41196916392073        -1,36211101943627       -0,045372139662504196   -1,9943826524540782     0       )

            (2.4 * v.AbsVector - p / 2).Sort.BinaryApproxSearch(1.5).Show(); // 1,4028086737729608
        }
Exemple #16
0
        public float[] Transform(
            IVectorPack <float> x,
            IList <float> weights,
            bool normalize,
            float[] result,
            CancellationToken cancellationToken)
        {
            if (result == null)
            {
                result = new float[this.K];
            }

            if (weights == null)
            {
                for (int i = 0, ii = x.Count, len = x.Length, off = 0; i < ii; i++, off += len)
                {
                    int cluster = this.Assign(new DenseVectorProxyF(len, x.X, off));
                    result[cluster] += 1.0f;
                }
            }
            else
            {
                if (weights.Count != x.Count)
                {
                    throw new ArgumentException("The number of weights must match the number of input vectors.", nameof(weights));
                }

                for (int i = 0, ii = x.Count, len = x.Length, off = 0; i < ii; i++, off += len)
                {
                    int cluster = this.Assign(new DenseVectorProxyF(len, x.X, off));
                    result[cluster] += weights[i];
                }
            }

            if (normalize)
            {
                float sum = Vectors.Sum(result.Length, result, 0);
                if (sum != 0.0f)
                {
                    Mathematics.DivC(result.Length, sum, result, 0);
                }
            }

            return(result);
        }
Exemple #17
0
        /// <summary>
        /// Called when a new player enters, and when scene changes occur
        /// </summary>
        /// <param name="observers">List of players to be updated.  Modify this set with all the players that can see this object</param>
        /// <param name="initial">True if this is the first time the method is called for this object</param>
        /// <returns>True if this component calculated the list of observers</returns>
        public override void OnRebuildObservers(HashSet <NetworkConnection> observers, bool initial)
        {
            //If force hidden then return without adding any observers.
            if (_forceHidden)
            {
                return;
            }

            Vector3 position = transform.position;

            foreach (NetworkConnectionToClient conn in NetworkServer.connections.Values)
            {
                if (conn == null || conn.identity == null)
                {
                    continue;
                }

                //Check only against local player object.
                if (_localPlayerOnly)
                {
                    if (Vectors.FastSqrMagnitude(position - conn.identity.transform.position) < _squaredVisibilityRange)
                    {
                        observers.Add(conn);
                    }
                }
                //Include all player objects.
                else
                {
                    bool add = false;
                    foreach (NetworkIdentity netId in conn.clientOwnedObjects)
                    {
                        if (Vectors.FastSqrMagnitude(netId.transform.position - transform.position) < _squaredVisibilityRange)
                        {
                            add = true;
                            break;
                        }
                    }
                    //If any objects are in range than add to observers.
                    if (add)
                    {
                        observers.Add(conn);
                    }
                }
            }
        }
Exemple #18
0
        public static IEnumerator Ensure()
        {
            /* Call this and wait for finish whenever prior to using the global ghost */
            EntityPlayerLocal player = GameManager.Instance.World.GetLocalPlayers()[0];
            Bounds            area   = BoundsUtils.BoundsForMinMax(-2, -1, -2, 2, 1, 2);

            while (true)
            {
                Vector3 ppos = Vectors.Copy(player.GetPosition());
                area.center = ppos; // will be surfaced anyway
                pool.Update(area);  // update in any case to invalidate
                if (pool.Entities[0] != null)
                {
                    yield break;
                }
                yield return(Yield);
            }
        }
Exemple #19
0
    void Start()
    {
        _walkTimer              = WalkTimer;
        MoovingLeft             = true;
        CurrentHealth           = MaxHealth;
        Speed                   = NormalSpeed;
        HelthBeforeTakingDamage = CurrentHealth;
        _timeBtwDamageCurrent   = TimeBtwDamage;
        _castTimer              = CastTimer;
        _vectors                = GetComponent <Vectors>();
        _rb              = GetComponent <Rigidbody2D>();
        _enemyBodyColor  = GetComponent <SpriteRenderer>();
        PlayerTransform  = GameObject.FindGameObjectWithTag("Player").GetComponent <Transform>();
        PlayerController = GameObject.FindGameObjectWithTag("Player").GetComponent <PlayerController>();


        Physics2D.queriesStartInColliders = false;
    }
Exemple #20
0
        /// <summary>
        /// Populates the corners of a polygon with atoms. Used to place atoms in a
        /// geometrically regular way around a ring center or another atom. If this is
        /// used to place the bonding partner of an atom (and not to draw a ring) we
        /// want to place the atoms such that those with highest "weight" are placed
        /// far-most away from the rest of the molecules. The "weight" mentioned here is
        /// calculated by a modified Morgan number algorithm.
        /// </summary>
        /// <param name="atoms">All the atoms to draw</param>
        /// <param name="thetaBeg">A start angle (in radians), giving the angle of the most clockwise                  atom which has already been placed</param>
        /// <param name="thetaStep">An angle (in radians) to be added for each atom from                  atomsToDraw</param>
        /// <param name="center">The center of a ring, or an atom for which the partners are to be placed</param>
        /// <param name="radius">The radius of the polygon to be populated: bond length or ring radius</param>
        public static void PopulatePolygonCorners(IEnumerable <IAtom> atoms, Vector2 center, double thetaBeg, double thetaStep, double radius)
        {
            double theta = thetaBeg;

            Debug.WriteLine($"populatePolygonCorners(numAtoms={atoms.Count()}, center={center}, thetaBeg={Common.Mathematics.Vectors.RadianToDegree(thetaBeg)}, r={radius}");

            foreach (var atom in atoms)
            {
                theta += thetaStep;
                var x    = Math.Cos(theta) * radius;
                var y    = Math.Sin(theta) * radius;
                var newX = x + center.X;
                var newY = y + center.Y;
                atom.Point2D  = new Vector2(newX, newY);
                atom.IsPlaced = true;
                Debug.WriteLine($"populatePolygonCorners - angle={Vectors.RadianToDegree(theta)}, newX={newX}, newY={newY}");
            }
        }
Exemple #21
0
        public override void Update(GameTime gameTime)
        {
            //Aim a player
            int rand = RandomMachine.GetRandomInt(0, 1);

            if ((rand == 0) && (TGPAContext.Instance.Player2 != null))
            {
                fireAngle = Angles.GetAngle(Vectors.ConvertPointToVector2(armDst.Center), Vectors.ConvertPointToVector2(TGPAContext.Instance.Player2.DstRect.Center));
            }
            else
            {
                fireAngle = Angles.GetAngle(Vectors.ConvertPointToVector2(armDst.Center), Vectors.ConvertPointToVector2(TGPAContext.Instance.Player1.DstRect.Center));
            }

            fireAngle -= (float)(Math.PI / 2);

            base.Update(gameTime);
        }
Exemple #22
0
 public void DrawField(Vector3 center)
 {
     if (this.status != enumShieldStatus.Charging && this.status != enumShieldStatus.Sustaining && (this.status != enumShieldStatus.Loading || this.shieldRecoverWarmup - this.warmupTicksCurrent >= 60))
     {
         return;
     }
     if (this.shieldStructuralIntegrityMode)
     {
         foreach (IntVec3 square in this.squares)
         {
             this.DrawSubField(Vectors.IntVecToVec(square), 0.8f);
         }
     }
     else
     {
         this.DrawSubField(center, (float)this.shieldShieldRadius);
     }
 }
Exemple #23
0
        //------------------------------------------------------------------------------
        public override double DistLMA(Vectors x, double[] a)
        {
            // x-a
            Vectors s = new Vectors(x._X - a[0], x._Y - a[1], x._Z - a[2]);
            //
            double g = Math.Abs(s._X * a[3] + s._Y * a[4] + s._Z * a[5]);
            double f = s.dot(s) - (g * g);

            if (f <= C.CONST.EPSILON)
            {
                f = 0.0d;
            }
            else
            {
                f = Math.Sqrt(f);
            }
            return(Math.Cos(a[6]) * f - Math.Sin(a[6]) * g);
        }
Exemple #24
0
        /// <summary>
        /// Method assumes that host vector can't have host vector
        /// If this is not correct algorithm shall be improved
        /// using validation methods above
        /// </summary>
        public void SetPostingOrder()
        {
            //save original order before post
            int order = 0;

            foreach (var vector in Vectors)
            {
                vector.intOriginalOrder = order++;
            }
            //set post order
            order = 0;
            //vectors without host vectors must be posted firstly
            foreach (var vector in Vectors.Where(v => v.HostVector == null))
            {
                vector.intPostOrder = order++;
            }
            Vectors.Sort(new[] { "intPostOrder" });
        }
Exemple #25
0
    // Set Orbit vertex data for current position
    void setOrbit()
    {
        // Grab position along orbit
        Vectors orbitPosition = orbit.orbit.Create(Oprogress, RotationOrigin);

        // Sort out matrix conversion
        Matrix4X4 yawMatrix   = Matrix4X4.CreateYaw(orbit.yaw);
        Matrix4X4 pitchMatrix = Matrix4X4.CreatePitch(orbit.pitch);
        Matrix4X4 rollMatrix  = Matrix4X4.CreateRoll(orbit.roll);

        Vectors rollVertex  = rollMatrix * orbitPosition;
        Vectors pitchVertex = pitchMatrix * rollVertex;
        Vectors yawVertex   = yawMatrix * pitchVertex;

        // Set position to this position
        CurrentPosition = yawVertex;
        //Debug.Log(orbitPosition.x + " " + orbitPosition.y + " " + orbitPosition.z);
    }
Exemple #26
0
        /// <summary>
        /// Получить минимум функции, посчитанный роевым методом
        /// </summary>
        /// <param name="f">Целевая функция</param>
        /// <param name="n">Размерность области определения целевой функции</param>
        /// <param name="min">Минимальное возможное значение каждого аргумента</param>
        /// <param name="max">Максимальное возможное значение каждого аргумента</param>
        /// <param name="eps">Допустимая погрешность</param>
        /// <param name="countpoints">Количество пчёл в рое</param>
        /// <param name="maxcountstep">Максимальное число неудачных итераций метода (подряд)</param>
        /// <param name="center">Центр распредления точек</param>
        /// <param name="maxiter">Максимальное число итераций метода</param>
        /// <returns></returns>
        public static Tuple <Vectors, double> GetGlobalMin(Func <Vectors, double> f, int n = 1, double min = -1e12, double max = 1e12, double eps = 1e-10, int countpoints = 1000, int maxcountstep = 100, Vectors center = null, int maxiter = 150)
        {
            Vectors minimum = new Vectors(n, min);
            Vectors maximum = new Vectors(n, max);

            Hive hive;

            if (center == null)
            {
                hive = new Hive(minimum, maximum, f, countpoints);
            }
            else
            {
                hive = new Hive(minimum + center, maximum + center, f, countpoints, center);
            }

            return(Gets(hive, eps, maxcountstep, maxiter));
        }
    void Start()
    {
        MoovingLeft             = true;
        CurrentHealth           = MaxHealth;
        Speed                   = NormalSpeed;
        HelthBeforeTakingDamage = CurrentHealth;
        _timeBtwDamageCurrent   = TimeBtwDamage;
        TimeBtwLaunchCurrent    = TimeBtwLaunch;
        AttackAnimation.GetComponent <Animation>();
        _distanseToPlayer = GetComponent <Vectors>();
        _rb              = GetComponent <Rigidbody2D>();
        _enemyBodyColor  = GetComponent <SpriteRenderer>();
        PlayerTransform  = GameObject.FindGameObjectWithTag("Player").GetComponent <Transform>();
        PlayerController = GameObject.FindGameObjectWithTag("Player").GetComponent <PlayerController>();


        Physics2D.queriesStartInColliders = false;
    }
Exemple #28
0
        public override void PermaActive()
        {
            base.PermaActive();

            if (!R.IsReady() || Player.CountEnemiesInRange(1100) == 0)
            {
                WhyIDidThatAddonInsec = false;
            }

            R.Width = 133 * (3 + R.Level);

            if (R.IsReady() && Game.Time - LastQTime > 0.1f && Game.Time - LastQTime < 1)
            {
                Player.Spellbook.CastSpell(SpellSlot.R, Vectors.CorrectSpellRange(Game.CursorPos, R.Range));
            }

            if (WhyIDidThatAddonInsec)
            {
                Orbwalker.DisableAttacking = true; Orbwalker.DisableMovement = true;
            }
            else
            {
                Orbwalker.DisableAttacking = false; Orbwalker.DisableMovement = false;
            }

            var Target = TargetSelector.GetTarget(Q.Range, DamageType.Magical);

            if (Target == null)
            {
                return;
            }

            if (R.IsReady() && Player.Mana >= GetFuckingInsecMana(Target))
            {
                if (misc.IsActive("insec.normal"))
                {
                    Insec(Target);
                }
                else if (misc.IsActive("insec.godlike"))
                {
                    WhyInsec(Target);
                }
            }
        }
Exemple #29
0
    private static void ShowSurface(List <string> _params)
    {
        EntityPlayerLocal player = GameManager.Instance.World.GetLocalPlayers()[0];
        Vector3i          pos    = Vectors.ToInt(player.GetPosition());
        Vector3i          s;

        if (_params.Count > 0)
        {
            pos.x = int.Parse(_params[0]);
            pos.y = int.Parse(_params[1]);
            pos.z = int.Parse(_params[2]);
        }

        // int dx = 100;
        // pos.x = pos.x + dx;

        Printer.Print("GetTerrainHeight", GameManager.Instance.World.GetTerrainHeight(pos.x, pos.z));
        s = Geo3D.Surface(pos, -1); Printer.Print("pos", pos, "@", -1, "->", s);
        s = Geo3D.Surface(pos, -2); Printer.Print("pos", pos, "@", -2, "->", s);

        pos.y = pos.y + 1;
        s     = Geo3D.Surface(pos, -1); Printer.Print("pos", pos, "@", -1, "->", s);
        s     = Geo3D.Surface(pos, -2); Printer.Print("pos", pos, "@", -2, "->", s);

        pos.y = pos.y + 1;
        s     = Geo3D.Surface(pos, -1); Printer.Print("pos", pos, "@", -1, "->", s);
        s     = Geo3D.Surface(pos, -2); Printer.Print("pos", pos, "@", -2, "->", s);

        pos.y = pos.y - 3;
        s     = Geo3D.Surface(pos, -1); Printer.Print("pos", pos, "@", -1, "->", s);
        s     = Geo3D.Surface(pos, -2); Printer.Print("pos", pos, "@", -2, "->", s);

        pos.y = pos.y - 1;
        s     = Geo3D.Surface(pos, -1); Printer.Print("pos", pos, "@", -1, "->", s);
        s     = Geo3D.Surface(pos, -2); Printer.Print("pos", pos, "@", -2, "->", s);

        pos.y = 1;
        s     = Geo3D.Surface(pos, -1); Printer.Print("pos", pos, "@", -1, "->", s);
        s     = Geo3D.Surface(pos, -2); Printer.Print("pos", pos, "@", -2, "->", s);

        pos.y = 0;
        s     = Geo3D.Surface(pos, -1); Printer.Print("pos", pos, "@", -1, "->", s);
        s     = Geo3D.Surface(pos, -2); Printer.Print("pos", pos, "@", -2, "->", s);
    }
Exemple #30
0
 //------------------------------------------------------------------------------
 // normals
 public void normals()
 {
     for (int v = 0; v < (_tiles + 1); v++)
     {
         double y = (double)v / (double)_tiles;
         for (int u = 0; u < (_tiles + 1); u++)
         {
             double    x = (double)u / (double)_tiles;
             int       j;
             int       k;
             Vectors[] T = new Vectors[C.CONST.ORDER];
             // d/du tangent
             for (j = 0; j < C.CONST.ORDER; j++)
             {
                 T[j] = (double)(C.CONST.ORDER - 1) * _matrix[0][j];
                 for (k = 1; k < C.CONST.ORDER - 1; k++)
                 {
                     T[j] = x * T[j] + (double)(C.CONST.ORDER - 1 - k) * _matrix[k][j];
                 }
             }
             Vectors du = T[0];
             for (k = 1; k < C.CONST.ORDER; k++)
             {
                 du = y * du + T[k];
             }
             // d/dv tangent
             for (j = 0; j < C.CONST.ORDER; j++)
             {
                 T[j] = _matrix[0][j];
                 for (k = 1; k < C.CONST.ORDER; k++)
                 {
                     T[j] = x * T[j] + _matrix[k][j];
                 }
             }
             Vectors dv = (double)(C.CONST.ORDER - 1) * T[0];
             for (k = 1; k < C.CONST.ORDER - 1; k++)
             {
                 dv = y * dv + (double)(C.CONST.ORDER - 1 - k) * T[k];
             }
             // cross product
             _normal[v][u] = du.cross(dv).unit();
         }
     }
 }
Exemple #31
0
        /// <summary>
        /// Creates an <see cref="Image"/> from an encapsulated GDI+ bitmap.
        /// </summary>
        /// <param name="bitmap">The GDI+ bitmap from which to create the <see cref="Image"/>.</param>
        /// <returns>
        /// The <see cref="Image"/> this method creates.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="bitmap"/> is <b>null</b>.
        /// </exception>
        public static Image FromBitmap(System.Drawing.Bitmap bitmap)
        {
            if (bitmap == null)
            {
                throw new ArgumentNullException(nameof(bitmap));
            }

            Image image = new Image(
                bitmap.Width,
                bitmap.Height,
                BitmapExtensions.PixelFormatToBitsPerPixel(bitmap.PixelFormat),
                (int)(bitmap.HorizontalResolution + 0.5f),
                (int)(bitmap.VerticalResolution + 0.5f));

            BitmapData srcData = bitmap.LockBits(
                new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
                ImageLockMode.ReadOnly,
                bitmap.PixelFormat);

            unsafe
            {
                fixed(ulong *dst = image.Bits)
                {
                    Arrays.CopyStrides(
                        image.Height,
                        srcData.Scan0,
                        srcData.Stride,
                        new IntPtr(dst),
                        image.Stride8);
                }
            }

            if (image.BitsPerPixel < 8)
            {
                Vectors.SwapBits(image.Bits.Length, image.BitsPerPixel, image.Bits, 0);
            }

            bitmap.UnlockBits(srcData);

            return(Image.OnLoaded(
                       image,
                       null,
                       bitmap.Palette?.Entries?.Select(x => Color.FromArgb(x.A, x.R, x.G, x.B)).ToArray()));
        }
	//perform calculation at time for given TLE lines
	//if you can get at objects from the JS use the commented version
	//this will make GetPos() and GetVel redundant
	
	/*public Vectors calculate(int time, string line1, string line2){
		TLE_DATA sat = new TLE_DATA();
		sat.TLE_DATA_INIT(line1, line2);
		return satvec(sat, timeutil.UnixTimeToDayNumber(time),timeutil.UnixTimeToDayFrac(time));
	}*/
	
	public void calculate(int time, string line1, string line2){
		TLE_DATA sat = new TLE_DATA();
		sat.TLE_DATA_INIT(line1, line2);
		results =  satvec(sat, timeutil.UnixTimeToDayNumber(time),timeutil.UnixTimeToDayFrac(time));
	}
	//calculate stalite position at DN, TN
	private Vectors satvec(TLE_DATA sat,int DN, double TN){
        //calculate average precession rates
        double N0 = sat.MM/86400; //Mean Motion rad/s
        double A0 = Math.Pow((GM/N0/N0),(1.0/3.0)); //semi major axis km
        double B0 = A0*Math.Sqrt(1 - sat.EC*sat.EC); //semi minor axis km
        double SI = Math.Sin(sat.IN); 
		double CI = Math.Cos(sat.IN);
        double PC = RE*A0/(B0*B0); //precession constant rad/day
        PC = 1.5*J2*PC*PC*sat.MM; //precession constant rads/day
        double QD = -PC*CI; //precession rate rad/day
        double WD = PC*(5*CI*CI-1)/2; //Perigee precession rate rad/day
        double DC = -2*(sat.M2)/sat.MM/3; //REM Drag coeff. (Angular momentum rate)/(Ang mom)  s^-1
        
        //Sidereal and Solar data. NEVER needs changing. valid until year ~2015
        //double YG = 2000;
		//double G0 = 98.9821; //GHAA, year YG Jan 0.0
        
		// UPDATED BY ALEX: Sidereal and Solar data. Valid to year ~2030
		double YG = 2014;
		double G0 = 99.5828; //GHAA, year YG Jan 0.0


        //Bring sun data to satellite epoch
        double TEG = (timeutil.EpochToDay(sat) - timeutil.FNday(Convert.ToInt32(YG),1,0)) + timeutil.EpochToFract(sat); //Elapsed Time: Epoch - YG
        //there is a wired bug in this line fixed by defining WE explicitly
        double GHAE = degtorad(G0) + TEG*6.300388; //GHA Aries, epoch
        //Time
        double T = (DN - timeutil.EpochToDay(sat)) + (TN - timeutil.EpochToFract(sat)); //Elapsed Time since epoch, days
        
        //Linear drag terms
        double DT = DC*T/2;
        double KD = 1 + 4*DT;
        double KDP = 1 - 7*DT;
        double M  = sat.MA + sat.MM*T*(1- 3*DT); //Mean anomaly at YR,TN
        //orbit number
        int DR = Convert.ToInt32(M/(2*PI)); //strip out whole number of revs;
        M  = M - DR*2*PI; //M now in range 0 - 2pi
        //double RN = sat.RV + DR; //current orbit number

        //solve M = EA - EC*Sin(EA) for EA givne M, using newtons methood
        double EA = M;  //Initial solution
        //declare here for use later
        double D = 1;
        double DNOM = 0; 
        double C = 0;
        double S = 0;
        while((Math.Abs(D) >= 1e-5)){
                C = Math.Cos(EA);
                S = Math.Sin(EA);
                DNOM = 1 - sat.EC*C;
                D = (EA- (sat.EC*S) -M)/DNOM; //change to EA for better solution
                EA = EA - D; //by this ammount
        }
        
        //distances
        double A = A0*KD;
        double B = B0*KD;
        //double RS = A*DNOM;
        
        //calculate satalite position and velocity in plane of elipse
        double Sx = A*(C - sat.EC);
        double Sy = B*S;
        double Vx = -A*S/DNOM*N0;
        double Vy = B*C/DNOM*N0;
        double AP = sat.WP + WD*T*KDP;
        double RAAN = sat.RA + QD*T*KDP;
        
        double CW = Math.Cos(AP);
        double CQ = Math.Cos(RAAN);
        double SW = Math.Sin(AP);
        double SQ = Math.Sin(RAAN);
        
        //plane . celestial coordinate transformtation, [C] = [RAAN]*[IN]*[AP]
        double CXx = CW*CQ - SW*CI*SQ;
        double CYx = CW*SQ + SW*CI*CQ;
        double CZx = SW*SI;
        
        double CXy = -SW*CQ - CW*CI*SQ;
        double CYy = -SW*SQ + CW*CI*CQ;
        double CZy = CW*SI;
        
        //double CXz = SI*SQ;
        //double CYz = -SI*CQ;
        //double CZz = CI;
		
        //Compute satalites position vector and velocity in clestial coordinates
        double SATx = Sx*CXx + Sy*CXy;
        double SATy = Sx*CYx + Sy*CYy;
        double SATz = Sx*CZx + Sy*CZy;
        
        double VELx = Vx*CXx + Vy*CXy;
        double VELy = Vx*CYx + Vy*CYy;
        double VELz = Vx*CZx + Vy*CZy;
        
        //express position and velocity in Geocentric coordinates
        //weired WE def bug also in this line fixed with explicit definition
        double GHAA = GHAE + 6.300388*T; //GHA Aries at elapsed time T
        C = Math.Cos(-GHAA);
        S = Math.Sin(-GHAA);
		
        Sx = SATx*C - SATy*S;
        Sy = SATx*S + SATy*C;
        double Sz = SATz;
        
        Vx = VELx*C - VELy*S;
        Vy = VELx*S + VELy*C;
        double Vz = VELz;       
        
		Vector pos = new Vector(Sx, Sy, Sz);
		Vector vel = new Vector(Vx, Vy, Vz);;
		Vectors output = new Vectors(pos, vel);
        return output;
	}