Ejemplo n.º 1
0
        public void Initialize(World world, PhysicsControl physics)
        {
            _physics = physics;
            var particles  = new List <Vector2>();
            var velocities = new List <Vector2>();

            Particles       = new Vector2[ParticleCount];
            Velocities      = new Vector2[ParticleCount];
            _velocityBuffer = new Vector2[ParticleCount];
            const float initGridSize = 0.4f;

            for (var x = 0.0f; x < _width; x += initGridSize)
            {
                for (var y = 0.0f; y < _height; y += initGridSize)
                {
                    if (!world.StaticGeometry.IsWaterSpawn(x, y))
                    {
                        continue;
                    }

                    particles.Add(new Vector2(x, y));
                    velocities.Add(new Vector2(0, 0));
                    _grid[(int)(particles.Last().X *GridMultiplier), (int)(particles.Last().Y *GridMultiplier)].Add(particles.Count - 1);
                }
            }

            Particles       = particles.ToArray();
            Velocities      = velocities.ToArray();
            _velocityBuffer = Velocities.ToArray();
            ParticleCount   = particles.Count;
            _w = new float[ParticleCount, ParticleCount];
        }
Ejemplo n.º 2
0
    /// <summary>
    /// Builds Road shapes from lane and road position data.
    /// Shapes are built as polygon meshes.
    /// </summary>
    /// <param name="shapelist">A List of floating point x,y position</param>
    /// <param name="id">The string id of the Road or Lane Shape.</param>
    /// <param name="type">"Road" or "Pedestrian". This will set the materials used.</param>
    /// <param name="width">The Road or Lane width in meters.</param>
    private void BuildShapeMesh(List <Vector3> shapelist, string id, string type, float width)
    {
        GameObject chunk = new GameObject();

        chunk.name = id;

        MeshRenderer mr = chunk.AddComponent <MeshRenderer>();
        Material     m;

        if (type == "Road")
        {
            //m = new Material(Road_Shader);
            m = Resources.Load("Materials/Road_Material", typeof(Material)) as Material;
        }
        else
        {
            m = Resources.Load("Materials/Road_Material", typeof(Material)) as Material;
        }

        mr.material = m;
        Mesh mesh         = new Mesh();
        int  numMeshVerts = shapelist.Count * 2;
        // Build Vertices
        float offset    = LANEWIDTH / 2.0f;
        int   slcounter = 0;

        Vector2[] verts = new Vector2[numMeshVerts];
        for (int i = 0; i < numMeshVerts; i += 2)
        {
            verts[i]     = new Vector2(shapelist[slcounter].x - offset, shapelist[slcounter].z - offset);
            verts[i + 1] = new Vector2(shapelist[slcounter].x + offset, shapelist[slcounter].z + offset);
            slcounter++;
        }

        Triangulator tr = new Triangulator(verts.ToArray());

        int[] indices = tr.Triangulate();

        Vector3[] vertices = new Vector3[numMeshVerts];
        for (int j = 0; j < numMeshVerts; j++)
        {
            vertices[j] = new Vector3(verts[j].x, 0.0f, verts[j].y);
        }

        Vector3[] normals = new Vector3[numMeshVerts];
        for (int k = 0; k < numMeshVerts; k++)
        {
            vertices[k] = -Vector3.up;
        }

        mesh.vertices  = vertices;
        mesh.triangles = indices;
        mesh.normals   = normals;
        mesh.RecalculateBounds();
        MeshFilter mf = chunk.AddComponent <MeshFilter>();

        mf.mesh = mesh;

        chunk.transform.parent = Edges_GO.transform;
    }
Ejemplo n.º 3
0
        public Mobile(Player player, Vector2 position, MobileType mobileType, bool IsSummon = false) : base()
        {
            ProjectileList              = new List <Projectile>();
            UnusedProjectile            = new List <Projectile>();
            LastCreatedProjectileList   = new List <Projectile>();
            UninitializedProjectileList = new List <Projectile>();
            ItemsUnderEffectList        = new List <ItemType>();

            MobileType = mobileType;
            Owner      = player;

            movingSE       = AssetHandler.Instance.RequestSoundEffect(SoundEffectParameter.MobileMovement(mobileType));
            unableToMoveSE = AssetHandler.Instance.RequestSoundEffect(SoundEffectParameter.MobileUnableToMove(mobileType));

            this.IsSummon = IsSummon;

            IsPlayable = GameInformation.Instance.IsOwnedByPlayer(this) && !IsSummon;

            if (IsPlayable)
            {
                Movement = new LocalMovement(this);
            }
            else if (!IsSummon)
            {
                Movement = new RemoteMovement(this);
            }

            MobileMetadata = MobileMetadata.BuildMobileMetadata(player, mobileType);

            Position       = position;
            MobileFlipbook = MobileFlipbook.CreateMobileFlipbook(MobileType, position);

            if (!IsSummon)
            {
                Rider = new Rider(this);

                if (MobileType != MobileType.Random)
                {
                    Crosshair = new Crosshair(this);
                }
            }

            //Sync
            SyncMobile                = new SyncMobile();
            SyncMobile.Owner          = player;
            SyncMobile.Position       = Position.ToArray <int>();
            SyncMobile.MobileMetadata = MobileMetadata.BuildMobileMetadata(player, player.PrimaryMobile);
            SyncPosition              = Position;

            IsAlive                = true;
            IsActionsLocked        = false;
            hasShotSequenceStarted = false;

#if DEBUG
            DebugHandler.Instance.Add(debugCrosshair);
            DebugHandler.Instance.Add(debugCrosshair2);
#endif
        }
Ejemplo n.º 4
0
    public Mesh BuildTerrainMeshFogOfWar(Field height, Cell offset, int res)
    {
        var vertices = new Vector3[res * res];
        var uv       = new Vector2[res * res];

        for (int i = 0; i < res; i++)
        {
            for (int j = 0; j < res; j++)
            {
                var x = offset.i + i;
                var y = offset.j + j;
                var h = height[x, y];
                vertices[i + res * j] = new Vector3(x, h, y);
                uv[i + res * j]       = new Vector2(x / (float)res, y / (float)res);
            }
        }
        var triangles = new List <int>();

        for (int i = 0; i < res - 1; i++)
        {
            for (int j = 0; j < res - 1; j++)
            {
                if (Game.NeighbourDist[i, j] > Game.VisionRange)
                {
                    continue;
                }
                if ((offset.i + i + offset.j + j) % 2 == 0)
                {
                    triangles.Add((i + 1) + res * (j + 0));
                    triangles.Add((i + 0) + res * (j + 0));
                    triangles.Add((i + 0) + res * (j + 1));
                    triangles.Add((i + 1) + res * (j + 1));
                    triangles.Add((i + 1) + res * (j + 0));
                    triangles.Add((i + 0) + res * (j + 1));
                }
                else
                {
                    triangles.Add((i + 1) + res * (j + 0));
                    triangles.Add((i + 0) + res * (j + 0));
                    triangles.Add((i + 1) + res * (j + 1));
                    triangles.Add((i + 1) + res * (j + 1));
                    triangles.Add((i + 0) + res * (j + 0));
                    triangles.Add((i + 0) + res * (j + 1));
                }
            }
        }
        var mesh = new Mesh();

        mesh.vertices  = vertices.ToArray();
        mesh.uv        = uv.ToArray();
        mesh.triangles = triangles.ToArray();
        mesh.RecalculateBounds();
        mesh.RecalculateNormals();
        mesh.RecalculateTangents();
        return(mesh);
    }
Ejemplo n.º 5
0
        public void ForceChangePosition(Vector2 newPosition)
        {
            Position            = SyncPosition = newPosition;
            SyncMobile.Position = newPosition.ToArray <int>();

            if (!IsPlayable)
            {
                ((RemoteMovement)Movement).DesiredPosition = newPosition;
                ((RemoteMovement)Movement).DesiredPositionQueue.Clear();
                ((RemoteMovement)Movement).EnqueuePosition(newPosition);
            }
        }
Ejemplo n.º 6
0
        public void ToArray(
            [Random(-100d, 100d, 1)] double x,
            [Random(-100d, 100d, 1)] double y)
        {
            // Arrange
            var v = new Vector2(x, y);

            // Act
            var actual = v.ToArray();

            // Assert
            Assert.That(actual[0], Is.EqualTo(x));
            Assert.That(actual[1], Is.EqualTo(y));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Return Vertex as Float Array
        /// </summary>
        /// <returns></returns>
        internal float[] GetArray()
        {
            List <float> v = new List <float>();

            v.AddRange(Position.ToArray());
            v.AddRange(Normal.ToArray());
            v.AddRange(TextureSet1.ToArray());
            v.AddRange(TextureSet2.ToArray());
            v.AddRange(Tangent.ToArray());
            v.AddRange(Binormal.ToArray());
            v.AddRange(Joint.ToArray());
            v.AddRange(Weight.ToArray());
            return(v.ToArray());
        }
Ejemplo n.º 8
0
        public static void ApplyMaterials(CityGml2GO cityGml2Go)
        {
            //var path = Path.GetFullPath(cityGml2Go.Filename);
            var path = Application.dataPath + "/StreamingAssets/test/";

            foreach (var texture in cityGml2Go.Textures)
            {
                var fn    = Path.Combine(path, texture.Url);
                var b     = File.ReadAllBytes(fn);
                var tex2D = new Texture2D(1, 1);
                tex2D.LoadImage(b);
                var mat = new Material(Shader.Find("Standard"))
                {
                    mainTexture = tex2D
                };

                foreach (var textureTarget in texture.Targets)
                {
                    if (!cityGml2Go.Polygons.Any(x => x != null && x.name == textureTarget.Id && x.activeSelf))
                    {
                        continue;
                    }
                    GameObject   go = cityGml2Go.Polygons.First(x => x != null && x.name == textureTarget.Id && x.activeSelf);
                    MeshRenderer mr = go.GetComponent <MeshRenderer>();

                    mr.material = mat;

                    MeshFilter mf = go.GetComponent <MeshFilter>();

                    Vector3[] vertices = mf.sharedMesh.vertices;
                    var       uv       = new Vector2[vertices.Length];
                    foreach (var x in cityGml2Go.oriPoly)
                    {
                        if (x.name == textureTarget.Id)
                        {
                            x.outsideUVs = textureTarget.Coords;
                            for (int i = 0; i < vertices.Length; i++)
                            {
                                uv[i] = x.ClosestUV(vertices[i]);
                            }
                        }
                    }
                    uv.Reverse();
                    mf.sharedMesh.uv = uv.ToArray();
                    mf.sharedMesh.RecalculateTangents();
                }
            }
        }
Ejemplo n.º 9
0
    public void EndDraw(Vector2 point)
    {
        if (points.Count == 1)
        {
            SetPoint(new Vector2(point.x + 0.01f, point.y));
        }

        PolygonCollider2D polygonCollider = lineRenderer.gameObject.AddComponent <PolygonCollider2D>();

        int verticesCount    = 2;
        int doublePointCount = points.Count * verticesCount;
        int lastPoint        = doublePointCount - 1;

        Vector2[] temps = new Vector2[doublePointCount];

        for (int i = 0; i < points.Count; i++)
        {
            float angle = i < points.Count - 1? GetAngle(points[i], points[i + 1]) : GetAngle(points[i], points[i - 1]);    //最後一點  反過來取得角度
            SetModifierPoint(angle);

            if (i < points.Count - 1)
            {
                temps[i]             = new Vector2(points[i].x + modifierX, points[i].y + modifierY);
                temps[lastPoint - i] = new Vector2(points[i].x + modifierX2, points[i].y + modifierY2);
            }
            else
            {
                temps[i]             = new Vector2(points[i].x + modifierX2, points[i].y + modifierY2);
                temps[lastPoint - i] = new Vector2(points[i].x + modifierX, points[i].y + modifierY);
            }
        }

        polygonCollider.points = temps.ToArray();

        polygonCollider.gameObject.AddComponent <Rigidbody2D>();

        Rigidbody2D rigidbody2D = polygonCollider.gameObject.GetComponent <Rigidbody2D>();

        rigidbody2D.mass = mass;

        isEndDraw = true;
    }
Ejemplo n.º 10
0
        // ///Kind of scales a polygon based on it's vertices average normal.
        // ///This is the old (and non very correct way)
        // public static Vector2[] InflatePolygon(ref Vector2[] points, float dist) {
        //     for ( int i = 0; i < points.Length; i++ ) {
        //         var a = points[i == 0 ? points.Length - 1 : i - 1];
        //         var b = points[i];
        //         var c = points[( i + 1 ) % points.Length];
        //         var ab = ( a - b ).normalized;
        //         var cb = ( c - b ).normalized;
        //         // var mid = ( ab + cb ).normalized + ( ab + cb );
        //         var mid = ( ab + cb );
        //         mid *= ( !PointIsConcave(points, i) ? -dist : dist );
        //         points[i] = ( points[i] + mid );
        //     }
        //     return points;
        // }



        // Return points representing an enlarged polygon.
        public static Vector2[] InflatePolygon(ref Vector2[] points, float dist)
        {
            var enlarged_points = new Vector2[points.Length];

            for (var j = 0; j < points.Length; j++)
            {
                // Find the new location for point j.
                // Find the points before and after j.
                var i = (j - 1);
                if (i < 0)
                {
                    i += points.Length;
                }
                var k = (j + 1) % points.Length;

                // Move the points by the offset.
                var v1 = new Vector2(points[j].x - points[i].x, points[j].y - points[i].y).normalized;
                v1 *= dist;
                var n1 = new Vector2(-v1.y, v1.x);

                var pij1 = new Vector2((float)(points[i].x + n1.x), (float)(points[i].y + n1.y));
                var pij2 = new Vector2((float)(points[j].x + n1.x), (float)(points[j].y + n1.y));

                var v2 = new Vector2(points[k].x - points[j].x, points[k].y - points[j].y).normalized;
                v2 *= dist;
                var n2 = new Vector2(-v2.y, v2.x);

                var pjk1 = new Vector2((float)(points[j].x + n2.x), (float)(points[j].y + n2.y));
                var pjk2 = new Vector2((float)(points[k].x + n2.x), (float)(points[k].y + n2.y));

                // See where the shifted lines ij and jk intersect.
                bool    lines_intersect, segments_intersect;
                Vector2 poi, close1, close2;
                FindIntersection(pij1, pij2, pjk1, pjk2, out lines_intersect, out segments_intersect, out poi, out close1, out close2);
                Debug.Assert(lines_intersect, "Edges " + i + "-->" + j + " and " + j + "-->" + k + " are parallel");
                enlarged_points[j] = poi;
            }

            return(enlarged_points.ToArray());
        }
Ejemplo n.º 11
0
        public void OnDraw(Sprite sp)
        {
            m_Context.ClearRenderTargetView(m_RenderView, Color.Black);

            m_Context.PixelShader.SetShaderResource(0, m_TexturePool.GetView(sp.TextureID));

            m_SpriteBatch.Begin(m_Context);

            var worldViewProj = m_ViewMatrix * m_ProjMatrix * sp.GetTransform.GetMatrix();

            worldViewProj.Transpose();

            float[] data  = new float[40];
            int     index = 0;

            foreach (Vertex i in sp.Vertices)
            {
                Vector2 rp = Vector2.TransformCoordinate(i.Position, worldViewProj);
                // rp -= new Vector2(1f, 1f);
                rp.ToArray().CopyTo(data, index);
                index        += 2;
                data[index++] = 0f;
                data[index++] = 1f;

                i.Color.ToArray().CopyTo(data, index);
                index        += 3;
                data[index++] = 1f;

                i.TexCoords.ToArray().CopyTo(data, index);
                index += 2;
            }

            m_SpriteBatch.Draw(data, sp.TextureID);


            m_SpriteBatch.End();

            m_SwapChain.Present(0, PresentFlags.None);
        }
Ejemplo n.º 12
0
    public static Mesh SubmeshToMesh(Mesh oldMesh, int index)
    {
        Mesh newMesh = new Mesh();

        newMesh.name = $"{oldMesh.name}_{index}";

        int[] triangles = oldMesh.GetTriangles(index);

        Vector3[] newVertices = new Vector3[triangles.Length];
        Vector2[] newUvs      = new Vector2[triangles.Length];

        Dictionary <int, int> oldToNewIndices = new Dictionary <int, int>();
        int newIndex = 0;

        for (int i = 0; i < oldMesh.vertices.Length; i++)
        {
            if (triangles.Contains(i))
            {
                newVertices[newIndex] = oldMesh.vertices[i];
                newUvs[newIndex]      = oldMesh.uv[i];
                oldToNewIndices.Add(i, newIndex);
                ++newIndex;
            }
        }

        int[] newTriangles = new int[triangles.Length];

        for (int i = 0; i < newTriangles.Length; i++)
        {
            newTriangles[i] = oldToNewIndices[triangles[i]];
        }

        newMesh.vertices  = newVertices.ToArray();
        newMesh.uv        = newUvs.ToArray();
        newMesh.triangles = newTriangles;
        newMesh.Optimize();
        return(newMesh);
    }
Ejemplo n.º 13
0
    Mesh GenerateLensMesh(Vector2[] curve1, Vector2[] curve2)
    {
        Vector3[] vertices  = new Vector3[curve1.Count() + curve2.Count()];
        Vector2[] uv        = new Vector2[vertices.Length];
        int[]     triangles = new int[(curve1.Count() - 1) * 6];

        for (int i = 0; i <= pointsQuantity; i++)
        {
            var tmp = i * 2;
            vertices[tmp]     = curve1[i];
            vertices[tmp + 1] = curve2[i];
        }

        int counter = 0;

        for (int segment = 0; segment < curve1.Count() - 1; segment++)
        {
            var tmp = segment * 2;

            triangles[counter++] = tmp;
            triangles[counter++] = 1 + tmp;
            triangles[counter++] = 2 + tmp;

            triangles[counter++] = 1 + tmp;
            triangles[counter++] = 3 + tmp;
            triangles[counter++] = 2 + tmp;
        }

        Mesh lensMesh = new Mesh();

        lensMesh.vertices  = vertices;
        lensMesh.uv        = uv.ToArray();
        lensMesh.triangles = triangles;

        return(lensMesh);
    }
Ejemplo n.º 14
0
 public void WriteFloat16_2(Vector2 v)
 {
     Write(v.ToArray(), 2, e => _writer.Write(Half.GetBytes(new Half(e))));
 }
Ejemplo n.º 15
0
 public void Set(Vector2 vector)
 {
     Program.Context.SetProgramUniform(this, 2, "f", vector.ToArray());
 }
Ejemplo n.º 16
0
    public ColladaLite(string content)
    {
        var doc = new XmlDocument();

        doc.LoadXml(content);
        XmlNode colladaNode = null;

        foreach (XmlNode childNode in doc.ChildNodes)
        {
            if (childNode.Name == "COLLADA")
            {
                colladaNode = childNode;
                break;
            }
        }

        foreach (XmlNode childNode in colladaNode.ChildNodes)
        {
            if (childNode.Name == "library_images")
            {
                foreach (XmlNode imageNode in childNode.ChildNodes)
                {
                    if (imageNode.Name == "image" && imageNode.HasChildNodes)
                    {
                        if (imageNode.FirstChild.Name == "init_from")
                        {
                            (textureNames ?? (textureNames = new List <string>())).Add(imageNode.FirstChild.InnerText);
                        }
                    }
                }
            }
            else if (childNode.Name == "library_geometries")
            {
                if (childNode.HasChildNodes)
                {
                    var fc = URDFLoader.GetXmlNodeChildByName(childNode, "geometry");
                    foreach (XmlNode mesh in fc.ChildNodes)
                    {
                        if (mesh.Name != "mesh")
                        {
                            continue;
                        }

                        var       sources     = new Dictionary <string, float[]>();
                        var       vertsSource = "null";
                        Vector3[] triangles   = null;
                        Vector3[] normals     = null;
                        Vector2[] uvs         = null;
                        int[]     indices     = null;
                        var       inputs      = new List <DaeInput>();
                        var       triCount    = 0;
                        foreach (XmlNode node in mesh.ChildNodes)
                        {
                            if (node.Name == "source")
                            {
                                var fa = URDFLoader.GetXmlNodeChildByName(node, "float_array");
                                if (fa != null)
                                {
                                    sources.Add(node.Attributes["id"].Value,
                                                fa.InnerText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                                                .Select(f => float.Parse(f))
                                                .ToArray());
                                }
                            }
                            else if (node.Name == "vertices")
                            {
                                var vs = URDFLoader.GetXmlNodeChildByName(node, "input");
                                if (vs != null)
                                {
                                    vertsSource = vs.Attributes["source"].Value.Replace("#", "");
                                }
                            }
                            else if (node.Name == "triangles")
                            {
                                triCount = int.Parse(node.Attributes["count"].Value) * 3;
                                inputs.AddRange(URDFLoader.GetXmlNodeChildrenByName(node, "input")
                                                .Select(inputNode => new DaeInput {
                                    semantic = inputNode.Attributes["semantic"].Value,
                                    source   = inputNode.Attributes["source"].Value,
                                    offset   = int.Parse(inputNode.Attributes["offset"].Value)
                                }));
                                indices = URDFLoader.GetXmlNodeChildByName(node, "p").InnerText
                                          .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(i => int.Parse(i))
                                          .ToArray();
                            }
                        }

                        foreach (DaeInput input in inputs)
                        {
                            var source = input.source.Replace("#", "");
                            if (sources.ContainsKey(source))
                            {
                                if (input.semantic == "TEXCOORD")
                                {
                                    var temp = new List <Vector2>();
                                    for (int i = 0; i < sources[source].Length; i += 2)
                                    {
                                        temp.Add(new Vector2(sources[source][i], sources[source][i + 1]));
                                    }
                                    uvs = temp.ToArray();
                                }
                                else if (input.semantic == "NORMAL")
                                {
                                    //not actually dealing with normals right now
                                }
                            }
                            else if (input.semantic == "VERTEX")
                            {
                                var temp = new List <Vector3>();
                                for (int i = 0; i < sources[vertsSource].Length; i += 3)
                                {
                                    temp.Add(URDFLoader.URDFToUnityPos(new Vector3(sources[vertsSource][i],
                                                                                   sources[vertsSource][i + 1],
                                                                                   sources[vertsSource][i + 2])));
                                }
                                triangles = temp.ToArray();
                            }
                        }

                        if (triangles != null && triangles.Length > 2)
                        {
                            var sb        = new StringBuilder();
                            var tris      = new int[triCount];
                            var uvsActual = new Vector2[triangles.Length];
                            var uvOffset  = inputs.First(u => u.semantic == "TEXCOORD").offset;
                            for (int i = 0; i < tris.Length; i++)
                            {
                                tris[i] = indices[i * 3];
                            }

                            Mesh temp = new Mesh();
                            temp.vertices  = triangles;
                            temp.triangles = tris;
                            temp.uv        = uvsActual.ToArray();
                            temp.RecalculateNormals();
                            (meshes ?? (meshes = new List <Mesh>())).Add(temp);
                        }
                    }
                }
            }
        }
    }
Ejemplo n.º 17
0
        ///-------------------------------------------------------------------------------------------------
        /// <summary>   Draws a point, a coordinate in space at the dimension of one pixel </summary>
        ///
        /// <remarks>   Jan Tamis, 27-8-2017. </remarks>
        ///
        /// <param name="x">    The x coordinate. </param>
        /// <param name="y">    The y coordinate. </param>
        ///
        /// <returns>   The given point. </returns>

        public static void point(double x, double y)
        {
            if (currentStyle.strokeColor.A > 0)
            {
                if (currentStyle.strokeWidth > 3)
                {
                    int num_segments = 0;

                    num_segments = ceil(5 * sqrt(currentStyle.strokeWidth / 2));

                    Vector2[] vertbuffer = new Vector2[num_segments];

                    Vector2 vector = new Vector2(0, 0);

                    float theta = TWO_PI / (num_segments);

                    float tangetial_factor = tan(theta);
                    float radial_factor    = cos(theta);

                    double X = (currentStyle.strokeWidth / 2) * cos(0);//we now start at the start angle
                    double Y = (currentStyle.strokeWidth / 2) * sin(0);


                    for (int i = 0; i < num_segments; i++)
                    {
                        vector.X = (float)(X + x);
                        vector.Y = (float)(Y + y);

                        double tx = -Y;
                        double ty = X;

                        X += tx * tangetial_factor;
                        Y += ty * tangetial_factor;

                        X *= radial_factor;
                        Y *= radial_factor;

                        vertbuffer[i] = vector;
                    }

                    GL.BufferData(BufferTarget.ArrayBuffer, Vector2.SizeInBytes * vertbuffer.Length, vertbuffer.ToArray(), BufferUsageHint.DynamicDraw);
                    GL.Color4(currentStyle.strokeColor);
                    GL.DrawArrays(PrimitiveType.Polygon, 0, vertbuffer.Length);
                }
                else
                {
                    GL.PointSize(currentStyle.strokeWidth);

                    GL.Begin(PrimitiveType.Points);

                    GL.Color4(currentStyle.strokeColor);
                    GL.Vertex2(x, y);

                    GL.End();
                }
            }
        }
Ejemplo n.º 18
0
        ///-------------------------------------------------------------------------------------------------
        /// <summary>   Draws an ellipse (oval) to the screen. </summary>
        ///
        /// <remarks>   Jan Tamis, 27-8-2017. </remarks>
        ///
        /// <param name="x">    The x coordinate. </param>
        /// <param name="y">    The y coordinate. </param>
        /// <param name="w">    The width. </param>
        /// <param name="h">    The height. </param>

        public static void ellipse(double x, double y, double w, double h)
        {
            // http://slabode.exofire.net/circle_draw.shtml

            int num_segments = 0;

            double r = ((w / h) * 2);

            num_segments = ceil(1.275 * sqrt((w * h) / 2));

            Vector2[] vertbuffer = new Vector2[num_segments];

            Vector2 vector = new Vector2(0, 0);

            if (CircleMode == drawModes.Center)
            {
                w /= 2;
                h /= 2;
            }

            if (currentStyle.fillColor.A > 0 || currentStyle.strokeColor.A > 0)
            {
                float theta = TWO_PI / (num_segments);

                float tangetial_factor = tan(theta);
                float radial_factor    = cos(theta);

                double X = w * cos(0);//we now start at the start angle
                double Y = h * sin(0);


                for (int i = 0; i < num_segments; i++)
                {
                    vector.X = (float)(X + x);
                    vector.Y = (float)(Y + y);

                    double tx = -Y;
                    double ty = X;

                    X += tx * tangetial_factor;
                    Y += ty * tangetial_factor;

                    X *= radial_factor;
                    Y *= radial_factor;

                    vertbuffer[i] = vector;
                }

                GL.BufferData(BufferTarget.ArrayBuffer, Vector2.SizeInBytes * vertbuffer.Length, vertbuffer.ToArray(), BufferUsageHint.DynamicDraw);
            }

            if (currentStyle.fillColor.A > 0)
            {
                GL.Color4(currentStyle.fillColor);
                GL.DrawArrays(PrimitiveType.Polygon, 0, vertbuffer.Length);
            }

            if (currentStyle.strokeColor.A > 0)
            {
                GL.LineWidth(currentStyle.strokeWidth);
                GL.Color4(currentStyle.strokeColor);
                GL.DrawArrays(PrimitiveType.LineLoop, 0, vertbuffer.Length);
            }
        }
Ejemplo n.º 19
0
		public void SetPoints(Vector2[] points)
		{
			Points = points.ToArray();
			SetVerticesDirty();
		}
Ejemplo n.º 20
0
 public void WriteShort2N(Vector2 v)
 {
     Write(v.ToArray(), 2, e => _writer.Write((short)(Clamp(e) * 32767.0f)));
 }
 public Polygon(Vector2[] vertices)
 {
     _vertices = vertices.ToArray();
 }
Ejemplo n.º 22
0
 public void WriteUShort2N(Vector2 v)
 {
     Write(v.ToArray(), 2, e => _writer.Write((ushort)(Clamp((e + 1.0f) / 2.0f) * 65535.0f)));
 }
Ejemplo n.º 23
0
 internal CylinderFlowLineDrawer(CylinderFlow cf, Vector2 startPos)
 {
     _cf = cf;
     _xs = startPos.ToArray();
 }
Ejemplo n.º 24
0
 public void WriteFloat2(Vector2 v)
 {
     Write(v.ToArray(), 2, e => _writer.Write(e));
 }
Ejemplo n.º 25
0
 public void Vector2(Vector2 v)
 {
     Floats(v.ToArray());
 }
Ejemplo n.º 26
0
 public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
 {
     if (destinationType == (Type)null)
     {
         throw new ArgumentNullException("destinationType");
     }
     if (value is Vector2)
     {
         Vector2 vector2 = (Vector2)value;
         if (destinationType == typeof(string))
         {
             return((object)BaseConverter.ConvertFromValues <float>(context, culture, vector2.ToArray()));
         }
         if (destinationType == typeof(InstanceDescriptor))
         {
             ConstructorInfo constructor = typeof(Vector2).GetConstructor(MathUtil.Array <Type>(typeof(float), 2));
             if (constructor != (ConstructorInfo)null)
             {
                 return((object)new InstanceDescriptor((MemberInfo)constructor, (ICollection)vector2.ToArray()));
             }
         }
     }
     return(base.ConvertTo(context, culture, value, destinationType));
 }
Ejemplo n.º 27
0
        public void CreateMesh2(List<Vector3> vertices, List<Vector2> uvs, List<Vector3> normals)
        {
            double t0 = EditorApplication.timeSinceStartup;
            //Debug.Log ("Face Count: " + faces.Count ());
            if (faces.Count () <= 0)
                return;

            List<int> mVerticesID = new List<int> ();
            List<int> mTriangles = new List<int> ();

            //populate mVerticesID containing all vertices used in all faces of mesh
            foreach (List<int> face in faces) {
                mVerticesID.AddRange(face);
            }
            //make it unique
            int[] mVerticesIDArr = mVerticesID.Distinct ().ToArray ();

            int[] vertLookup = new int[vertices.Count];
            for (int i=0; i<vertLookup.Length; i++) {
                vertLookup[i] = -1; //init values to -1
            }
            for (int i = 0; i < mVerticesIDArr.Length; i++) {
                vertLookup[mVerticesIDArr[i]] = i;
            }

            Vector3[] mVertices = new Vector3[mVerticesIDArr.Length];
            Vector2[] mUVs = new Vector2[mVerticesIDArr.Length];
            Vector3[] mNormals = new Vector3[mVerticesIDArr.Length];

            //populate data array
            for (int i = 0; i < mVerticesIDArr.Length; i++) {
                mVertices[i]= vertices[mVerticesIDArr[i]];
                mUVs[i] 	= uvs[mVerticesIDArr[i]];
                mNormals[i] = normals[mVerticesIDArr[i]];
            }

            Debug.Log ("Preparing vert data took: " + (t0 - EditorApplication.timeSinceStartup));
            t0 = EditorApplication.timeSinceStartup;

            double tVertLookup = 0;
            double tFaceCreation = 0;

            double tf;
            //generate face and vertices data
            foreach (List<int> face in faces) {
                tf = EditorApplication.timeSinceStartup;

                List<int> newFace = new List<int> ();
                foreach (int vertID in face){

                    int newID = vertLookup[vertID];//Array.IndexOf(mVerticesIDArr, vertID); //mVerticesIDArr.Contains(vertID);
                    if (newID >= 0){
                        newFace.Add(newID);
                    }
                }
                tVertLookup += EditorApplication.timeSinceStartup - tf;

                tf = EditorApplication.timeSinceStartup;
                newFace.Reverse();
                if (newFace.Count() == 3) {
                    mTriangles.AddRange(newFace);
                } else {	//implement face triangulation algorithm
                    Debug.Log ("Non-triangle face");
                }
                tFaceCreation += EditorApplication.timeSinceStartup - tf;
            }
            Debug.Log ("Computing face verts took: " + (t0 - EditorApplication.timeSinceStartup));
            Debug.Log ("  vertex lookup: " + tVertLookup);
            Debug.Log ("  face data creation: " + tFaceCreation);
            t0 = EditorApplication.timeSinceStartup;

            //Generate mesh object
            Mesh mesh = new Mesh ();
            mesh.vertices = mVertices.ToArray ();
            mesh.uv = mUVs.ToArray ();
            mesh.normals = mNormals.ToArray ();
            mesh.triangles = mTriangles.ToArray ();

            //add meshrenderer / meshfilters to parent and apply mesh
            MeshRenderer mr = parent.AddComponent<MeshRenderer> ();
            mr.sharedMaterial = new Material (Shader.Find ("Standard"));
            MeshFilter mf = parent.AddComponent<MeshFilter> ();
            mf.sharedMesh = mesh;
        }
Ejemplo n.º 28
0
    void Update()
    {
        // 3
        if (player.name == "Player 4")
        {
            playerHor      = Input.GetAxis("HorizontalRStickP4");
            playerVer      = Input.GetAxis("VerticalRStickP4");
            firebuttonDown = Input.GetButtonDown("Fire1P4");
            firebuttonUp   = Input.GetButtonUp("Fire1P4");
        }
        if (player.name == "Player 1")
        {
            playerHor      = Input.GetAxis("HorizontalRStick");
            playerVer      = Input.GetAxis("VerticalRStick");
            firebuttonDown = Input.GetButtonDown("Fire1");
            firebuttonUp   = Input.GetButtonUp("Fire1");
        }
        if (player.name == "Player 2")
        {
            playerHor      = Input.GetAxis("HorizontalRStickP2");
            playerVer      = Input.GetAxis("VerticalRStickP2");
            firebuttonDown = Input.GetButtonDown("Fire1P2");
            firebuttonUp   = Input.GetButtonUp("Fire1P2");
        }
        if (player.name == "Player 3")
        {
            playerHor      = Input.GetAxis("HorizontalRStickP3");
            playerVer      = Input.GetAxis("VerticalRStickP3");
            firebuttonDown = Input.GetButtonDown("Fire1P3");
            firebuttonUp   = Input.GetButtonUp("Fire1P3");
        }


        var aimAngle = Mathf.Atan2(playerVer, playerHor);

        if (aimAngle < 0f)
        {
            aimAngle = Mathf.PI * 2 + aimAngle;
        }
        if (playerVer == 0 && playerHor == 0)
        {
            crosshairSprite.enabled = false;
        }

        // 4
        var aimDirection = Quaternion.Euler(0, 0, aimAngle * Mathf.Rad2Deg) * Vector2.right;

        // 5
        playerPosition = transform.position;
        startPos       = transform.localPosition + new Vector3(0.1f, 0.1f, 0.1f);
        endPos         = ropeHingeAnchor.transform.localPosition;
        Vector2[] points = new Vector2[2]
        {
            startPos,
            endPos
        };
        edgeCollider.points = points.ToArray();
        // 6
        if (!ropeAttached)
        {
            SetCrosshairPosition(aimAngle);
        }
        else
        {
            crosshairSprite.enabled = false;
        }
        HandleInput(aimDirection);
        UpdateRopePositions();
    }