Example #1
0
        protected override void Initialize()
        {
            quad = new Quad[6];
            quad[0] = new Quad(Vector3.Backward, Vector3.Backward, Vector3.Up, 2, 2);
            quad[1] = new Quad(Vector3.Left, Vector3.Left, Vector3.Up, 2, 2);
            quad[2] = new Quad(Vector3.Right, Vector3.Right, Vector3.Up, 2, 2);
            quad[3] = new Quad(Vector3.Forward, Vector3.Forward, Vector3.Up, 2, 2);
            quad[4] = new Quad(Vector3.Down, Vector3.Down, Vector3.Right, 2, 2);
            quad[5] = new Quad(Vector3.Up, Vector3.Up, Vector3.Left, 2, 2);
            nh = new NodeHandle();
            imgSub = nh.subscribe<Messages.sensor_msgs.Image>("/camera/rgb/image_rect_color", 1, (img) =>
                                                                    {
                                                                        if (padlock.WaitOne(10))
                                                                        {
                                                                            if (next_texture == null)
                                                                            {
                                                                                next_texture = new Texture2D(GraphicsDevice, (int) img.width, (int) img.height);
                                                                            }
                                                                            util.UpdateImage(GraphicsDevice, img.data, new Size((int)img.width, (int)img.height), ref next_texture, img.encoding.data);
                                                                            padlock.ReleaseMutex();
                                                                        }
                                                                    });

            base.Initialize();
        }
        /// <summary>
        /// This is a specialized version of HitTestPolygonSegment that takes 
        /// a Quad for a polygon. This method is called very intensively by
        /// hit-testing API and we don't want to create Vector[] for every quad it hit-tests.
        /// </summary>
        /// <param name="quad">the connecting quad to test against</param> 
        /// <param name="hitBegin">begin point of the hitting segment</param>
        /// <param name="hitEnd">end point of the hitting segment</param> 
        /// <returns>true if hit, false otherwise</returns> 
        internal static bool HitTestQuadSegment(Quad quad, Point hitBegin, Point hitEnd)
        { 
            System.Diagnostics.Debug.Assert(quad.IsEmpty == false);

            HitResult hitResult = HitResult.Right, firstResult = HitResult.Right, prevResult = HitResult.Right;
            int count = 4; 
            Vector zeroVector = new Vector(0, 0);
            Vector hitVector = hitEnd - hitBegin; 
            Vector vertex = quad[count - 1] - hitBegin; 

            for (int i = 0; i < count; i++) 
            {
                Vector nextVertex = quad[i] - hitBegin;
                hitResult = WhereIsSegmentAboutSegment(zeroVector, hitVector, vertex, nextVertex);
                if (HitResult.Hit == hitResult) 
                {
                    return true; 
                } 
                if (true == IsOutside(hitResult, prevResult))
                { 
                    return false;
                }
                if (i == 0)
                { 
                    firstResult = hitResult;
                } 
                prevResult = hitResult; 
                vertex = nextVertex;
            } 
            return (false == IsOutside(firstResult, hitResult));
        }
Example #3
0
        public Snowflake(Vector3 position, float snowflakeTemperature)
        {
            float diameter = Snowflake.CalculateDiameter(snowflakeTemperature);
            this.mass      = Snowflake.CalculateMass    (snowflakeTemperature, diameter);

            this.basicEffect = new BasicEffect(this.graphicsDevice);

            this.basicEffect.World = this.camera.World;
            this.basicEffect.View = this.camera.View;
            this.basicEffect.Projection = this.camera.Projection;
            this.basicEffect.TextureEnabled = true;

            if (this.showLeaf)
            {
                this.quad = new Quad(diameter * 2);
                Texture2D texture = this.contentManager.Load<Texture2D>("leaf_" + (int)(Snowflake.random.NextDouble() * numTextures));
                this.basicEffect.Texture = texture;
            }
            else
            {
                this.quad = new Quad(diameter);
                Texture2D texture = this.contentManager.Load<Texture2D>("flake_" + (int)(Snowflake.random.NextDouble() * numTextures));
                this.basicEffect.Texture = texture;
            }

            this.Position = position;
            this.velocity = new Vector3(0f, -0.1f, 0f);
        }
Example #4
0
	public static bool OverlapQuads(Quad quad1, Quad quad2) {
		bool triIntersect1 = TriTriIntersection.TriTriOverlap.TriTriIntersect(quad1.GetTri1(), quad2.GetTri1());
		bool triIntersect2 = TriTriIntersection.TriTriOverlap.TriTriIntersect(quad1.GetTri1(), quad2.GetTri2());
		bool triIntersect3 = TriTriIntersection.TriTriOverlap.TriTriIntersect(quad1.GetTri2(), quad2.GetTri1());
		bool triIntersect4 = TriTriIntersection.TriTriOverlap.TriTriIntersect(quad1.GetTri2(), quad2.GetTri2());
		return triIntersect1 || triIntersect2 || triIntersect3 || triIntersect4;
	}
Example #5
0
        public Quad(QuadRoot tree, Quad parent, Rectangle rectangle)
        {
            this.tree = tree;
            this.parent = parent;
            this.rectangle = rectangle;

            this.imageX = this.rectangle.X / this.rectangle.Width;
            this.imageY = this.rectangle.Y / this.rectangle.Height;

            // Console.Out.WriteLine("Creating quad with " + this.rectangle + " this.GetDepth() = " + this.GetDepth() + ", maxDepth = " + tree.depth);
            if (this.GetDepth() == tree.depth)
            {
                this.isLeaf = true;
                tree.leafList.AddLast(this);

                if (tree.collisionMap.game != null)
                {

                    if (!tree.collisionMap.drawMode)
                    {
                        this.collisionTexture = new CollisionTexture(this, tree.collisionMap.game.Content.Load<Texture2D>
                        (tree.collisionMap.collisionMapPath + "/" + tree.collisionMap.collisionMapName + "_" + imageX + "_" + imageY));
                    }
                    else this.collisionTexture = new CollisionTexture(this, new Texture2D(tree.collisionMap.graphicsDevice,
                            this.rectangle.Width, this.rectangle.Height));
                }
                else
                {
                    this.collisionTexture = new CollisionTexture(this, new Texture2D(tree.collisionMap.graphicsDevice,
                        this.rectangle.Width, this.rectangle.Height));
                }
            }
        }
Example #6
0
 /// <summary>
 /// Init SLQuad with Custom Quad Parameters
 /// </summary>
 /// <param name="gd"></param>
 /// <param name="service"></param>
 /// <param name="path"></param>
 /// <param name="quad"></param>
 public SLQuad(GraphicsDevice gd, IServiceProvider service, string path, Quad quad)
     : base(gd)
 {
     Para = quad;
     LoadContent(service, path, quad.BasePara.contentname);
     Init(gd);
 }
Example #7
0
        public CollisionTexture(Quad quad, Texture2D texture)
        {
            this.quad = quad;
            this.texture = texture;

            this.textureData = new int[quad.rectangle.Width * quad.rectangle.Height];
        }
Example #8
0
        public override void Initialise(Renderer renderer, ResourceContext context)
        {
            _quad = new Quad(renderer.Device);

            //Create geometry management objects
            _geometryProviders = renderer.Scene.FindManagers<IGeometryProvider>();
            _depthPeeler = new DepthPeel();

            var settings = renderer.Settings;

            // 1 - Min
            // 5 - Default
            // 10 - Extreme
            settings.Add("transparency_deferred_layers", "the max number of depth peeled layers to use for deferred transparency", 5);

            //Make sure deferred lighting is enabled
            LightingComponent.SetupScene(renderer.Scene, out _directLights, out _indirectLights);

            // define inputs
            context.DefineInput("gbuffer_depth");
            context.DefineInput("gbuffer_normals");
            context.DefineInput("gbuffer_diffuse");
            context.DefineInput("lightbuffer");

            //define outputs
            context.DefineOutput("gbuffer_depth");
            context.DefineOutput("lightbuffer", isLeftSet: true, surfaceFormat: SurfaceFormat.HdrBlendable, depthFormat: DepthFormat.Depth24Stencil8);

            base.Initialise(renderer, context);
        }
Example #9
0
 public void Initialize()
  {
      // TODO: Add your initialization logic here
      quad = new Quad( Vector3.Zero, Vector3.Backward, Vector3.Up, 1, 1 );
      View = Matrix.CreateLookAt( new Vector3( 0, 0, 2 ), Vector3.Zero, Vector3.Up );
      Projection = Matrix.CreatePerspectiveFieldOfView( MathHelper.PiOver4, 4.0f / 3.0f, 1, 500 );
  }
        protected override DX11IndexedGeometry GetGeom(DX11RenderContext context, int slice)
        {
            Quad quad = new Quad();
            quad.Size = this.FSize[slice];

            return context.Primitives.QuadCross(quad);
        }
	private int GetSortingOrder(Quad newQuad, List<Building> buildings) {
		int numberToCheck = Mathf.Min(buildings.Count, numBuildingsToCheck);
		int sortingOrder;
		int? sortingOrderUpperLimit = null;
		int? sortingOrderLowerLimit = null;

		for (int i = 1; i <= numberToCheck; i++) {
			int index = buildings.Count - i;
			Building otherBuilding = buildings[index];
			Quad otherQuad = otherBuilding.attributes.quad;
			if (!Quad.OverlapQuads(newQuad, otherQuad)) continue;
			if (newQuad.ContainsTopPointsFromOtherQuad(otherQuad)) {
				if (sortingOrderUpperLimit != null) sortingOrderUpperLimit = Mathf.Min((int)sortingOrderUpperLimit, otherBuilding.attributes.sortingOrder);
				else sortingOrderUpperLimit = otherBuilding.attributes.sortingOrder;
			}
			else if (otherQuad.ContainsTopPointsFromOtherQuad(newQuad)) {
				if (sortingOrderLowerLimit != null) sortingOrderLowerLimit = Mathf.Max((int)sortingOrderLowerLimit, otherBuilding.attributes.sortingOrder);
				else sortingOrderLowerLimit = otherBuilding.attributes.sortingOrder;
			}
		}

		if (sortingOrderLowerLimit == null && sortingOrderUpperLimit == null) sortingOrder = baseSortingOrder;
		else if (sortingOrderLowerLimit == null) sortingOrder = (int)sortingOrderUpperLimit - 10;
		else if (sortingOrderUpperLimit == null) sortingOrder = (int)sortingOrderLowerLimit + 10;
		else sortingOrder = ((int)sortingOrderUpperLimit + (int)sortingOrderLowerLimit) / 2;

		return sortingOrder;
	}
Example #12
0
 /// <summary>
 /// Init SLQuad with Default Quad Parameters and Custom Texture
 /// </summary>
 /// <param name="gd"></param>
 /// <param name="service"></param>
 /// <param name="path"></param>
 /// <param name="texture"></param>
 public SLQuad(GraphicsDevice gd, IServiceProvider service, string path, string texture)
     : base(gd)
 {
     Para = Quad.Default;
     LoadContent(service, path, texture);
     Init(gd);
 }
Example #13
0
        private static void ReflectEdgesRecursive( Sphere[] mirrors, Quad[] quads, 
			List<Quad> allQuads, HashSet<Vector3D> completed )
        {
            if( 0 == quads.Length )
                return;

            List<Quad> newQuads = new List<Quad>();

            foreach( Quad quad in quads )
            //foreach( Sphere mirror in mirrors )
            {
                Sphere mirror = mirrors[3];
                Quad newQuad = quad.Clone();

                for( int i = 0; i < newQuad.Verts.Length; i++ )
                    newQuad.Verts[i] = mirror.ReflectPoint( newQuad.Verts[i] );

                if( completed.Add( newQuad.ID ) )
                {
                    // Haven't seen this yet, so
                    // we'll need to recurse on it.
                    allQuads.Add( newQuad );
                    newQuads.Add( newQuad );
                }
            }

            //ReflectEdgesRecursive( mirrors, newQuads.ToArray(), allQuads, completed );
        }
Example #14
0
        public void Render(GraphicsDeviceManager graphics, Matrix cameraViewMatrix, Matrix cameraProjectionMatrix, ParticleSystem system, Entity camera)
        {
            // TODO: Fix.

            Vector3 ps = new Vector3(pos.X, pos.Y, pos.Z);
            if (relativePosition)
            {
                ps += system.position;
            }

            Matrix billboardMatrix = Matrix.CreateBillboard(pos, camera.position, camera.getUpVector(), camera.getForwardVector());

            if (quad == null)
            {
            }
            quad = new Quad(ps, Vector3.Backward, Vector3.Up, size, size);
            quadVertexDeclaration = new VertexDeclaration(graphics.GraphicsDevice, VertexPositionNormalTexture.VertexElements);

            foreach (VertexPositionNormalTexture v in quad.Vertices)
            {
                Vector3.Transform(v.Position, billboardMatrix);
            }

            graphics.GraphicsDevice.VertexDeclaration = quadVertexDeclaration;
            graphics.GraphicsDevice.DrawUserIndexedPrimitives
                <VertexPositionNormalTexture>(
                PrimitiveType.TriangleList,
                quad.Vertices, 0, 4,
                quad.Indexes, 0, 2);
        }
Example #15
0
 public Viewport()
 {
     _extent = new BoundingBox(0, 0, 0, 0);
     _windowExtent = new Quad();
     RenderResolutionMultiplier = 1;
     _center.PropertyChanged += (sender, args) => _modified = true; 
 }
Example #16
0
        static void Main(string[] args)
        {
            Vector v1 = new Vector(0F, 5F, 0F);
            Vector v2 = new Vector(5F, 5F, 0F);
            Vector v3 = new Vector(0F, 5F, 5F);
            Vector v4 = new Vector(5F, 5F, 5F);
            Quad quad = new Quad(v1, v2, v3, v4, new MyColor(0F, 0F, 0F));
            List<Quad> quads = new List<Quad>();
            quads.Add(quad);

            Vector observer = new Vector(2F, 6.5F, 3F);

            float distanceToGround = MovingTools.DistanceToGround(observer, quads);

            /*
            float Distance = MovingTools.PointToPlaneDistance(observer, v1, v2, v3);
            Console.WriteLine("distance: " + Distance.ToString());

            bool intersectWithWall = MovingTools.PointIsWithinRangeOfTriangle(10F, observer, v1, v2, v3);
            Console.WriteLine("intersection?: " + intersectWithWall);

            v1 = new Vertex(10F, 0F, 0F);
            v2 = new Vertex(10F, 3F, 0F);
            v3 = new Vertex(0F, 3F, 0F);

            observer = new Vertex(8F, 0.1F, 0.1F);

            intersectWithWall = MovingTools.PointIsWithinRangeOfTriangle(1F, observer, v1, v2, v3);
            Console.WriteLine("intersection?: " + intersectWithWall);

            */

            Console.ReadKey();
        }
Example #17
0
        public Player(GraphicsDeviceManager _graphics )
        {
            graphics = _graphics;
            spriteEffect = new BasicEffect(graphics.GraphicsDevice);

            Position = new Quad(new Vector3(0, 50, 0), Vector3.Backward, Vector3.Up, 100, 100);
        }
Example #18
0
        public static bool AdjustPointToNotGoThroughQuad(float MinDistance, ref Vector observer, Quad quad)
        {
            Vector ab = quad.vertices[0].Difference(quad.vertices[1]);
            Vector ad = quad.vertices[0].Difference(quad.vertices[3]);
            Vector N = ab.CrossProduct(ad);

            float d = -N.DotProduct(quad.vertices[0]);
            float t = -(d + observer.DotProduct(N)) / (N.DotProduct(N));
            float Distance = (float)Math.Abs(t * N.Length());

            if (Distance > MinDistance)
                return false;   //too far away, regardless of where you are relative to the wall

            Vector projectionOntoTriangle = new Vector(observer.x + t * N.x, observer.y + t * N.y, observer.z + t * N.z);

            if (!PointIsInQuad(projectionOntoTriangle, quad))
                return false;   //outside the quad

            //the point needs to be moved
            float NormalMultiplier = MinDistance / N.Length();
            if (N.x / (observer.x - projectionOntoTriangle.x) < 0
                || N.y / (observer.y - projectionOntoTriangle.y) < 0
                || N.z / (observer.z - projectionOntoTriangle.z) < 0)
                NormalMultiplier *= -1.0F;

            observer = new Vector(projectionOntoTriangle.x + N.x * NormalMultiplier, projectionOntoTriangle.y + N.y * NormalMultiplier, projectionOntoTriangle.z + N.z * NormalMultiplier);
            return true;
        }
Example #19
0
        public Quad[] Divide(Quad quad, int recursion)
        {
            var minx = quad.minx;
            var miny = quad.miny;
            var maxx = quad.maxx;
            var maxy = quad.maxy;
            if (recursion == 0) {
                for (var y = miny; y < maxy; y++) {
                    for (var x = minx; x < maxx; x++) {
                        var c = _img.GetPixel(x, y);
                        if (c.a >= _alphaThreshold)
                            return new Quad[]{ quad };
                    }
                }
                return new Quad[0];
            }

            var midx = (minx + maxx) >> 1;
            var midy = (miny + maxy) >> 1;
            var quad0 = Divide(new Quad(minx, miny, midx, midy), recursion - 1);
            var quad1 = Divide(new Quad(midx, miny, maxx, midy), recursion - 1);
            var quad2 = Divide(new Quad(minx, midy, midx, maxy), recursion - 1);
            var quad3 = Divide(new Quad(midx, midy, maxx, maxy), recursion - 1);
            var nQuads = quad0.Length + quad1.Length + quad2.Length + quad3.Length;

            if (quad0.Length == 1 && quad1.Length == 1 && quad2.Length == 1 && quad3.Length == 1)
                return new Quad[]{ quad };

            var list = new List<Quad>(nQuads);
            list.AddRange(quad0);
            list.AddRange(quad1);
            list.AddRange(quad2);
            list.AddRange(quad3);
            return list.ToArray();
        }
Example #20
0
        public Beacon( int index, Vector3 position, bool active )
        {
            rotationScale = Matrix.CreateScale( .5f );
              Position = position;
              Active = active;

              ContentManager content = ZombieCraft.Instance.Content;
              model = content.Load<StillModel>( "Models/beacon" );

              Texture2D haloTexture = content.Load<Texture2D>( "Textures/halo" );
              Vector3[] verts =
              {
            new Vector3(-1f, 0f,-1f ),
            new Vector3( 1f, 0f,-1f ),
            new Vector3( 1f, 0f, 1f ),
            new Vector3(-1f, 0f, 1f ),
              };
              halo = new Quad( verts, Position, haloTexture );

              switch ( index )
              {
            case 0:
              label = content.Load<Texture2D>( "Textures/beaconLabelA" );
              break;
            case 1:
              label = content.Load<Texture2D>( "Textures/beaconLabelB" );
              break;
            case 2:
              label = content.Load<Texture2D>( "Textures/beaconLabelX" );
              break;
              }
        }
Example #21
0
        public void Gen()
        {
            Vector3D[] verts = Verts( m_m, m_k );
            Sphere[] tet = Tetrahedron( verts );
            Quad quad = new Quad() { Verts = verts };

            // We need to avoid infinities.
            //tet = tet.Select( s => H3Models.UHSToBall( s ) ).ToArray();
            //for( int i=0; i<quad.Verts.Length; i++ )
            //	quad.Verts[i] = H3Models.UHSToBall( quad.Verts[i] );

            // Reflect it around.
            //Quad[] quads = new Quad[] { quad };
            Quad[] quads = CalcQuads( tet, quad );

            List<H3.Cell.Edge> edges = new List<H3.Cell.Edge>();
            foreach( Quad q in quads )
            {
                q.R3toS3();
                edges.AddRange( q.GenEdges() );
            }

            string filename = string.Format( "lawson_{0}_{1}.pov", m_m, m_k );
            PovRay.WriteEdges( new PovRay.Parameters() { AngularThickness = 0.01 },
                Geometry.Spherical, edges.ToArray(), filename, append: false );
        }
Example #22
0
        public QuadContainer(int startX, int endX, int startZ, int endZ, ref Quad[] quads, int quadCountZ)
        {
            int quadsX = endX - startX;
            int quadsZ = endZ - startZ;
            bool singleX = quadsX == 0;
            bool singleZ = quadsZ == 0;
            int quadsXhalf = quadsX / 2;
            int quadsZhalf = quadsZ / 2;
            if(singleX && singleZ)
            {
                ContainedQuad = startX * quadCountZ + startZ;
                Bounds = quads[ContainedQuad].Bounds;
            }
            else if (singleZ || quadsX / 2 >= quadsZ)
            {
                // -------------
                // |     |     |
                // -------------
                SubContainer = new List<QuadContainer>(2)
                                   {
                                       new QuadContainer(startX, startX + quadsXhalf, startZ, endZ, ref quads, quadCountZ),
                                       new QuadContainer(startX + quadsXhalf + 1, endX, startZ, endZ, ref quads, quadCountZ)
                                   };
                Bounds = GetContainingBounds(SubContainer.Select(quad => quad.Bounds));

            }
            else if (singleX || quadsZ / 2 >= quadsX)
            {
                // ----
                // |  |
                // ----
                // |  |
                // ----

                SubContainer = new List<QuadContainer>(2)
                                   {
                                       new QuadContainer(startX, endX, startZ, startZ + quadsZhalf, ref quads, quadCountZ),
                                       new QuadContainer(startX, endX, startZ + quadsZhalf + 1, endZ, ref quads, quadCountZ)
                                   };
                Bounds = GetContainingBounds(SubContainer.Select(quad => quad.Bounds));
            }
            else
            {
                // ---------
                // | 1 | 2 |
                // ---------
                // | 3 | 4 |
                // ---------
                SubContainer = new List<QuadContainer>(4)
                                   {
                                       new QuadContainer(startX, startX + quadsXhalf, startZ, startZ + quadsZhalf, ref quads, quadCountZ),
                                       new QuadContainer(startX + quadsXhalf + 1, endX, startZ, startZ + quadsZhalf, ref quads, quadCountZ),
                                       new QuadContainer(startX, startX + quadsXhalf, startZ + quadsZhalf + 1, endZ, ref quads, quadCountZ),
                                       new QuadContainer(startX + quadsXhalf + 1, endX, startZ + quadsZhalf + 1, endZ, ref quads, quadCountZ)
                                   };
                Bounds = GetContainingBounds(SubContainer.Select(quad => quad.Bounds));
            }
            BoundingBox = CreateBoundingBox(Bounds);
        }
		public SystemFontObject()
		{
			this.Quad = new Quad(Vector2.Zero, Vector2.Zero, System.Drawing.Color.White);
			this.Quad.Vertices[0].TexCoord = new Vector2(0, 0);
			this.Quad.Vertices[1].TexCoord = new Vector2(1, 0);
			this.Quad.Vertices[2].TexCoord = new Vector2(1, 1);
			this.Quad.Vertices[3].TexCoord = new Vector2(0, 1);
		}
Example #24
0
        public AntiAliasComponent(GraphicsDevice device, string inputResource = null)
        {
            _device = device;

            _fxaa = new Material(Content.Load<Effect>("FXAA"), "FXAA");
            _quad = new Quad(device);
            _inputResource = inputResource;
        }
Example #25
0
        public LightingComponent(GraphicsDevice device)
        {
            _quad = new Quad(device);
            _quad.SetPosition(depth: 0.99999f);

            _restoreDepth = new Material(Content.Load<Effect>("RestoreDepth"));
            _copyTexture = new Material(Content.Load<Effect>("CopyTexture"));
        }
Example #26
0
 private static Quad[] CalcQuads( Sphere[] mirrors, Quad start )
 {
     List<Quad> allQuads = new List<Quad>();
     allQuads.Add( start );
     HashSet<Vector3D> completed = new HashSet<Vector3D>( new Vector3D[] { start.ID } );
     ReflectEdgesRecursive( mirrors, new Quad[] { start }, allQuads, completed );
     return allQuads.ToArray();
 }
Example #27
0
        public static void DrawQuad(Effect effect, Quad quad, GraphicsDevice gd)
        {
            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();

                gd.DrawUserIndexedPrimitives<VertexPositionNormalTexture>(PrimitiveType.TriangleList, quad.Vertices, 0, 4, quad.Indexes, 0, 2);
            }
        }
Example #28
0
        /// <summary>
        /// Constructor for corridor. TODO: Add user-selectable textures.
        /// </summary>
        /// <param name="xMin"></param>
        /// <param name="yMin"></param>
        /// <param name="zMin"></param>
        /// <param name="xMax"></param>
        /// <param name="yMax"></param>
        /// <param name="zMax"></param>
        public Corridor(float xMin, float yMin, float zMin, float xMax, float yMax, float zMax)
            : base(xMin, yMin, zMin, xMax, yMax, zMax)
        {
            XMin = xMin;
            YMin = yMin;
            ZMin = zMin;
            XMax = xMax;
            YMax = yMax;
            ZMax = zMax;

            //texture no: 5, length 16, height 1
            m_leftWall = new Quad(7, 100, 3,
                                            new Vector3f(XMin, YMin, ZMin),
                                            new Vector3f(XMin, YMin, ZMax),
                                            new Vector3f(XMin, YMax, ZMax),
                                            new Vector3f(XMin, YMax, ZMin)
                                         );

            //texture no: 0, length 16, height 1
            m_rightWall = new Quad(7, 100, 3,
                                                        new Vector3f(XMax, YMin, ZMax),
                                                        new Vector3f(XMax, YMin, ZMin),
                                                        new Vector3f(XMax, YMax, ZMin),
                                                        new Vector3f(XMax, YMax, ZMax)
                                                      );

            m_floor = new Quad(4, 500, 5,
                                                    new Vector3f(XMin, YMin, ZMax),
                                                    new Vector3f(XMin, YMin, ZMin),
                                                    new Vector3f(XMax, YMin, ZMin),
                                                    new Vector3f(XMax, YMin, ZMax)
                                                  );

            m_ceiling = new Quad(0, 500, 5,
                                                        new Vector3f(XMin, YMax, ZMin),
                                                        new Vector3f(XMin, YMax, ZMax),
                                                        new Vector3f(XMax, YMax, ZMax),
                                                        new Vector3f(XMax, YMax, ZMin)
                                                    );
            m_ceiling.Colour = new Colour(0.8f, 0.8f, 0.8f, 0.0f);



            //CollisionModel = new List<BoundingBox>();

            //Enlarge collision models to 3D
            m_leftWall.CollisionModel.XMin -= 2.0f;
            m_rightWall.CollisionModel.XMax += 2.0f;
            m_floor.CollisionModel.YMin -= 2.0f;
            m_ceiling.CollisionModel.YMax += 2.0f;

            //CollisionModel.Add(m_leftWall.CollisionModel);
            //CollisionModel.Add(m_rightWall.CollisionModel);
            //CollisionModel.Add(m_floor.CollisionModel);
            //CollisionModel.Add(m_ceiling.CollisionModel);

        }
Example #29
0
   /**
     <summary>Creates a new text markup on the specified page, making it printable by default.
     </summary>
     <param name="page">Page to annotate.</param>
     <param name="text">Annotation text.</param>
     <param name="markupType">Markup type.</param>
     <param name="markupBox">Quadrilateral encompassing a word or group of contiguous words in the
     text underlying the annotation.</param>
   */
   public TextMarkup(
 Page page,
 string text,
 MarkupTypeEnum markupType,
 Quad markupBox
 )
       : this(page, text, markupType, new List<Quad>(){markupBox})
   {
   }
Example #30
0
        public Truck(Point init, int delta = -1)
        {
            start_d = init;
            this.delta = delta;
            wheel_radius = 15;

            Point wh1, wh2, wh3, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16;

            d2 = new Point(start_d.X, start_d.Y + 40);
            d3 = new Point(d2.X - 160, d2.Y);
            d4 = new Point(d3.X, start_d.Y);
            Quad q1 = new Quad(start_d, d2, d3, d4);
            q1.SetColor(0.6f, 0.75f, 0.35f);
            figures.Add(q1);

            d5 = new Point(d3.X, d3.Y + 10);
            d6 = new Point(d5.X - 40, d5.Y - 10);
            d7 = new Point(d6.X, d4.Y);
            Quad q2 = new Quad(d4, d5, d6, d7);
            q2.SetColor(0.6f, 0.75f, 0.35f);
            figures.Add(q2);

            _length = start_d.X - d7.X;

            d8 = new Point(d3.X, d3.Y + 40);
            d9 = new Point(d8.X + 55, d8.Y);
            d10 = new Point(d9.X, d3.Y);
            Quad q3 = new Quad(d3, d8, d9, d10);
            q3.SetColor(0.6f, 0.75f, 0.35f);
            figures.Add(q3);

            d11 = new Point(d9.X, d9.Y - 5);
            d12 = new Point(d11.X, d11.Y - 5);
            d13 = new Point(d12.X + 20, d12.Y);
            d14 = new Point(d13.X, d11.Y);
            Quad q4 = new Quad(d11, d12, d13, d14);
            q4.SetColor(0.6f, 0.75f, 0.35f);
            figures.Add(q4);

            d15 = new Point(d14.X + 70, d14.Y - 35);
            d16 = new Point(d15.X - 10, d15.Y);
            Quad q5 = new Quad(d13, d14, d15, d16);
            q5.SetColor(0.6f, 0.75f, 0.35f);
            figures.Add(q5);

            wh1 = new Point(start_d.X - 25, start_d.Y);
            wh2 = new Point(wh1.X - 35, start_d.Y);
            wh3 = new Point(wh2.X - 115, start_d.Y);
            Circle wheel1 = new Circle(wh1, wheel_radius);
            Circle wheel2 = new Circle(wh2, wheel_radius);
            Circle wheel3 = new Circle(wh3, wheel_radius);

            figures.Add(wheel3);
            figures.Add(wheel2);
            figures.Add(wheel1);
        }
 private void Start()
 {
     quad = GetComponent <Quad>();
 }
Example #32
0
 // clones quad
 public static Quad Clone(Quad q)
 {
     return(new Quad(Clone(q.TopLeft), Clone(q.TopRight), Clone(q.BottomLeft), Clone(q.BottomRight)));
 }
Example #33
0
            public override void Draw(Action <TexturedVertex2D> vertexAction)
            {
                base.Draw(vertexAction);

                if (texture?.Available != true || points == null || points.Count == 0)
                {
                    return;
                }

                shader.Bind();
                texture.TextureGL.Bind();

                Vector2 localInflationAmount = new Vector2(0, 1) * DrawInfo.MatrixInverse.ExtractScale().Xy;

                // We're dealing with a _large_ number of points, so we need to optimise the quadToDraw * drawInfo.Matrix multiplications below
                // for points that are going to be masked out anyway. This allows for higher resolution graphs at larger scales with virtually no performance loss.
                // Since the points are generated in the local coordinate space, we need to convert the screen space masking quad coordinates into the local coordinate space
                RectangleF localMaskingRectangle = (Quad.FromRectangle(GLWrapper.CurrentMaskingInfo.ScreenSpaceAABB) * DrawInfo.MatrixInverse).AABBFloat;

                float separation = drawSize.X / (points.Count - 1);

                for (int i = 0; i < points.Count - 1; i++)
                {
                    float leftX  = i * separation;
                    float rightX = (i + 1) * separation;

                    if (rightX < localMaskingRectangle.Left)
                    {
                        continue;
                    }

                    if (leftX > localMaskingRectangle.Right)
                    {
                        break; // X is always increasing
                    }
                    Color4 colour = DrawColourInfo.Colour;

                    // colouring is applied in the order of interest to a viewer.
                    colour = Interpolation.ValueAt(points[i].MidIntensity / midMax, colour, midColour, 0, 1);
                    // high end (cymbal) can help find beat, so give it priority over mids.
                    colour = Interpolation.ValueAt(points[i].HighIntensity / highMax, colour, highColour, 0, 1);
                    // low end (bass drum) is generally the best visual aid for beat matching, so give it priority over high/mid.
                    colour = Interpolation.ValueAt(points[i].LowIntensity / lowMax, colour, lowColour, 0, 1);

                    Quad quadToDraw;

                    switch (channels)
                    {
                    default:
                    case 2:
                    {
                        float height = drawSize.Y / 2;
                        quadToDraw = new Quad(
                            new Vector2(leftX, height - points[i].Amplitude[0] * height),
                            new Vector2(rightX, height - points[i + 1].Amplitude[0] * height),
                            new Vector2(leftX, height + points[i].Amplitude[1] * height),
                            new Vector2(rightX, height + points[i + 1].Amplitude[1] * height)
                            );
                        break;
                    }

                    case 1:
                    {
                        quadToDraw = new Quad(
                            new Vector2(leftX, drawSize.Y - points[i].Amplitude[0] * drawSize.Y),
                            new Vector2(rightX, drawSize.Y - points[i + 1].Amplitude[0] * drawSize.Y),
                            new Vector2(leftX, drawSize.Y),
                            new Vector2(rightX, drawSize.Y)
                            );
                        break;
                    }
                    }

                    quadToDraw *= DrawInfo.Matrix;
                    DrawQuad(texture, quadToDraw, colour, null, vertexBatch.AddAction, Vector2.Divide(localInflationAmount, quadToDraw.Size));
                }

                shader.Unbind();
            }
Example #34
0
    ////////////////////////////////////////////////////////////////////////////



    // Adds all faces for the given index of the given voxels to the list of quads.
    static void AddFaces(VoxelSet <Vec4b> voxels, List <Quad> quads, Vec3i idx)
    {
        Vec3i[] normals =
        {
            new Vec3i(1,   0, 0),
            new Vec3i(-1,  0, 0),

            new Vec3i(0,   1, 0),
            new Vec3i(0,  -1, 0),

            new Vec3i(0,   0, 1),
            new Vec3i(0,   0, -1)
        };

        bool transparent = IsTransparent(voxels, idx);

        for (int i = 0; i < normals.Length; ++i)
        {
            Vec3i normal   = normals[i];
            Vec3i neighbor = idx + normal;
            if (voxels.IsValid(neighbor) && (voxels[neighbor].w > 0))
            {
                if (transparent && IsTransparent(voxels, neighbor))
                {
                    // Two transparent voxels - face is hidden.
                    continue;
                }

                if (transparent && voxels[neighbor].w == 255)
                {
                    // Transparent self and opaque neighbor - hidden to avoid z-fighting.
                    continue;
                }

                if (!transparent && voxels[neighbor].w == 255)
                {
                    // Two opaque voxels - face is hidden.
                    continue;
                }
            }

            var  c = voxels[idx];
            Quad q = new Quad();

            q.color = new Color32(c.x, c.y, c.z, c.w);

            Vec3i pos = idx;

            if (Vec3i.Dot(normal, new Vec3i(1)) > 0)
            {
                pos += normal;
            }

            q.position = new Vector3(pos.x, pos.y, pos.z);
            q.uv       = new Vector2(i, 0);

            quads.Add(q);

            if (transparent)
            {
                // Add back facing as well for transparent quads
                //q.uv = new Vector2((i - (i % 2)) + ((i + 1) % 2), 0);
                q.uv = new Vector2(i ^ 1, 0);
                //q.position += new Vector3(normal.x, normal.y, normal.z);
                quads.Add(q);
            }
        }
    }
Example #35
0
 public StructureBase(Quad _patchRelativePlot, int y_height)
 {
     setupSB(_patchRelativePlot, y_height);
 }
        private bool Search(Point pt, out double foundVal)
        {
            var grid = DataSource.Grid;

            foundVal = 0;

            int  width = DataSource.Width;
            int  height = DataSource.Height;
            bool found = false;
            int  i = 0, j = 0;

            for (i = 0; i < width - 1; i++)
            {
                for (j = 0; j < height - 1; j++)
                {
                    Quad quad = new Quad(
                        grid[i, j],
                        grid[i, j + 1],
                        grid[i + 1, j + 1],
                        grid[i + 1, j]);
                    if (quad.Contains(pt))
                    {
                        found     = true;
                        foundQuad = quad;
                        foundI    = i;
                        foundJ    = j;

                        break;
                    }
                }
                if (found)
                {
                    break;
                }
            }
            if (!found)
            {
                foundQuad = null;
                return(false);
            }

            var data = DataSource.Data;

            double x = pt.X;
            double y = pt.Y;
            Vector A = grid[i, j + 1].ToVector();                       // @TODO: in common case add a sorting of points:
            Vector B = grid[i + 1, j + 1].ToVector();                   //   maxA ___K___ B
            Vector C = grid[i + 1, j].ToVector();                       //      |         |
            Vector D = grid[i, j].ToVector();                           //      M    P    N
            double a = data[i, j + 1];                                  //		|         |
            double b = data[i + 1, j + 1];                              //		В ___L____Сmin
            double c = data[i + 1, j];
            double d = data[i, j];

            Vector K, L;
            double k, l;

            if (x >= A.X)
            {
                k = Interpolate(A, B, a, b, K = new Vector(x, GetY(A, B, x)));
            }
            else
            {
                k = Interpolate(D, A, d, a, K = new Vector(x, GetY(D, A, x)));
            }

            if (x >= C.X)
            {
                l = Interpolate(C, B, c, b, L = new Vector(x, GetY(C, B, x)));
            }
            else
            {
                l = Interpolate(D, C, d, c, L = new Vector(x, GetY(D, C, x)));
            }

            foundVal = Interpolate(L, K, l, k, new Vector(x, y));
            return(!double.IsNaN(foundVal));
        }
Example #37
0
        public static readonly int maxSteps = 5;                        // maximum steps allowed until separation of structures, in depth as well as from left to right (good for filling gaps)
        //public readonly int samples = 5;			// count of subsamples to interpolate depth (1 = off)

        public static void PerspectiefNaarEasyMesh(IList <Perspective> perspectives)
        {
            int counter = 0;

            LOG.Instance.publishMessage("START CREATING ONE MESH PER PERSPECTIVE: " + perspectives.Count + " PERSPECTIVES");
            IEnumerator <Perspective> e = perspectives.GetEnumerator();

            while (e.MoveNext())
            {
                LOG.Instance.publishMessage("Start creating mesh " + ++counter + " out of" + perspectives.Count + " meshes");
                lock (e.Current)
                {
                    int   i, k, x, y, depthPos, j;
                    float xf, yf, zf;
                    int[] vertIdx = new int[e.Current.XRes * e.Current.YRes];
                    for (i = 0, j = 0; i < 640 * 480; i++)
                    {
                        depthPos = (int)e.Current.Depth[i];
                        if (depthPos > 340 && depthPos < 1081)
                        {
                            j++;
                        }
                    }
                    Vertex[]     vertices = new Vertex[j];
                    IList <Face> faces    = new List <Face>();

                    // apply noise filter
                    // perform smoothing filter to remove noise (use iterations here to remove low frequency noise better)
                    int colorIndex = 0;
                    for (y = 0, i = 0, j = 0; y < e.Current.XRes; y++)
                    {
                        for (x = 0; x < e.Current.YRes; x++, i++)
                        {
                            //j = (y * e.Current.YRes + x) * 3;
                            // numbers seems to be in ranges:
                            // extrema 18,1120
                            // 2 rooms +floor (~13m) 1064
                            // 1 room +floor (~7m) 1045
                            // 6.0m 1038
                            // 1.7m 875
                            // 1.0m 765
                            // 0.6m 456
                            // 0.5m 370 minimum measureable distance
                            depthPos = (int)e.Current.Depth[i];
                            if (depthPos > 380 && depthPos < 1081)
                            {
                                colorIndex = (y * 640 + x) * 3;
                                xf         = (float)x;
                                yf         = (float)y;
                                zf         = (float)e.Current.Depth[i];
                                zf         = -(1 / ((zf - 1091) / 355)); // convert depth to meters, see diagrams for details... 351=0.48m, 1080=32m, 1090=355m
                                xf         = (((xf - 320) / 320) * zf);  // perspective correction for X displacement of 57° FOV * .5f
                                yf         = ((yf - 240) / 240) * zf;    // perspective correction for Y TODO correction still needed  * .4f
                                if (float.IsNaN(xf) || float.IsInfinity(xf) || xf < -100 || xf > 100)
                                {
                                    xf = 0;
                                }
                                if (float.IsNaN(yf) || float.IsInfinity(yf) || yf < -100 || yf > 100)
                                {
                                    yf = 0;
                                }
                                if (float.IsNaN(zf) || float.IsInfinity(zf) || zf < -100 || zf > 100)
                                {
                                    zf = 0;
                                }
                                // store vertex coordinates]
                                vertices[j]          = new Vertex();
                                vertices[j].Position = new Vector3(xf, -yf, -zf);
                                vertices[j].RGBB     = e.Current.CopyPixels()[y, x].Blue;
                                vertices[j].RGBG     = e.Current.CopyPixels()[y, x].Green;
                                vertices[j].RGBR     = e.Current.CopyPixels()[y, x].Red;

                                /*vertex[(y * 640 + x) * 3 + 0] = ;
                                 * vertex[(y * 640 + x) * 3 + 1] = -yf;
                                 * vertex[(y * 640 + x) * 3 + 2] = -zf;*/
                                //vertIdx[i] = j;	// store indices for further processing
                                j++;
                            }
                        }
                    }

                    /*if (useFilter != 0)
                     * {
                     *  // (float factor, int iterations, float surfacePreserve, short radius, short shape, short fallOff)
                     *  filterVertices(0.5f, 2, 0, 0, 0, 0);
                     *  filterVertices(0.5f, 20, 1.0f, 8, 1, 1);
                     *  filterVertices(0.5f, 20, 1.0f, 8, 2, 1);
                     *  filterVertices(0.5f, 20, 0.5f, 2, 1, 3);
                     *  filterVertices(0.5f, 20, 0.5f, 2, 2, 3);
                     *  //		filterVertices(.95, 50, .05, 2, 0, 3);
                     * }*/

                    //for (int ii = 0; ii < rgb.Length; ii++) { rgb[ii] = 100; }//TODO vervangen voor echte kleurwaarden
                    // save vertices to file

                    // save faces
                    for (y = 1; y < e.Current.YRes; y++)
                    {
                        for (x = 1; x < e.Current.XRes; x++)
                        {
                            depthPos = (int)e.Current.Depth[y * e.Current.XRes + x];
                            if (depthPos > 340 && depthPos < 1081)
                            {
                                k        = depthPos;
                                depthPos = (int)e.Current.Depth[(y - 1) * 640 + (x - 1)];
                                if (depthPos > 340 && depthPos < 1081 && depthPos > k - maxSteps && depthPos < k + maxSteps)
                                {
                                    k        = depthPos;
                                    depthPos = (int)e.Current.Depth[y * 640 + x - 1];
                                    if (depthPos > 340 && depthPos < 1081 && depthPos > k - maxSteps && depthPos < k + maxSteps)
                                    {
                                        k        = depthPos;
                                        depthPos = (int)e.Current.Depth[(y - 1) * 640 + x];
                                        if (depthPos > 340 && depthPos < 1081 && depthPos > k - maxSteps && depthPos < k + maxSteps)
                                        {
                                            Quad q = new Quad();
                                            q.Point1 = vertices[vertIdx[(y - 1) * 640 + (x - 1)]];
                                            q.Point2 = vertices[vertIdx[y * 640 + x - 1]];
                                            q.Point3 = vertices[vertIdx[y * 640 + x]];
                                            q.Point4 = vertices[vertIdx[(y - 1) * 640 + x]];
                                            faces.Add(q);
                                            //tw.Write("4 {0:d} {0:d} {0:d} {0:d}\n", );	// save a quad if possible, but those will be reduced to triangles by opengl. Still ply doesn't do that
                                        }
                                        else
                                        {
                                            Triangle t = new Triangle();
                                            t.Point1 = vertices[vertIdx[y * 640 + x]];
                                            t.Point2 = vertices[vertIdx[(y - 1) * 640 + (x - 1)]];
                                            t.Point3 = vertices[vertIdx[y * 640 + x - 1]];
                                            faces.Add(t);
                                            //mesh.Faces.Add(new Triangel(
                                            //    mesh.vertices[vertIdx[y * 640 + x]],
                                            //    mesh.vertices[vertIdx[(y - 1) * 640 + (x - 1)]],
                                            //    mesh.vertices[vertIdx[y * 640 + x - 1]]));
                                            //tw.Write("3 {0:d} {0:d} {0:d}\n",); // in case there are not enough vertices for a quad save a triangle
                                        }
                                    }
                                    else
                                    {
                                        depthPos = (int)e.Current.Depth[(y - 1) * 640 + x];
                                        if (depthPos > 340 && depthPos < 1081 && depthPos > k - maxSteps && depthPos < k + maxSteps)
                                        {
                                            Triangle t = new Triangle();
                                            t.Point1 = vertices[vertIdx[(y - 1) * 640 + (x - 1)]];
                                            t.Point2 = vertices[vertIdx[y * 640 + x]];
                                            t.Point3 = vertices[vertIdx[(y - 1) * 640 + x]];
                                            faces.Add(t);
                                            //mesh.Faces.Add(
                                            //new Triangel(
                                            //    mesh.Vertices[vertIdx[(y - 1) * 640 + (x - 1)]],
                                            //    mesh.Vertices[vertIdx[y * 640 + x]],
                                            //    mesh.Vertices[vertIdx[(y - 1) * 640 + x]])); // in case there are not enough vertices for a quad save a triangle
                                        }
                                    }
                                }
                            }
                        }
                    }
                    BeeldOpslag.Instance.registerMesh(new Mesh(faces, vertices), e.Current);
                }
            }
            LOG.Instance.publishMessage("START CREATING ONE MESH PER PERSPECTIVE: DONE");
        }
Example #38
0
 /// <summary>
 /// Accepts a rectangle in local coordinates and converts it to a quad in Parent's space.
 /// </summary>
 /// <param name="input">A rectangle in local coordinates.</param>
 /// <returns>The quad in Parent's coordinates.</returns>
 public Quad ToParentSpace(RectangleF input)
 {
     return(Quad.FromRectangle(input) * (DrawInfo.Matrix * Parent.DrawInfo.MatrixInverse));
 }
Example #39
0
 /// <summary>
 /// Accepts a rectangle in local coordinates and converts it to a quad in screen space.
 /// </summary>
 /// <param name="input">A rectangle in local coordinates.</param>
 /// <returns>The quad in screen coordinates.</returns>
 public Quad ToScreenSpace(RectangleF input)
 {
     return(Quad.FromRectangle(input) * DrawInfo.Matrix);
 }
Example #40
0
 protected virtual bool CheckForcedPixelSnapping(Quad screenSpaceQuad)
 {
     return(false);
 }
Example #41
0
    public Tree(PTwo _patchRelOrigin, int y_height, float _seed, bool adjustOriginWithOffset)
    {
        seed = _seed;
        int structure_height = 8;

        structure_height += (int)(Utils.DecimatLeftShift(seed, 1) * structure_height * .33f);

        int length = 6;

        length += (int)(Utils.DecimatLeftShift(seed, 3) * length * .33f);
        if (length % 2 == 0)
        {
            length++;
        }

        Coord dimensions = new Coord(length, structure_height, length);         // TEST

        int  rel_trunk_coord = length / 2;
        PTwo center_coord    = new PTwo(rel_trunk_coord, rel_trunk_coord);

        int trunk_height = 3 + (int)(1 * Utils.DecimatLeftShift(seed, 5));

#if NO_RANDOMNESS
        structure_height = 8;
        length           = 6;
        trunk_height     = 3;
        dimensions       = new Coord(length * 0 + 2, structure_height, length);   // TEST
        center_coord     = new PTwo(rel_trunk_coord * 0 + 1, rel_trunk_coord);
#endif

#if TREE_OFFSET_METHOD
        //shift the origin to put the trunk at the coord that noise patch chose
        if (adjustOriginWithOffset)                           //don't do this if "copying" for a section
        {
            _patchRelOrigin = _patchRelOrigin - center_coord; // no, need a different way?
        }
#endif

        Quad _patchRelPlot = new Quad(_patchRelOrigin, PTwo.PTwoXZFromCoord(dimensions));

        setupSB(_patchRelPlot, y_height);

        //ground level plot
        this.groundLevelPlot = Quad.UnitQuadWithPoint(center_coord);

//		if (this.plot.dimensions.isIndexSafe(center_coord))
//		{
//			Range1D trunk_range = new Range1D(0, structure_height - 1, BlockType.TreeTrunk); // change later to wood
//			Range1D top_leaves = new Range1D(structure_height - 1, 1, BlockType.TreeLeaves); // change later
//			List<Range1D> center_list = new List<Range1D>() {trunk_range, top_leaves};
//			ranges[center_coord.s , center_coord.t ] = center_list;
//		}

        int number_of_tapers    = 3;
        int foliage_base_height = structure_height - trunk_height - number_of_tapers;


        PTwo relation_to_center;
        PTwo cur_coord;

        int i = 0; int j = 0;
        int i_end = this.plot.dimensions.s;
        int j_end = this.plot.dimensions.t;
#if TREE_OFFSET_METHOD
        i = this.constructOffsetStart.s;

        i_end = this.undividedDimensions.s - this.constructOffsetEnd.s;
        j_end = this.undividedDimensions.t - this.constructOffsetEnd.t;
#endif


        for (; i < i_end; ++i)
        {
            j = 0;
#if TREE_OFFSET_METHOD
            j = this.constructOffsetStart.t;
#endif
            for (; j < j_end; ++j)
            {
                if (i == center_coord.s && j == center_coord.t)                                              //center, already done
                {
                    Range1D        trunk_range = new Range1D(0, structure_height - 1, BlockType.TreeTrunk);  // change later to wood
                    Range1D        top_leaves  = new Range1D(structure_height - 1, 1, BlockType.TreeLeaves); // change later
                    List <Range1D> center_list = new List <Range1D>()
                    {
                        trunk_range, top_leaves
                    };
                    ranges[center_coord.s - constructOffsetStart.s, center_coord.t - constructOffsetStart.t] = center_list;
                    continue;
                }

                cur_coord          = new PTwo(i, j);
                relation_to_center = center_coord - PTwo.Abs(cur_coord - center_coord);

                if (relation_to_center.s + relation_to_center.t <= 1)                 //corners
                {
                    continue;
                }

                int foliage_height = foliage_base_height + Mathf.Min(number_of_tapers, PTwo.LesserDimension(relation_to_center));
                int foliage_start  = trunk_height;

                if (PTwo.LesserDimension(relation_to_center) < 1)
                {
                    foliage_start++;
                    foliage_height--;
                }

                List <Range1D> ij_ranges = new List <Range1D>()
                {
                    new Range1D(foliage_start, foliage_height, BlockType.TreeLeaves)
                };

#if TREE_OFFSET_METHOD
                ranges[i - constructOffsetStart.s, j - constructOffsetStart.t] = ij_ranges;
#else
                ranges[i, j] = ij_ranges;
#endif
            }
        }
    }
Example #42
0
        public override void Draw(IDrawer drawer)
        {
            RefreshBuffers();
            if (_vertexArray == null)
            {
                return;
            }

            GraphicsDevice graphicsDevice = drawer.GraphicsDevice;
            Quad           rect           = drawer.DisplayedRectangle;

            // Configure default effect matrices
            _defaultEffect.World      = SceneNode.Matrix.ToMatrix4X4(SceneNode.Depth);
            _defaultEffect.View       = Matrix.CreateLookAt(Vector3.Backward, Vector3.Zero, Vector3.Up);
            _defaultEffect.Projection = Matrix.CreateOrthographicOffCenter(rect.Left, rect.Right, rect.Bottom, rect.Top, float.MinValue / 2, float.MaxValue / 2);

            drawer.SpriteBatchStack.Push(null);

            int        verticesIndex = 0;
            int        indicesIndex  = 0;
            Effect     currentEffect = null;
            EffectPass currentPass   = null;

            foreach (IVisualMesh mesh in Meshes)
            {
                // If mesh not visible, move indexes and go to next
                if (!mesh.Visible)
                {
                    verticesIndex += mesh.VertexCount;
                    indicesIndex  += mesh.TriangulationIndexCount;
                    continue;
                }

                bool meshIndexed = mesh.TriangulationIndexCount > 0;

                foreach (IVisualMeshPart part in mesh.Parts)
                {
                    Effect effect = part.Effect;
                    if (effect == null)
                    {
                        // If no effect provided, use default effect
                        effect = _defaultEffect;

                        // Enable texture if necessary
                        _defaultEffect.TextureEnabled = TextureSource?.Texture != null;//material.Textures.Count > 0;
                    }
                    else if (effect != currentEffect)
                    {
                        // Configure effect matrices
                        IEffectMatrices effectMatrices = part.EffectMatrices;
                        if (effectMatrices != null)
                        {
                            effectMatrices.World      = _defaultEffect.World;
                            effectMatrices.View       = _defaultEffect.View;
                            effectMatrices.Projection = _defaultEffect.Projection;
                        }

                        currentEffect = effect;
                    }

                    foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                    {
                        if (pass != currentPass)
                        {
                            // Apply effect pass
                            pass.Apply();
                            currentPass = pass;
                        }

                        // Interesting links:
                        // http://www.shawnhargreaves.com/blog/spritebatch-billboards-in-a-3d-world.html
                        // https://github.com/MonoGame/MonoGame/blob/3e65abb158de2e07c72d0831dd971f594ff76a18/MonoGame.Framework/Graphics/Effect/SpriteEffect.cs#L71
                        // https://community.monogame.net/t/solved-drawing-primitives-and-spritebatch/10015/4

                        graphicsDevice.Textures[0]      = TextureSource?.Texture;
                        graphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;

                        graphicsDevice.RasterizerState   = RasterizerState.CullCounterClockwise;
                        graphicsDevice.BlendState        = BlendState.AlphaBlend;
                        graphicsDevice.DepthStencilState = DepthStencilState.None;

                        // Draw primitives
                        if (meshIndexed)
                        {
                            int primitiveCount = GetPrimitiveCount(mesh.Type, part.TriangulationIndexCount);

                            graphicsDevice.DrawUserIndexedPrimitives(mesh.Type, _vertexArray, verticesIndex, mesh.VertexCount, _indexArray, indicesIndex, primitiveCount);
                            indicesIndex += part.TriangulationIndexCount;
                        }
                        else
                        {
                            int primitiveCount = GetPrimitiveCount(mesh.Type, part.VertexCount);

                            graphicsDevice.DrawUserPrimitives(mesh.Type, _vertexArray, verticesIndex, primitiveCount);
                            verticesIndex += part.VertexCount;
                        }
                    }
                }

                // If mesh indexed, move vertices index after all parts have been drawn.
                if (meshIndexed)
                {
                    verticesIndex += mesh.VertexCount;
                }
            }

            drawer.SpriteBatchStack.Pop();
        }
Example #43
0
        /// <summary>
        /// A getter for available gear in the Item exd files
        /// </summary>
        /// <returns>A list containing XivGear data</returns>
        public async Task <List <XivGear> > GetGearList()
        {
            // These are the offsets to relevant data
            // These will need to be changed if data gets added or removed with a patch
            const int modelDataCheckOffset = 30;
            const int dataLength           = 160;
            const int nameDataOffset       = 14;
            const int modelDataOffset      = 24;
            const int iconDataOffset       = 136;
            const int slotDataOffset       = 154;

            var xivGearList = new List <XivGear>();

            xivGearList.AddRange(GetMissingGear());

            var ex             = new Ex(_modding, _xivLanguage);
            var itemDictionary = await ex.ReadExData(XivEx.item);

            // Loops through all the items in the item exd files
            // Item files start at 0 and increment by 500 for each new file
            // Item_0, Item_500, Item_1000, etc.
            await Task.Run(() => Parallel.ForEach(itemDictionary, (item) =>
            {
                // This checks whether there is any model data present in the current item
                if (item.Value[modelDataCheckOffset] <= 0 && item.Value[modelDataCheckOffset + 1] <= 0)
                {
                    return;
                }

                // Gear can have 2 separate models (MNK weapons for example)
                var primaryMi   = new XivModelInfo();
                var secondaryMi = new XivModelInfo();

                var xivGear = new XivGear
                {
                    Category           = XivStrings.Gear,
                    ModelInfo          = primaryMi,
                    SecondaryModelInfo = secondaryMi
                };

                /* Used to determine if the given model is a weapon
                 * This is important because the data is formatted differently
                 * The model data is a 16 byte section separated into two 8 byte parts (primary model, secondary model)
                 * Format is 8 bytes in length with 2 bytes per data point [short, short, short, short]
                 * Gear: primary model [blank, blank, variant, ID] nothing in secondary model
                 * Weapon: primary model [blank, variant, body, ID] secondary model [blank, variant, body, ID]
                 */
                var isWeapon = false;

                // Big Endian Byte Order
                using (var br = new BinaryReaderBE(new MemoryStream(item.Value)))
                {
                    br.BaseStream.Seek(nameDataOffset, SeekOrigin.Begin);
                    var nameOffset = br.ReadInt16();

                    // Model Data
                    br.BaseStream.Seek(modelDataOffset, SeekOrigin.Begin);

                    // Primary Model Key
                    primaryMi.ModelKey = Quad.Read(br.ReadBytes(8), 0);
                    br.BaseStream.Seek(-8, SeekOrigin.Current);

                    // Primary Blank
                    primaryMi.Unused = br.ReadInt16();

                    // Primary Variant for weapon, blank otherwise
                    var weaponVariant = br.ReadInt16();

                    if (weaponVariant != 0)
                    {
                        primaryMi.Variant = weaponVariant;
                        isWeapon          = true;
                    }

                    // Primary Body if weapon, Variant otherwise
                    if (isWeapon)
                    {
                        primaryMi.Body = br.ReadInt16();
                    }
                    else
                    {
                        primaryMi.Variant = br.ReadInt16();
                    }

                    // Primary Model ID
                    primaryMi.ModelID = br.ReadInt16();

                    // Secondary Model Key
                    isWeapon             = false;
                    secondaryMi.ModelKey = Quad.Read(br.ReadBytes(8), 0);
                    br.BaseStream.Seek(-8, SeekOrigin.Current);

                    // Secondary Blank
                    secondaryMi.Unused = br.ReadInt16();

                    // Secondary Variant for weapon, blank otherwise
                    weaponVariant = br.ReadInt16();

                    if (weaponVariant != 0)
                    {
                        secondaryMi.Variant = weaponVariant;
                        isWeapon            = true;
                    }

                    // Secondary Body if weapon, Variant otherwise
                    if (isWeapon)
                    {
                        secondaryMi.Body = br.ReadInt16();
                    }
                    else
                    {
                        secondaryMi.Variant = br.ReadInt16();
                    }

                    // Secondary Model ID
                    secondaryMi.ModelID = br.ReadInt16();

                    // Icon
                    br.BaseStream.Seek(iconDataOffset, SeekOrigin.Begin);
                    xivGear.IconNumber = br.ReadUInt16();

                    // Gear Slot/Category
                    br.BaseStream.Seek(slotDataOffset, SeekOrigin.Begin);
                    int slotNum = br.ReadByte();

                    // Waist items do not have texture or model data
                    if (slotNum == 6)
                    {
                        return;
                    }

                    xivGear.EquipSlotCategory = slotNum;
                    xivGear.ItemCategory      = _slotNameDictionary.ContainsKey(slotNum) ? _slotNameDictionary[slotNum] : "Unknown";

                    // Gear Name
                    var gearNameOffset = dataLength + nameOffset;
                    var gearNameLength = item.Value.Length - gearNameOffset;
                    br.BaseStream.Seek(gearNameOffset, SeekOrigin.Begin);
                    var nameString = Encoding.UTF8.GetString(br.ReadBytes(gearNameLength)).Replace("\0", "");
                    xivGear.Name   = new string(nameString.Where(c => !char.IsControl(c)).ToArray());

                    lock (_gearLock)
                    {
                        xivGearList.Add(xivGear);
                    }
                }
            }));

            xivGearList.Sort();

            return(xivGearList);
        }
Example #44
0
 private void SortVerticies(Quad quad) => _verticesList.AddRange(quad.GetVerticies());
Example #45
0
        protected internal override void UpdateVertices()
        {
            if (text == null)
            {
                text = "";
            }

            Quads      = Quad.CreateSet(text.Length);
            RealLength = 0;

            // This object controls lines breaking
            var writer = new SymbolWriter(font, MaxWidth, Scale);

            // Word Size
            var metrics = new PointF();

            var paragraphs = Paragraph.Split(text);

            // Current character (used in masking)
            var pos = 0;

            foreach (var words in paragraphs.Select(paragraph => Word.Split(paragraph)))
            {
                foreach (var word in words.Where(word => word.Length != 0))
                {
                    GetWordMetrics(word, metrics);
                    writer.AddSymbol(metrics.X, metrics.Y);

                    var length = word.Length;
                    var shift  = 0f; // Position in pixels relative to the beginning of the word

                    for (var k = 0; k < length; k++)
                    {
                        var rect = ((TextureFilm)font).Get(word[k]);

                        var w = font.Width(rect);
                        var h = font.Height(rect);

                        if (Mask == null || Mask[pos])
                        {
                            Vertices[0] = writer.x + shift;
                            Vertices[1] = writer.y;

                            Vertices[2] = rect.Left;
                            Vertices[3] = rect.Top;

                            Vertices[4] = writer.x + shift + w;
                            Vertices[5] = writer.y;

                            Vertices[6] = rect.Right;
                            Vertices[7] = rect.Top;

                            Vertices[8] = writer.x + shift + w;
                            Vertices[9] = writer.y + h;

                            Vertices[10] = rect.Right;
                            Vertices[11] = rect.Bottom;

                            Vertices[12] = writer.x + shift;
                            Vertices[13] = writer.y + h;

                            Vertices[14] = rect.Left;
                            Vertices[15] = rect.Bottom;

                            Quads.Put(Vertices);
                            RealLength++;
                        }

                        shift += w + font.tracking;

                        pos++;
                    }

                    writer.AddSpace(SpaceSize);
                }

                writer.NewLine(0, font.LineHeight);
            }

            Dirty = false;
        }
Example #46
0
    public void Import(DsonTypes.Geometry geometry)
    {
        GeometryType type;

        if (geometry.type == DsonTypes.GeometryType.PolygonMesh)
        {
            type = GeometryType.PolygonMesh;
        }
        else if (geometry.type == DsonTypes.GeometryType.SubdivisionSurface)
        {
            type = GeometryType.SubdivisionSurface;
        }
        else
        {
            throw new InvalidOperationException("unrecognized geometry type: " + geometry.type);
        }

        Quad[] faces = geometry.polylist.values
                       .Select(values => {
            if (values.Length == Quad.SideCount + 2)
            {
                return(new Quad(values[2], values[3], values[4], values[5]));
            }
            else if (values.Length == Quad.SideCount + 2 - 1)
            {
                return(Quad.MakeDegeneratedIntoTriangle(values[2], values[3], values[4]));
            }
            else
            {
                throw new InvalidOperationException("expected only quads and tris");
            }
        }).ToArray();

        string[] faceGroupNames = geometry.polygon_groups.values;

        string[] surfaceNames = geometry.polygon_material_groups.values;

        int[] faceGroupMap = geometry.polylist.values
                             .Select(values => {
            return(values[0]);
        }).ToArray();

        int[] surfaceMap = geometry.polylist.values
                           .Select(values => {
            return(values[1]);
        }).ToArray();

        Vector3[] vertexPositions = geometry.vertices.values
                                    .Select(values => FromArray(values))
                                    .ToArray();

        string defaultUvSet = geometry.default_uv_set.ReferencedObject.name;

        Graft graft;

        if (geometry.graft != null && (geometry.graft.hidden_polys != null || geometry.graft.vertex_pairs != null))
        {
            Graft.VertexPair[] vertexPairs = geometry.graft.vertex_pairs.values
                                             .Select(values => new Graft.VertexPair(values[0], values[1]))
                                             .ToArray();
            int[] hiddenFaces = geometry.graft.hidden_polys.values;
            graft = new Graft(vertexPairs, hiddenFaces);
        }
        else
        {
            graft = null;
        }

        recipes.Add(new GeometryRecipe(type, faces, faceGroupMap, surfaceMap, vertexPositions, faceGroupNames, surfaceNames, defaultUvSet, graft));
    }
Example #47
0
 private void SortTriangles(int index, Quad quad) => _trianglesList.AddRange(quad.GetTriangles(AngleOffset * index));
Example #48
0
 /// <summary>
 /// Draws a quad to the screen.
 /// </summary>
 /// <param name="vertexQuad">The quad to draw.</param>
 /// <param name="drawColour">The vertex colour.</param>
 /// <param name="textureRect">The texture rectangle.</param>
 /// <param name="vertexAction">An action that adds vertices to a <see cref="VertexBatch{T}"/>.</param>
 /// <param name="inflationPercentage">The percentage amount that <paramref name="textureRect"/> should be inflated.</param>
 /// <param name="blendRangeOverride">The range over which the edges of the <paramref name="textureRect"/> should be blended.</param>
 /// <param name="textureCoords">The texture coordinates of the quad's vertices.</param>
 internal abstract void DrawQuad(Quad vertexQuad, ColourInfo drawColour, RectangleF?textureRect = null, Action <TexturedVertex2D> vertexAction = null, Vector2?inflationPercentage = null,
                                 Vector2?blendRangeOverride = null, RectangleF?textureCoords = null);
Example #49
0
 private void SortQuadData(int index, Quad quad)
 {
     SortVerticies(quad);
     SortTriangles(index, quad);
 }