Example #1
1
        public void Init(ContentManager content, Vector2 position, string normalTextureName, string hoverTextureName)
        {
            m_Normal = content.Load<Texture2D>(normalTextureName);
            m_Hover = content.Load<Texture2D>(hoverTextureName);

            m_ButtonRec = new Rectangle((int)position.X, (int)position.Y, m_Normal.Width, m_Normal.Height);
        }
Example #2
1
        internal APNGFrame(GraphicsDevice graphicsDevice, Frame frame)
        {
            if (frame.fcTLChunk != null)
            {
                X = (int) frame.fcTLChunk.XOffset;
                Y = (int) frame.fcTLChunk.YOffset;
                Width = (int) frame.fcTLChunk.Width;
                Height = (int) frame.fcTLChunk.Height;
                BlendOp = frame.fcTLChunk.BlendOp;
                DisposeOp = frame.fcTLChunk.DisposeOp;
                DelayTime = new TimeSpan(
                    TimeSpan.TicksPerSecond*frame.fcTLChunk.DelayNum/frame.fcTLChunk.DelayDen);
            }
            else
            {
                X = 0;
                Y = 0;
                Width = frame.IHDRChunk.Width;
                Height = frame.IHDRChunk.Height;
                BlendOp = BlendOps.APNGBlendOpSource;
                DisposeOp = DisposeOps.APNGDisposeOpNone;
                DelayTime = TimeSpan.Zero;
            }

            // frame.GetStream() is not seekable, so we build a new MemoryStream.
            FrameTexture = Texture2D.FromStream(
                graphicsDevice, new MemoryStream(frame.GetStream().ToArray()));
            MultiplyAlpha(FrameTexture);
        }
Example #3
1
        public MapTile(Texture2D texture, int type, int x, int y, int size)
        {
            this.TileTexture = texture;

            // Changes which column of the sprite sheet the game uses to draw
            int blockX = size * SpriteSheetXOffset;
            this.TileColour = Color.White;
            switch (type)
            {
                case 0: break;
                case 1: this.RectSlice = new Rectangle(blockX, size * 1, size, size); this.IsSolid = true; break;
                case 2: this.RectSlice = new Rectangle(blockX, size * 2, size, size); this.IsSolid = true; this.IsSpring = true; break;
                case 3: this.RectSlice = new Rectangle(blockX, size * 3, size, size); this.IsSolid = true; break;
                case 4: this.RectSlice = new Rectangle(blockX, size * 4, size, size); this.IsSolid = true; break;
                case 5: this.RectSlice = new Rectangle(blockX, size * 5, size, size); this.IsSolid = true; break;
                case 6: this.RectSlice = new Rectangle(blockX, size * 6, size, size); this.IsSolid = true; break;
                case 7:
                    this.RectSlice = new Rectangle(blockX, size * 7, size, size); this.IsSolid = false;
                    this.TileColour = new Color(255, 255, 255, 20);
                    this.IsWater = true;
                    break;
                default: this.RectSlice = new Rectangle(blockX, size * 0, size, size); this.IsSolid = true; break;
            }
            this.Width = size;
            this.Height = size;
            this.PositionRect = new Rectangle(x, y, this.Width, this.Height);
        }
Example #4
1
 /// <summary>
 /// Initializes a new instance of the <see cref="Button"/> class.
 /// </summary>
 /// <param name="texture">The texture.</param>
 /// <param name="color">The color.</param>
 /// <param name="spriteFont">The sprite font.</param>
 /// <param name="text">The text.</param>
 /// <param name="textColor">Color of the text.</param>
 public Button(Texture2D texture, Color color, SpriteFont spriteFont, String text, Color textColor)
     : base(texture, color, new Vector2(0, 0), new Vector2(1, 1), 0f)
 {
     _textLabel = new Label(spriteFont, text, textColor, new Vector2(0, 0), new Vector2(1, 1), 0);
     _state = BState.Up;
     _timer = 2f;
 }
Example #5
1
        public Texture2D GetTexture(string name)
        {
            if (!_initialized)
                Initialize();

            if (_textures.ContainsKey(name))
                return _textures[name];
            else
            {
                Rectangle r = RectangleFromName(name);

                if (r.Width > 1)
                {
                    Color[] colors = new Color[_width * _height];

                    _texture.GetData<Color>(0, r, colors, 0, _width * _height);

                    Texture2D tex = new Texture2D(MainApplication.Instance.GraphicsDevice, _width, _height);

                    tex.SetData<Color>(0, new Rectangle(0, 0, _width, _height), colors, 0, _width * _height);

                    _textures.Add(name, tex);

                    return tex;
                }

                return null;
            }
        }
Example #6
1
        /// <summary>
        /// Player constructor.
        /// </summary>
        /// <param name="color"></param>
        public Player(Alliance alliance, Color color, Point startLocation)
        {
            Game1.GetInstance().players.AddLast(this);
            this.device = Game1.GetInstance().GraphicsDevice;
            this.alliance = alliance;
            this.startLocation = startLocation;
            if (!this.alliance.members.Contains(this)) this.alliance.members.AddLast(this);
            this.color = color;

            selectionTex = Game1.GetInstance().Content.Load<Texture2D>("Selection");
            selectedTex = Game1.GetInstance().Content.Load<Texture2D>("Selected");

            units = new CustomArrayList<Unit>();
            buildings = new CustomArrayList<Building>();
            hud = new HUD(this, color);
            resources = 100000;

            meleeStore = new MeleeStore(this);
            rangedStore = new RangedStore(this);
            fastStore = new FastStore(this);

            arrowManager = new ArrowManager();

            lightTexture = Game1.GetInstance().Content.Load<Texture2D>("Fog/Light");

            MouseManager.GetInstance().mouseClickedListeners += ((MouseClickListener)this).OnMouseClick;
            MouseManager.GetInstance().mouseReleasedListeners += ((MouseClickListener)this).OnMouseRelease;
            MouseManager.GetInstance().mouseMotionListeners += ((MouseMotionListener)this).OnMouseMotion;
            MouseManager.GetInstance().mouseDragListeners += ((MouseMotionListener)this).OnMouseDrag;
        }
Example #7
1
 public MyTexture2D(Texture2D tex, int nbFrames, double[] timings = null)
 {
     _timings = timings;
     Texture = tex;
     _nbFrames = nbFrames;
     Reset ();
 }
Example #8
1
 public Octopus(Texture2D textura, Vector2 posicion)
 {
     Textura = textura;
     Posicion = posicion;
     Inicializa_Cuadros();
     iniAreas();
 }
        internal void DrawSpriteGlyph(Texture2D texture, Vector4 dest, Vector4 source, Color color)
        {
            if (!m_DrawString_InProgress)
                Logging.Fatal("BeginDrawString() must be called before DrawSpriteGlyph()");

            Vector4 uv = new Vector4(
                (float)source.X / texture.Width,
                (float)source.Y / texture.Height,
                (float)(source.X + source.Z) / texture.Width,
                (float)(source.Y + source.W) / texture.Height);

            VertexPositionTextureHueExtra[] v = new VertexPositionTextureHueExtra[4]
            {
                new VertexPositionTextureHueExtra(new Vector3(dest.X, dest.Y, m_DrawString_Depth), new Vector2(uv.X, uv.Y), color, Vector4.Zero), // top left
                new VertexPositionTextureHueExtra(new Vector3(dest.X + dest.Z, dest.Y, m_DrawString_Depth), new Vector2(uv.Z, uv.Y), color, Vector4.Zero), // top right
                new VertexPositionTextureHueExtra(new Vector3(dest.X, dest.Y + dest.W, m_DrawString_Depth), new Vector2(uv.X, uv.W), color, Vector4.Zero), // bottom left
                new VertexPositionTextureHueExtra(new Vector3(dest.X + dest.Z, dest.Y + dest.W, m_DrawString_Depth), new Vector2(uv.Z, uv.W), color, Vector4.Zero) // bottom right
            };

            /*if (shadow != null)
            {
                Color shadow2 = new Color(
                    shadow.Value.R, shadow.Value.G,
                    shadow.Value.B, 128);
                for (int i = 0; i < 4; i++)
                {
                    VertexPositionTextureHueExtra v0 = v[i];
                    v0.Hue = shadow.Value;
                    v0.Position.Y += 1f;
                    m_DrawString_VertexList.Add(v0);
                }
            }*/
            for (int i = 0; i < 4; i++)
                m_DrawString_VertexList.Add(v[i]);
        }
Example #10
1
 public static void RenderPolygone(SpriteBatch spriteBatch, Texture2D texture, Polygon polygon, int lineThickness, Color color)
 {
     for (int i = 0; i < polygon.Points.Count; ++i)
     {
         RenderLine(spriteBatch, texture, polygon.Points[i], polygon.Edges[i], 1, lineThickness, color);
     }
 }
Example #11
1
 /// <summary>
 /// Inicializa una nueva instancia de la clase AzulEngine.SpriteEngine.SpriteCatalog que recibe como
 /// parametros la textura, el ancho y alto del cuadro.
 /// </summary>
 /// <param name="texture">Textura que define el catálogo</param>
 /// <param name="width">Ancho de un cuadro</param>
 /// <param name="height">Alto de un cuadro</param>
 public SpriteCatalog(Texture2D texture, int width, int height)
 {
     this.texture = texture;
     this.framePositions = new Dictionary<int, Rectangle>();
     CalculateFrames(texture, width, height, ref this.framePositions);
     this.Size = new Point(width, height);
 }
Example #12
1
 public Emitter(Vector2 position, Texture2D sprite, Color color, int size)
 {
     this.position = position;
     this.sprite = sprite;
     this.color = color;
     this.size = size;
 }
Example #13
1
 public ObjectClass(Texture2D Img)
 {
     Image = Img;
     Position = Vector2.Zero;
     Center = Vector2.Zero;
     Rotation = 0.0f;
 }
Example #14
1
 public NPC(Texture2D texture, Dictionary<AnimationKey, Animation> animations, IEContentManager content)
     : base(texture, animations)
 {
     speakingRadius = 80f;
     dialog = new DialogComponent(content);
     dialog.Hide();
 }
Example #15
1
        public Inventory(int SCREEN_WIDTH, int SCREEN_HEIGHT, Pantheon gameReference)
        {
            locationBoxes = new List<Rectangle>();
            equippedBoxes = new List<Rectangle>();
            types = new List<int>();
            infoBox = new Rectangle();
            movingBox = new Rectangle();
            trashBox = new Rectangle();

            tempStorage = new Item();

            this.SCREEN_WIDTH = SCREEN_WIDTH;
            this.SCREEN_HEIGHT = SCREEN_HEIGHT;

            SetBoxes();

            selected = -1;
            hoveredOver = -1;

            color = new Color(34, 167, 222, 50);
            trashColor = Color.White;

            inventorySelector = gameReference.Content.Load<Texture2D>("Inventory/InvSelect");
            trashCan = gameReference.Content.Load<Texture2D>("Inventory/TrashCan");
            nullImage = new Texture2D(gameReference.GraphicsDevice, 1,1);
            nullImage.SetData(new[] { new Color(0,0,0,0) });
        }
Example #16
1
 public Toolbar(Texture2D texture, SpriteFont font, Vector2 position)
 {
     _texture = texture;
     _font = font;
     _position = position;
     _textPosition=new Vector2(130,_position.Y+10);
 }
Example #17
1
        public static void Draw(VertexPositionColor[] Points, Texture2D Texture)
        {
            //PUT IN DRAW CODE FOR PARTICLES HERE
            mGraphics.Peek.Device().RenderState.PointSpriteEnable = true;
            mGraphics.Peek.ToggleAlphaBlending(true);
            mGraphics.Peek.Device().RenderState.DepthBufferWriteEnable = false;
            mGraphics.Peek.Device().VertexDeclaration = mGraphics.Peek.vdPositionColor;
            mEffect.Peek.PointEffect().Parameters["WVPMatrix"].SetValue(Matrix.Identity * mCamera.Peek.ReturnCamera().View * mCamera.Peek.ReturnCamera().Projection);
            mEffect.Peek.PointEffect().Parameters["SpriteTexture"].SetValue(Texture);
            mEffect.Peek.PointEffect().Parameters["ViewportHeight"].SetValue(mGraphics.Peek.Device().Viewport.Height);
            mEffect.Peek.PointEffect().Parameters["ViewportHeight"].SetValue(25.0f);

            mEffect.Peek.PointEffect().Begin();
            for (int i = 0; i < mEffect.Peek.PointEffect().CurrentTechnique.Passes.Count; i++)
            {
                mEffect.Peek.PointEffect().CurrentTechnique.Passes[i].Begin();
                mGraphics.Peek.Device().DrawUserPrimitives<VertexPositionColor>(PrimitiveType.PointList, Points, 0, Points.Length);
                mEffect.Peek.PointEffect().CurrentTechnique.Passes[i].End();
            }
            mEffect.Peek.PointEffect().End();

            mGraphics.Peek.Device().RenderState.PointSpriteEnable = false;
            mGraphics.Peek.Device().RenderState.DepthBufferWriteEnable = true;
            mGraphics.Peek.ToggleAlphaBlending(false);
        }
Example #18
1
 public override void Initialize(Texture2D initTexture, Vector2 initPosition)
 {
     base.Initialize(initTexture, initPosition);
     acceleration = 2;
     velocity = 0;
     onTopOfBlock = false;
 }
Example #19
1
        /// <summary>
        /// Loads graphics content for this screen. The background texture is quite
        /// big, so we use our own local ContentManager to load it. This allows us
        /// to unload before going from the menus into the game itself, wheras if we
        /// used the shared ContentManager provided by the Game class, the content
        /// would remain loaded forever.
        /// </summary>
        public override void LoadContent()
        {
            if (content == null)
                content = new ContentManager(ScreenManager.Game.Services, "Content");

            backgroundTexture = content.Load<Texture2D>("background");
        }
Example #20
1
        public void LoadContent(ContentManager content, GraphicsDeviceManager graphicsDeviceManager)
        {
            texture = content.Load<Texture2D>("brick_texture_map");

            wall = new VertexPositionTexture[22];
            wall[0] = new VertexPositionTexture(new Vector3(200, 0, 200), new Vector2(0, 0));
            wall[1] = new VertexPositionTexture(new Vector3(200, 200, 200), new Vector2(2, 0));
            wall[2] = new VertexPositionTexture(new Vector3(0, 0, 200), new Vector2(0, 2));
            wall[3] = new VertexPositionTexture(new Vector3(0, 200, 200), new Vector2(2, 2));
            wall[4] = new VertexPositionTexture(new Vector3(0, 0, 220), new Vector2(0, 0));
            wall[5] = new VertexPositionTexture(new Vector3(0, 200, 220), new Vector2(2, 0));
            wall[6] = new VertexPositionTexture(new Vector3(200, 0, 220), new Vector2(0, 2));
            wall[7] = new VertexPositionTexture(new Vector3(200, 200, 220), new Vector2(2, 2));
            wall[8] = new VertexPositionTexture(new Vector3(200, 0, 200), new Vector2(0, 0));
            wall[9] = new VertexPositionTexture(new Vector3(200, 200, 220), new Vector2(2, 0));
            wall[10] = new VertexPositionTexture(new Vector3(200, 200, 200), new Vector2(2, 2));
            wall[11] = new VertexPositionTexture(new Vector3(0, 200, 220), new Vector2(0, 2));
            wall[12] = new VertexPositionTexture(new Vector3(0, 200, 200), new Vector2(0, 0));

            // Set vertex data in VertexBuffer
            vertexBuffer = new VertexBuffer(graphicsDeviceManager.GraphicsDevice, typeof(VertexPositionTexture), wall.Length, BufferUsage.None);
            vertexBuffer.SetData(wall);

            // Initialize the BasicEffect
            effect = new BasicEffect(graphicsDeviceManager.GraphicsDevice);
        }
 public Animation(Texture2D texture, float frameTime, bool isLooping, int FrameCount)
 {
     this.texture = texture;
     this.frameTime = frameTime;
     this.isLooping = isLooping;
     this.FrameCount = FrameCount;
 }
 public WaterSubMesh(Mesh mesh, RenderTarget2D reflectionBuffer, RenderTarget2D refractionBuffer, Texture2D offsetMap, Texture2D normalMap) : base(mesh)
 {
     m_ReflectionTarget = reflectionBuffer;
     m_RefractionTarget = refractionBuffer;
     m_OffsetMap = offsetMap;
     m_NormalMap = normalMap;
 }
Example #23
1
        public static void Load(ContentManager content)
        {
            Player = content.Load<Texture2D>("Player");

            Pixel = new Texture2D(Player.GraphicsDevice, 1, 1);
            Pixel.SetData(new[] { Color.White });
        }
Example #24
1
 public void debugDraw(SpriteBatch spritebatch, Texture2D texture)
 {
     foreach (Node nod in nodes){
         Vector2 adjustedPos = new Vector2(nod.Position.X - texture.Width/2, nod.Position.Y - texture.Height/2);
         spritebatch.Draw (texture, adjustedPos, Color.White);
     }
 }
Example #25
0
 public SpriteSheet(Texture2D texture, int currentFrame, int spriteWidth, int spriteHeight)
 {
     m_texture = texture;
     m_spriteWidth = spriteWidth;
     m_spriteHeight = spriteHeight;
     m_currentFrame = currentFrame;
 }
Example #26
0
 public BaseSelector(Grid inGrid, Texture2D inTexture, Rectangle inRect, int inRow, int inCol)
     : base(inTexture, inRect)
 {
     grid = inGrid;
     originRow = inRow;
     originCol = inCol;
 }
        public override bool InitOne(ContentManager content, int id)
        {
            XmlDocument _doc = new XmlDocument();
            _doc.Load(_xmlInfo);
            XmlNode _gameTitle = _doc.SelectSingleNode(@"//GameTitle[@id = '" + id.ToString() + "']");

            _prototype[id] = new GameTitle();
            XmlNodeList _listOfTitle = _gameTitle.SelectNodes(@"//Title");
            _prototype[id]._nsprite = _listOfTitle.Count;
            _prototype[id]._sprite = new GameSprite[_prototype[id]._nsprite];

            for (int i = 0; i < _prototype[id]._nsprite; i++)
            {
                int _numofframe = int.Parse(_listOfTitle[i].SelectSingleNode(@"NumOfFrames").InnerText);
                string _contentname = _listOfTitle[i].SelectSingleNode(@"ContentName").InnerText;

                Texture2D[] _textures = new Texture2D[_numofframe];

                for (int j = 0; j < _numofframe; ++j)
                {
                    _textures[j] = content.Load<Texture2D>(_contentname + j.ToString("00"));
                }
                _prototype[id]._sprite[i] = new GameSprite(_textures, 0, 0);
            }

            _prototype[id].X = float.Parse(_gameTitle.SelectSingleNode(@"X").InnerText);
            _prototype[id].Y = float.Parse(_gameTitle.SelectSingleNode(@"Y").InnerText);
            ((GameTitle)_prototype[id]).DelayTime = int.Parse((_gameTitle.SelectSingleNode(@"DelayTime").InnerText));
            return true;
        }
Example #28
0
        //position denotes location IN SIM SPACE
        public BallExplosion(World world, float intensity, Vector2 position)
        {
            particleList = new List<Body>();
            destructorWorld = world;
            particleImage = Game1.ballImage;

            for (int i = 0; i < numParticles; i++)
            {
                //Convert to Radians for Math's sake:
                angularSpacing = 2 * Math.PI / numParticles;

                //initialize the particle
                Body particle = BodyFactory.CreateCircle(world, UnitConverter.toSimSpace(radius), 50f, position);
                particle.BodyType = BodyType.Dynamic;
                particle.FixedRotation = true;
                particle.IsBullet = true;
                particle.LinearDamping = 0f;
                particle.GravityScale = .0f;
                particle.Friction = 0;
                particle.Restitution = 1.2f;
                particle.CollisionGroup = -1;

                //compute the impulse and send the particle on its merry way
                xVel = UnitConverter.toSimSpace((int)(10 * intensity * Math.Cos(i * angularSpacing)));
                yVel = UnitConverter.toSimSpace((int)(10 * intensity * Math.Sin(i * angularSpacing)));
                particle.LinearVelocity = new Vector2((float)xVel, (float)yVel);

                //Add each particle to a List for summary destruction after explosion
                particleList.Add(particle);
            }
        }
Example #29
0
 public Tilemap(Node parent, string name, Texture2D tileTexture, Point size, Point tileSize)
     : base(parent, name)
 {
     Body = new Body(this, "Body");
     Render = new TilemapRender(this, "TilemapRender", tileTexture, size, tileSize);
     Render.LinkDependency(TilemapRender.DEPENDENCY_BODY, Body);
 }
Example #30
0
        private void RenderLoop()
        {
            PrepareDXDevice();
            pixel       = CreatePixel();
            DeviceReady = true;

            while (!Program.AbortThreads)
            {
                if (DeviceReady && CurrentHostWindowState != System.Windows.WindowState.Minimized)
                {
                    RenderFrame();
#if FPS_TEST
                    fpsCounter.Tick();
#endif
                }
                else
                {
                    Thread.Sleep(100);
                }
            }
        }
Example #31
0
        private void RenderLoop()
        {
            PrepareDevice();
            pixel       = CreatePixel();
            deviceReady = true;

            while (!Program.AbortThreads)
            {
                if (deviceReady && form.WindowState != FormWindowState.Minimized)
                {
                    RenderFrame();
#if FPS_TEST
                    fpsCounter.Tick();
#endif
                }
                else
                {
                    Thread.Sleep(100);
                }
            }
        }
        public override void Draw(Microsoft.Xna.Framework.Graphics.Texture2D ImageToProcess, RenderHelper rHelper, Microsoft.Xna.Framework.GameTime gt, PloobsEngine.Engine.GraphicInfo GraphicInfo, IWorld world, bool useFloatBuffer)
        {
            Matrix v = world.CameraManager.ActiveCamera.View;
            Matrix p = world.CameraManager.ActiveCamera.Projection;

            if (firstTime)
            {
                oldViewProjection = world.CameraManager.ActiveCamera.ViewProjection;
                firstTime         = false;
            }
            rHelper.PushRenderTarget(rt);
            rHelper.Clear(Color.Black);
            rHelper.RenderSceneWithCustomMaterial(effectvelocity,
                                                  (effect, obj, bi, ti, s, er, wvp) =>
            {
                Matrix w1 = Matrix.Multiply(obj.WorldMatrix, bi.ModelLocalTransformation);
                effect.Parameters["wvp"].SetValue(w1 * wvp);
                effect.Parameters["oldwvp"].SetValue(w1 * oldViewProjection);
            }, world, gt, null, ref v, ref p, false, true);

            Texture2D tex = rHelper.PopRenderTargetAsSingleRenderTarget2D();

            eff.Parameters["halfPixel"].SetValue(GraphicInfo.HalfPixel);
            eff.Parameters["numSamples"].SetValue(NumSamples);
            eff.Parameters["velocity"].SetValue(tex);
            eff.Parameters["cena"].SetValue(ImageToProcess);
            eff.Parameters["Attenuation"].SetValue(Attenuation);


            oldViewProjection = world.CameraManager.ActiveCamera.ViewProjection;

            if (useFloatBuffer)
            {
                rHelper.RenderFullScreenQuadVertexPixel(eff, SamplerState.PointClamp);
            }
            else
            {
                rHelper.RenderFullScreenQuadVertexPixel(eff, GraphicInfo.SamplerState);
            }
        }
Example #33
0
        public static Texture2D CreateMosaic(GraphicsDevice device, Color c0, Color c1, int blockSize)
        {
            var t2d = new Texture2D(device, blockSize * 2, blockSize * 2, false, SurfaceFormat.Color);

            Color[] colorData = new Color[blockSize * blockSize * 4];
            int     offset    = blockSize * blockSize * 2;

            for (int i = 0; i < blockSize; i++)
            {
                colorData[i]                      = c0;
                colorData[blockSize + i]          = c1;
                colorData[offset + i]             = c1;
                colorData[offset + blockSize + i] = c0;
            }
            for (int i = 1; i < blockSize; i++)
            {
                Array.Copy(colorData, 0, colorData, blockSize * 2 * i, blockSize * 2);
                Array.Copy(colorData, offset, colorData, offset + blockSize * 2 * i, blockSize * 2);
            }
            t2d.SetData(colorData);
            return(t2d);
        }
        public void LoadTexture()
        {
            TextureCreationParameters parameters = new TextureCreationParameters(
                0, 0, 0, 0, SurfaceFormat.Unknown, TextureUsage.None, Color.White, FilterOptions.Triangle, FilterOptions.Linear);

            //TextureCreationParameters parameters = new TextureCreationParameters(
            //    0, 0, 0, 1, SurfaceFormat.Unknown, TextureUsage.None, Color.White, FilterOptions.Triangle, FilterOptions.Linear );

            try
            {
                if (Filename.StartsWith("file:///"))
                {
                    string path;
                    path    = Filename.Substring(("file:///").Length);
                    path    = path.Replace("%20", " ");
                    path    = path.Replace("%28", "(");
                    path    = path.Replace("%29", ")");
                    Texture = Texture2D.FromFile(game.GraphicsDevice, path, parameters);
                }
                else
                {
                    string path;
                    path    = Filename;
                    path    = path.Replace("%20", " ");
                    Texture = Texture2D.FromFile(game.GraphicsDevice, game.EngineFiles.RootDirectory + "\\Content\\" + path, parameters);
                }
            }
            catch
            {
            }
            finally
            {
            }

            //Texture.Save( "c:/temp.dds", ImageFileFormat.Dds );
            //Texture.GenerateMipMaps( TextureFilter.Linear );
        }
Example #35
0
        public static void draw_sprite(Texture2D sprite, double subimg, Vector2 position, float xscale = 1, float yscale = 1, float angle = 0, float originX = 0, float originY = 0)
        {
            if (subimg != -2)
            {
                int y = ((int)subimg / currentObject.Sprite.TextureCellsPerRow);
                int x = ((int)subimg % currentObject.Sprite.TextureCellsPerRow);

                Rectangle ImageRectangle = new Rectangle(x * currentObject.Sprite.cellW, y * (int)currentObject.Sprite.cellH, (int)currentObject.Sprite.cellW, (int)currentObject.Sprite.cellH);


                if (!batchRunning)
                {
                    sb.Begin(transformMatrix: m, effect: effect);
                    sb.Draw(sprite, position, ImageRectangle, FinalizeColor(DrawColor), currentObject.Sprite.ImageAngle, new Vector2(0, 0), currentObject.Sprite.ImageScale, SpriteEffects.None, 1);
                    sb.End();
                }
                else
                {
                    effect?.Parameters["FirstTexture"].SetValue(sprite);
                    sb.Draw(sprite, position, ImageRectangle, FinalizeColor(DrawColor), currentObject.Sprite.ImageAngle, new Vector2(0, 0), currentObject.Sprite.ImageScale, SpriteEffects.None, 1);
                }
            }
            else
            {
                if (aaOn)
                {
                    sb.Begin(transformMatrix: m, blendState: blendState);
                }
                else
                {
                    sb.Begin(transformMatrix: m, samplerState: SamplerState.PointClamp);
                }

                sb.Draw(sprite, position, null, FinalizeColor(DrawColor), MathHelper.ToRadians(angle), new Vector2(originX, originY), new Vector2(xscale, yscale), SpriteEffects.None, 1);
                sb.End();
            }
        }
Example #36
0
        private static void _Copy32(SpanBitmap src, XNA.Texture2D dst, bool fit)
        {
            if (dst == null)
            {
                throw new ArgumentNullException(nameof(dst));
            }
            var fmt = dst.Format == XNA.SurfaceFormat.Bgr32
                ? Pixel.BGRA32.Format
                : ToInteropFormat(dst.Format);

            if (fmt.ByteCount != 4)
            {
                throw new ArgumentException("invalid pixel size", nameof(dst));
            }

            var l = dst.Width * dst.Height;

            if (_32BitBuffer == null || _32BitBuffer.Length < l)
            {
                Array.Resize(ref _32BitBuffer, l);
            }

            var dstx = new SpanBitmap <UInt32>(_32BitBuffer, dst.Width, dst.Height, fmt);

            fit &= !(src.Width == dst.Width && src.Height == dst.Height);
            if (fit)
            {
                dstx.AsTypeless().FitPixels(src);
            }
            else
            {
                dstx.AsTypeless().SetPixels(0, 0, src);
            }

            dst.SetData(_32BitBuffer);
        }
Example #37
0
        public override void Draw(Microsoft.Xna.Framework.Graphics.Texture2D ImageToProcess, RenderHelper rHelper, Microsoft.Xna.Framework.GameTime gt, PloobsEngine.Engine.GraphicInfo GraphicInfo, IWorld world, bool useFloatBuffer)
        {
            rHelper.PushRenderTarget(RenderTarget2D);
            effect.Parameters["blurDepthFalloff"].SetValue(blurDepthFalloff);
            effect.Parameters["weights"].SetValue(kernel);
            effect.Parameters["offsets"].SetValue(offsetsHoriz);
            effect.Parameters["GBufferPixelSize"].SetValue(new Vector2(1f / ImageToProcess.Width, 1f / ImageToProcess.Height));
            effect.Parameters["TempBufferRes"].SetValue(destinySize.Value);
            rHelper.Textures[0] = rHelper[PrincipalConstants.DephRT];
            rHelper.Textures[1] = ImageToProcess;
            SamplerState s0 = rHelper.SetSamplerState(SamplerState.PointClamp, 0);
            SamplerState s1 = rHelper.SetSamplerState(ImageSamplerState, 1);

            rHelper.RenderFullScreenQuadVertexPixel(effect);

            rHelper.PopRenderTarget();

            effect.Parameters["offsets"].SetValue(offsetsVert);
            rHelper.Textures[1] = RenderTarget2D;
            rHelper.RenderFullScreenQuadVertexPixel(effect);

            rHelper.SetSamplerState(s0, 0);
            rHelper.SetSamplerState(s1, 1);
        }
Example #38
0
        protected virtual bool init(DisposableI parent, string fileName, Image image, int width, int height, bool generateMipmaps, MultiSampleTypes multiSampleType, SurfaceFormats surfaceFormat, RenderTargetUsage renderTargetUsage, BufferUsages usage, bool isRenderTarget, Loader.LoadedCallbackMethod loadedCallback)
        {
            try
            {
                if (usage == BufferUsages.Read && !isRenderTarget)
                {
                    Debug.ThrowError("Texture2D", "Only RenderTargets may be readable");
                }

                video = parent.FindParentOrSelfWithException <Video>();

                if (!isRenderTarget)
                {
                    if (fileName != null || image != null)
                    {
                                                #if SILVERLIGHT
                        texture = new X.Texture2D(video.Device, image.Size.Width, image.Size.Height, image.Mipmaps.Length != 0, Video.surfaceFormat(surfaceFormat));
                        for (int i = 0; i != image.Mipmaps.Length; ++i)
                        {
                            var mipmap = image.Mipmaps[i];
                            texture.SetData <byte>(i, null, mipmap.Data, 0, mipmap.Data.Length);
                        }
                                                #else
                        texture = parent.FindParentOrSelfWithException <RootDisposable>().Content.Load <X.Texture2D>(Streams.StripFileExt(fileName));
                        loadedFromContentManager = true;
                                                #endif
                    }
                    else
                    {
                        texture = new X.Texture2D(video.Device, width, height, generateMipmaps, Video.surfaceFormat(surfaceFormat));
                    }

                    Size          = new Size2(texture.Width, texture.Height);
                    PixelByteSize = Image.CalculatePixelByteSize(surfaceFormat, texture.Width, texture.Height);
                }
                else
                {
                    Size          = new Size2(width, height);
                    PixelByteSize = Image.CalculatePixelByteSize(surfaceFormat, width, height);
                }

                TexelOffset = (1 / Size.ToVector2()) * .5f;
                SizeF       = Size.ToVector2();
            }
            catch (Exception e)
            {
                FailedToLoad = true;
                Loader.AddLoadableException(e);
                Dispose();
                if (loadedCallback != null)
                {
                    loadedCallback(this, false);
                }
                return(false);
            }

            if (!isRenderTarget)
            {
                Loaded = true;
                if (loadedCallback != null)
                {
                    loadedCallback(this, true);
                }
            }
            return(true);
        }
Example #39
0
 public override void LoadResources(Microsoft.Xna.Framework.Content.ContentManager content)
 {
     m_Graphic = content.Load <Texture2D>(m_VisualName);
     m_Origin  = new Vector2(m_Graphic.Width / 2, m_Graphic.Height / 2);
 }
Example #40
0
 public Character(T2 tex, V2 pos, REC?rec, Color color,
                  F rot, V2 org, V2 scale, SE flip, F layer)
     : base(tex, pos, rec, color, rot, org, scale, flip, layer)
 {
 }
Example #41
0
        /// <summary>
        /// Loads the resources from any other XNA game like if they were form this one and extracts them.
        /// Tested with the XNA resources from the games "Terraria" and "Stardew Valley" with success.
        /// With applications like "ILSpy" you can see the source code from XNA games since they are .NET.
        /// The idea of this application is to find secrets hidden in the game textures and resources,
        /// but it should never be used to do anything illegal, so be sure you have the proper
        /// permissions before you start using it on random games. Jupisoft will never be responsible.
        /// </summary>
        protected override void LoadContent()
        {
            try
            {
                try { if (!Directory.Exists(Program.Ruta_XNA))
                      {
                          Directory.CreateDirectory(Program.Ruta_XNA);
                      }
                }
                catch (Exception Excepción) { Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); }

                List <string> Lista_Rutas     = new List <string>();
                List <string> Lista_Rutas_XSB = new List <string>();
                string[]      Matriz_Rutas    = Directory.GetFiles(Program.Ruta_XNA, "*.xnb", SearchOption.AllDirectories);
                if (Matriz_Rutas != null && Matriz_Rutas.Length > 0)
                {
                    Lista_Rutas.AddRange(Matriz_Rutas);
                    Matriz_Rutas = null;
                }
                Matriz_Rutas = Directory.GetFiles(Program.Ruta_XNA, "*.xwb", SearchOption.AllDirectories);
                if (Matriz_Rutas != null && Matriz_Rutas.Length > 0)
                {
                    Lista_Rutas.AddRange(Matriz_Rutas);
                    Matriz_Rutas = null;
                }
                Matriz_Rutas = Directory.GetFiles(Program.Ruta_XNA, "*.xgs", SearchOption.AllDirectories);
                if (Matriz_Rutas != null && Matriz_Rutas.Length > 0)
                {
                    Lista_Rutas.AddRange(Matriz_Rutas);
                    Matriz_Rutas = null;
                }
                Matriz_Rutas = Directory.GetFiles(Program.Ruta_XNA, "*.xsb", SearchOption.AllDirectories);
                if (Matriz_Rutas != null && Matriz_Rutas.Length > 0)
                {
                    //Lista_Rutas.AddRange(Matriz_Rutas);
                    Lista_Rutas_XSB.AddRange(Matriz_Rutas);
                    if (Lista_Rutas_XSB.Count > 1)
                    {
                        Lista_Rutas.Sort();
                    }
                    Matriz_Rutas = null;
                }
                if (Lista_Rutas.Count > 1)
                {
                    Lista_Rutas.Sort();
                }
                Matriz_Rutas = Lista_Rutas.ToArray();
                Lista_Rutas  = null;

                if (Matriz_Rutas != null && Matriz_Rutas.Length > 0) // There are files to extract.
                {
                    foreach (string Ruta in Matriz_Rutas)
                    {
                        try
                        {
                            if (!string.IsNullOrEmpty(Ruta) && File.Exists(Ruta))
                            {
                                string Ruta_Relativa = '.' + Ruta.Substring(Program.Ruta_Aplicación.Length).Substring(0, (Ruta.Length - Program.Ruta_Aplicación.Length) - 4);
                                string Ruta_Salida   = Ruta.Substring(0, Ruta.Length - 4);

                                try // Try to read as a 2D texture and export as a PNG image.
                                {
                                    Microsoft.Xna.Framework.Graphics.Texture2D Textura = base.Content.Load <Texture2D>(Ruta_Relativa);
                                    if (Textura != null)
                                    {
                                        MemoryStream Lector_Memoria = new MemoryStream();
                                        int          Ancho          = 16; // Default on error.
                                        int          Alto           = 16;
                                        try { Ancho = Textura.Width; }
                                        catch { Ancho = 16; }
                                        try { Alto = Textura.Height; }
                                        catch { Alto = 16; }
                                        Textura.SaveAsPng(Lector_Memoria, Ancho, Textura.Height);
                                        byte[] Matriz_Bytes = Lector_Memoria.ToArray();
                                        Lector_Memoria.Close();
                                        Lector_Memoria.Dispose();
                                        Lector_Memoria = null;
                                        Lector_Memoria = new MemoryStream(Matriz_Bytes);
                                        Image Imagen_Original = null;
                                        try { Imagen_Original = Image.FromStream(Lector_Memoria, false, false); }
                                        catch { Imagen_Original = null; }
                                        Lector_Memoria.Close();
                                        Lector_Memoria.Dispose();
                                        Lector_Memoria = null;
                                        Matriz_Bytes   = null;
                                        if (Imagen_Original != null) // Reconvert the image to 24 or 32 bits with alpha.
                                        {
                                            //Ancho = Imagen_Original.Width; // Could the width or height change?
                                            //Alto = Imagen_Original.Height;
                                            Bitmap   Imagen = new Bitmap(Ancho, Alto, !Image.IsAlphaPixelFormat(Imagen_Original.PixelFormat) ? PixelFormat.Format24bppRgb : PixelFormat.Format32bppArgb);
                                            Graphics Pintar = Graphics.FromImage(Imagen);
                                            Pintar.CompositingMode    = CompositingMode.SourceCopy;
                                            Pintar.CompositingQuality = CompositingQuality.HighQuality;
                                            Pintar.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                                            Pintar.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                                            Pintar.SmoothingMode      = SmoothingMode.None;
                                            Pintar.TextRenderingHint  = TextRenderingHint.AntiAlias;
                                            Pintar.DrawImage(Imagen_Original, new System.Drawing.Rectangle(0, 0, Ancho, Alto), new System.Drawing.Rectangle(0, 0, Ancho, Alto), GraphicsUnit.Pixel);
                                            Pintar.Dispose();
                                            Pintar = null;
                                            while (File.Exists(Ruta_Salida + ".png"))
                                            {
                                                Ruta_Salida += '_';
                                            }
                                            Imagen.Save(Ruta_Salida + ".png", ImageFormat.Png);
                                            Ruta_Salida = null;
                                            Imagen.Dispose();
                                            Imagen = null;
                                            Imagen_Original.Dispose();
                                            Imagen_Original = null;
                                            Ruta_Relativa   = null;
                                            Program.Eliminar_Archivo_Carpeta(Ruta); // Delete the copied XNB resource.
                                            continue;                               // Go to the next XNB resource file.
                                        }
                                    }
                                }
                                catch (Exception Excepción)
                                {
                                    //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null);
                                }

                                try // Try to read as a string and string dictionary and export as Unicode text.
                                {
                                    Dictionary <string, string> Diccionario = base.Content.Load <Dictionary <string, string> >(Ruta_Relativa);
                                    if (Diccionario != null && Diccionario.Count > 0)
                                    {
                                        while (File.Exists(Ruta_Salida + ".txt"))
                                        {
                                            Ruta_Salida += '_';
                                        }
                                        FileStream Lector = new FileStream(Ruta_Salida + ".txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                                        Lector.SetLength(0L);
                                        Lector.Seek(0L, SeekOrigin.Begin);
                                        StreamWriter Lector_Texto = new StreamWriter(Lector, Encoding.Unicode);
                                        foreach (KeyValuePair <string, string> Entrada in Diccionario)
                                        {
                                            try
                                            {
                                                Lector_Texto.WriteLine(Entrada.Key);
                                                Lector_Texto.WriteLine(Entrada.Value);
                                                Lector_Texto.WriteLine();
                                                Lector_Texto.Flush();
                                            }
                                            catch (Exception Excepción)
                                            {
                                                Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null);
                                                continue;
                                            }
                                        }
                                        Lector_Texto.Close();
                                        Lector_Texto.Dispose();
                                        Lector_Texto = null;
                                        Lector.Close();
                                        Lector.Dispose();
                                        Lector      = null;
                                        Diccionario = null;
                                        Program.Eliminar_Archivo_Carpeta(Ruta); // Delete the copied XNB resource.
                                        continue;                               // Go to the next XNB resource file.
                                    }
                                }
                                catch (Exception Excepción)
                                {
                                    //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null);
                                }

                                try // Try to read as an int and text dictionary and export as Unicode text.
                                {
                                    Dictionary <int, string> Diccionario = base.Content.Load <Dictionary <int, string> >(Ruta_Relativa);
                                    if (Diccionario != null && Diccionario.Count > 0)
                                    {
                                        while (File.Exists(Ruta_Salida + ".txt"))
                                        {
                                            Ruta_Salida += '_';
                                        }
                                        FileStream Lector = new FileStream(Ruta_Salida + ".txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                                        Lector.SetLength(0L);
                                        Lector.Seek(0L, SeekOrigin.Begin);
                                        StreamWriter Lector_Texto = new StreamWriter(Lector, Encoding.Unicode);
                                        foreach (KeyValuePair <int, string> Entrada in Diccionario)
                                        {
                                            try
                                            {
                                                Lector_Texto.WriteLine(Entrada.Key.ToString());
                                                Lector_Texto.WriteLine(Entrada.Value);
                                                Lector_Texto.WriteLine();
                                                Lector_Texto.Flush();
                                            }
                                            catch (Exception Excepción)
                                            {
                                                Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null);
                                                continue;
                                            }
                                        }
                                        Lector_Texto.Close();
                                        Lector_Texto.Dispose();
                                        Lector_Texto = null;
                                        Lector.Close();
                                        Lector.Dispose();
                                        Lector      = null;
                                        Diccionario = null;
                                        Program.Eliminar_Archivo_Carpeta(Ruta); // Delete the copied XNB resource.
                                        continue;                               // Go to the next XNB resource file.
                                    }
                                }
                                catch (Exception Excepción)
                                {
                                    //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null);
                                }

                                try // Try to read as an int and int array dictionary and export as Unicode text.
                                {
                                    Dictionary <int, int[]> Diccionario = base.Content.Load <Dictionary <int, int[]> >(Ruta_Relativa);
                                    if (Diccionario != null && Diccionario.Count > 0)
                                    {
                                        while (File.Exists(Ruta_Salida + ".txt"))
                                        {
                                            Ruta_Salida += '_';
                                        }
                                        FileStream Lector = new FileStream(Ruta_Salida + ".txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                                        Lector.SetLength(0L);
                                        Lector.Seek(0L, SeekOrigin.Begin);
                                        StreamWriter Lector_Texto = new StreamWriter(Lector, Encoding.Unicode); // .Default?
                                        foreach (KeyValuePair <int, int[]> Entrada in Diccionario)
                                        {
                                            try
                                            {
                                                Lector_Texto.WriteLine(Entrada.Key.ToString());
                                                if (Entrada.Value != null && Entrada.Value.Length > 0)
                                                {
                                                    for (int Índice = 0; Índice < Entrada.Value.Length; Índice++)
                                                    {
                                                        try
                                                        {
                                                            Lector_Texto.Write(Entrada.Value[Índice].ToString() + (Índice + 1 < Entrada.Value.Length ? ", " : null));
                                                        }
                                                        catch (Exception Excepción)
                                                        {
                                                            Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null);
                                                            continue;
                                                        }
                                                    }
                                                    Lector_Texto.WriteLine();
                                                }
                                                else
                                                {
                                                    Lector_Texto.WriteLine();
                                                }
                                                Lector_Texto.WriteLine();
                                                Lector_Texto.Flush();
                                            }
                                            catch (Exception Excepción)
                                            {
                                                Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null);
                                                continue;
                                            }
                                        }
                                        Lector_Texto.Close();
                                        Lector_Texto.Dispose();
                                        Lector_Texto = null;
                                        Lector.Close();
                                        Lector.Dispose();
                                        Lector      = null;
                                        Diccionario = null;
                                        Program.Eliminar_Archivo_Carpeta(Ruta); // Delete the copied XNB resource.
                                        continue;                               // Go to the next XNB resource file.
                                    }
                                }
                                catch (Exception Excepción)
                                {
                                    //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null);
                                }

                                try // Try to read as a sprite font and export as a PNG image.
                                {
                                    Microsoft.Xna.Framework.Graphics.SpriteFont Fuente = base.Content.Load <SpriteFont>(Ruta_Relativa);
                                    if (Fuente != null)
                                    {
                                        Fuente = null;
                                        while (File.Exists(Ruta_Salida + ".png"))
                                        {
                                            Ruta_Salida += '_';
                                        }
                                        if (XNA_Extractor.Extract.XnbExtractor.Extract(Ruta, Ruta_Salida + ".png", false, false, false, true))
                                        {
                                            Program.Eliminar_Archivo_Carpeta(Ruta); // Delete the copied XNB resource.
                                            continue;                               // Go to the next XNB resource file.
                                        }
                                    }
                                }
                                catch (Exception Excepción)
                                {
                                    //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null);
                                }

                                try // Try to read as a sound effect and export as WAV audio file.
                                {
                                    Microsoft.Xna.Framework.Audio.SoundEffect Efecto_Sonido = base.Content.Load <Microsoft.Xna.Framework.Audio.SoundEffect>(Ruta_Relativa);
                                    if (Efecto_Sonido != null)
                                    {
                                        Efecto_Sonido.Dispose();
                                        Efecto_Sonido = null;
                                        while (File.Exists(Ruta_Salida + ".wav"))
                                        {
                                            Ruta_Salida += '_';
                                        }
                                        if (XNA_Extractor.Extract.XnbExtractor.Extract(Ruta, Ruta_Salida + ".wav", false, false, true, false))
                                        {
                                            //Program.Eliminar_Archivo_Carpeta(Ruta); // Delete the copied XNB resource.
                                            continue; // Go to the next XNB resource file.
                                        }
                                    }
                                }
                                catch (Exception Excepción)
                                {
                                    //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null);
                                }

                                /*try // Try to read as an effect and export as ?.
                                 * {
                                 *  Microsoft.Xna.Framework.Graphics.Effect Efecto = base.Content.Load<Effect>(Ruta_Relativa);
                                 *  if (Efecto != null)
                                 *  {
                                 *      Program.Eliminar_Archivo_Carpeta(Ruta); // Delete the copied XNB resource.
                                 *      continue; // Go to the next XNB resource file.
                                 *  }
                                 * }
                                 * catch (Exception Excepción)
                                 * {
                                 *  //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null);
                                 * }*/

                                try // Try to read as a multiple type and export as a PNG image.
                                {
                                    while (File.Exists(Ruta_Salida + ".png"))
                                    {
                                        Ruta_Salida += '_';
                                    }
                                    if (XNA_Extractor.Extract.XnbExtractor.Extract(Ruta, Ruta_Salida + ".png", false, true, true, true))
                                    {
                                        Program.Eliminar_Archivo_Carpeta(Ruta); // Delete the copied XNB resource.
                                        continue;                               // Go to the next XNB resource file.
                                    }
                                }
                                catch (Exception Excepción)
                                {
                                    //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null);
                                }

                                try // Try to read as a bank wave file and export as multiple WAV sound files.
                                {
                                    //while (File.Exists(Ruta_Salida + ".wav")) Ruta_Salida += '_';
                                    //MessageBox.Show(Path.GetDirectoryName(Ruta_Salida), Ruta_Salida);
                                    if (/*string.Compare(Path.GetExtension(Ruta), ".xwb", true) == 0 && */ XNA_Extractor.Extract.XactExtractor.Extract(Ruta, Path.GetDirectoryName(Ruta)))
                                    {
                                        Program.Eliminar_Archivo_Carpeta(Ruta); // Delete the copied XNB resource.
                                        continue;                               // Go to the next XNB resource file.
                                    }
                                }
                                catch (Exception Excepción)
                                {
                                    //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null);
                                }

                                // TODO: Add support for more resource types...
                            }
                        }
                        catch (Exception Excepción)
                        {
                            //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null);
                            continue;
                        }
                    }
                    Matriz_Rutas = null;
                }
                // This works perfectly, but the class from "XactExtractor.cs" seems to export too many files?
                if (Lista_Rutas_XSB != null && Lista_Rutas_XSB.Count > 0) // Post-process the track names if present.
                {
                    List <char> Lista_Caracteres_Inválidos = new List <char>(Path.GetInvalidFileNameChars());
                    foreach (string Ruta in Lista_Rutas_XSB)
                    {
                        try
                        {
                            FileStream Lector_Entrada = new FileStream(Ruta, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
                            if (Lector_Entrada.Length > 0L)                            // Not empty.
                            {
                                byte[] Matriz_Bytes = new byte[Lector_Entrada.Length]; // Read the whole file at once.
                                int    Longitud     = Lector_Entrada.Read(Matriz_Bytes, 0, Matriz_Bytes.Length);
                                Lector_Entrada.Close();
                                Lector_Entrada.Dispose();
                                Lector_Entrada = null;
                                if (Longitud < Matriz_Bytes.Length)
                                {
                                    Array.Resize(ref Matriz_Bytes, Longitud);
                                }
                                string Ruta_Actual  = Path.GetDirectoryName(Ruta);
                                int    Total_Pistas = 0;
                                for (int Índice = 1; Índice < int.MaxValue; Índice++)
                                {
                                    if (File.Exists(Ruta_Actual + "\\" + Índice.ToString() + " Unknown.wav"))
                                    {
                                        Total_Pistas++;
                                    }
                                    else
                                    {
                                        break;  // Stop when a track in order is missing.
                                    }
                                }
                                List <string> Lista_Nombres   = new List <string>();
                                int           Índice_Anterior = Matriz_Bytes.Length - 1; // This byte should be zero (string ender).
                                for (int Índice = Matriz_Bytes.Length - 2; Índice >= 0; Índice--)
                                {
                                    if (Matriz_Bytes[Índice] == 0)
                                    {
                                        if (Índice + 1 != Índice_Anterior) // Avoid multiple nulls.
                                        {
                                            string Nombre = null;
                                            for (int Índice_Caracter = Índice + 1; Índice_Caracter < Índice_Anterior; Índice_Caracter++)
                                            {
                                                char Caracter = (char)Matriz_Bytes[Índice_Caracter];
                                                if (!char.IsControl(Caracter) && Caracter != 'ÿ' && !Lista_Caracteres_Inválidos.Contains(Caracter))
                                                {
                                                    Nombre += Caracter;
                                                }
                                            }
                                            if (string.IsNullOrEmpty(Nombre))
                                            {
                                                Nombre = "Unknown";
                                            }
                                            Lista_Nombres.Add(Nombre);
                                            //if (Lista_Nombres.Count >= Total_Pistas) break;
                                        }
                                        Índice_Anterior = Índice;
                                    }
                                }
                                if (Lista_Nombres != null && Lista_Nombres.Count > 0)
                                {
                                    for (int Índice_Pista = Total_Pistas, Índice_Nombre = 0; Índice_Pista >= 1; Índice_Pista--, Índice_Nombre++)
                                    {
                                        try
                                        {
                                            File.Move(Ruta_Actual + "\\" + Índice_Pista.ToString() + " Unknown.wav", Ruta_Actual + "\\" + Índice_Pista.ToString() + " " + Lista_Nombres[Índice_Nombre] + ".wav");
                                        }
                                        catch (Exception Excepción)
                                        {
                                            //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null);
                                            continue;
                                        }
                                    }
                                    Lista_Nombres.Reverse();
                                    string Ruta_Salida = Ruta.Substring(0, Ruta.Length - 4);
                                    while (File.Exists(Ruta_Salida + ".txt"))
                                    {
                                        Ruta_Salida += '_';
                                    }
                                    FileStream Lector = new FileStream(Ruta_Salida + ".txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                                    Lector.SetLength(0L);
                                    Lector.Seek(0L, SeekOrigin.Begin);
                                    StreamWriter Lector_Texto = new StreamWriter(Lector, Encoding.Unicode);
                                    foreach (string Nombre in Lista_Nombres)
                                    {
                                        try
                                        {
                                            Lector_Texto.WriteLine(Nombre);
                                            Lector_Texto.Flush();
                                        }
                                        catch (Exception Excepción)
                                        {
                                            //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null);
                                            continue;
                                        }
                                    }
                                    Lector_Texto.Close();
                                    Lector_Texto.Dispose();
                                    Lector_Texto = null;
                                    Lector.Close();
                                    Lector.Dispose();
                                    Lector        = null;
                                    Lista_Nombres = null;
                                    Program.Eliminar_Archivo_Carpeta(Ruta); // Delete the copied XNB resource.
                                    continue;                               // Go to the next XNB resource file.
                                }
                            }
                        }
                        catch (Exception Excepción)
                        {
                            Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null);
                            continue;
                        }
                    }
                    Lista_Caracteres_Inválidos = null;
                }
                Depurador.Detener_Depurador();
                this.Exit();
            }
            catch (Exception Excepción) { Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); }
        }
Example #42
0
 public static bool TryCreateTexture(SpanBitmap src, XNA.GraphicsDevice device, out XNA.Texture2D tex)
 {
     try
     {
         tex = null;
         Copy(src, ref tex, false, device, null, null);
         return(true);
     }
     catch (ArgumentException) { tex = null; return(false); }
 }
Example #43
0
 public void LoadGraphicsContentGem(Microsoft.Xna.Framework.Graphics.SpriteBatch sprite, Microsoft.Xna.Framework.Graphics.Texture2D texture)
 {
     foreach (Image gem in gems)
     {
         gem.LoadGraphicsContent(sprite, texture);
     }
 }
Example #44
0
        internal static Microsoft.Xna.Framework.Graphics.Texture2D ToTexture2D(Color[] pixelData, int textureWidth, int textureHeight, bool generateMipmaps, GraphicsDevice graphicsDevice)
        {
#if FRB_XNA
            // Justin Johnson - May 18, 2012 - Added XNA support for mipmap creation on generated textures
            int     mipLevelWidth;
            int     mipLevelHeight;
            int     mipTotalPixels;
            int     mipYCoordinate;
            int     mipXCoordinate;
            int     sourceXCoordinate;
            int     sourceYCoordinate;
            int     sourcePixelIndex;
            Color[] mipLevelData;
#if XNA4
            Texture2D texture = new Texture2D(graphicsDevice, textureWidth, textureHeight, generateMipmaps, SurfaceFormat.Color);
#else
            // Victor Chelaru
            // May 22, 2011
            // Not sure what the
            // additional arguments
            // should be here, but the
            // code wasn't compiling with
            // the code as written for XNA4.
            // So I removed soem of the args to
            // make it compile - we probably don't
            // care as much for XNA 3.1 since 4.0 is
            // the newest.
            Texture2D texture = new Texture2D(graphicsDevice, textureWidth, textureHeight);
#endif
            // creates texture for each mipmap level (level count defined automatically)
            if (generateMipmaps)
            {
                for (int i = 0; i < texture.LevelCount; i++)
                {
                    if (i == 0)
                    {
                        mipLevelData = pixelData;
                    }
                    else
                    {
                        // Scale previous texture to 50% size
                        // Since mipmaps are usually blended, interpolation is not necessary: point sampling only for speed
                        mipLevelWidth = textureWidth / 2;
                        mipLevelWidth = System.Math.Max(mipLevelWidth, 1);

                        mipLevelHeight = textureHeight / 2;
                        mipLevelHeight = System.Math.Max(mipLevelHeight, 1);

                        mipTotalPixels = mipLevelWidth * mipLevelHeight;
                        mipLevelData   = new Color[mipTotalPixels];

                        for (int mipPixelIndex = 0; mipPixelIndex < mipTotalPixels; mipPixelIndex++)
                        {
                            mipYCoordinate              = (int)System.Math.Floor(mipPixelIndex / (double)mipLevelWidth);
                            mipXCoordinate              = mipPixelIndex - (mipYCoordinate * mipLevelWidth);
                            sourceYCoordinate           = mipYCoordinate * 2;
                            sourceXCoordinate           = mipXCoordinate * 2;
                            sourcePixelIndex            = System.Math.Min(sourceYCoordinate * textureWidth + sourceXCoordinate, pixelData.Length - 1);
                            mipLevelData[mipPixelIndex] = pixelData[sourcePixelIndex];
                        }

                        pixelData     = mipLevelData;
                        textureWidth  = mipLevelWidth;
                        textureHeight = mipLevelHeight;
                    }
#if (XNA4) || WINDOWS_8
                    texture.SetData <Color>(i, null, mipLevelData, 0, mipLevelData.Length);
#else
                    texture.SetData <Color>(i, null, mipLevelData, 0, mipLevelData.Length, SetDataOptions.Discard);
#endif
                }
            }
            else
            {
                texture.SetData <Color>(pixelData);
            }
#elif FRB_MDX
            // Justin Johnson - May 18, 2012 - I did not change this at all when I updated this method
            if (textureHeight > FlatRedBallServices.GraphicsDevice.DeviceCaps.MaxTextureHeight ||
                textureWidth > FlatRedBallServices.GraphicsDevice.DeviceCaps.MaxTextureWidth)
            {
                throw new InvalidOperationException("The resolution of the to-be-created Texture2D " +
                                                    "is too large.  The desired resolution is " + textureWidth + " by " + textureHeight + "." +
                                                    "The largest supported resolution is " +
                                                    FlatRedBallServices.GraphicsDevice.DeviceCaps.MaxTextureWidth + " by " +
                                                    FlatRedBallServices.GraphicsDevice.DeviceCaps.MaxTextureHeight + ".");
            }

            Microsoft.Xna.Framework.Graphics.Texture2D texture = new Microsoft.Xna.Framework.Graphics.Texture2D();
            texture.texture = new Microsoft.DirectX.Direct3D.Texture(
                FlatRedBallServices.GraphicsDevice,
                textureWidth,
                textureHeight,
                0,
                0,
                Microsoft.DirectX.Direct3D.Format.A8R8G8B8,
                Microsoft.DirectX.Direct3D.Pool.Managed);


            texture.Width  = textureWidth;
            texture.Height = textureHeight;


            uint[,] textureData = (uint[, ])texture.texture.LockRectangle(
                typeof(uint),
                0,
                Microsoft.DirectX.Direct3D.LockFlags.None,
                textureWidth, textureHeight);


            int pixelY = 0;
            for (int pixelX = 0; pixelX < textureWidth; pixelX++)
            {
                for (pixelY = 0; pixelY < textureHeight; pixelY++)
                {
                    // Vic says:  I used to have the mData line say:
                    // mData[pixelY * width + pixelX]... but that didn't
                    // work I inverted it and it works fine now.  Not sure
                    // why, but this works so oh well.
                    textureData[pixelX, pixelY] = (uint)
                                                  pixelData[pixelX * textureHeight + pixelY].ToArgb();
                }
            }

            texture.texture.UnlockRectangle(0);
#else
            // Justin Johnson - May 18, 2012 - not sure if any other devices support mipmapping and to what level. Fall back to no mipmaps
            Texture2D texture = new Texture2D(FlatRedBallServices.GraphicsDevice, textureWidth, textureHeight);
            texture.SetData <Color>(pixelData);
#endif
            return(texture);
        }
Example #45
0
 /// <summary>
 /// Builds and load a texture.
 /// </summary>
 public static bool TryLoadTexture2D(this ContentBuilder builder, ContentManager content, string file, out Microsoft.Xna.Framework.Graphics.Texture2D value)
 {
     return(TryLoad <Microsoft.Xna.Framework.Graphics.Texture2D>(builder, content, "TextureImporter", "TextureProcessor", file, out value));
 }
Example #46
0
 public static void GetTexture_BGRA4444 <T>(this Texture2D texture, T[] data) where T : struct
 {
     texture.GetTexture_BGRA4444 <T>(0, 0, null, data, 0, data.Length);
 }
Example #47
0
        public static void GetTexture_BGRA4444 <T>(this Texture2D texture, int level, int arraySlice, Rectangle?rect, T[] data, int startIndex, int elementCount) where T : struct
        {
            int num  = Math.Max(texture.Width >> level, 1);
            int num2 = Math.Max(texture.Height >> level, 1);
            Texture2DDescription description = new Texture2DDescription
            {
                Width          = num,
                Height         = num2,
                MipLevels      = 1,
                ArraySize      = 1,
                Format         = DXGI_FORMAT_B4G4R4A4_UNORM,
                BindFlags      = BindFlags.None,
                CpuAccessFlags = CpuAccessFlags.Read
            };

            description.SampleDescription.Count   = 1;
            description.SampleDescription.Quality = 0;
            description.Usage       = ResourceUsage.Staging;
            description.OptionFlags = ResourceOptionFlags.None;

            DeviceContext context = texture.GraphicsDevice._d3dContext();

            using (SharpDX.Direct3D11.Texture2D textured = new SharpDX.Direct3D11.Texture2D(texture.GraphicsDevice._d3dDevice(), description))
            {
                lock (context)
                {
                    int width;
                    int height;
                    SharpDX.DataStream stream;
                    int sourceSubresource = 0;
                    if (rect.HasValue)
                    {
                        width  = rect.Value.Width;
                        height = rect.Value.Height;
                        context.CopySubresourceRegion(texture.GetTexture(), sourceSubresource, new ResourceRegion(rect.Value.Left, rect.Value.Top, 0, rect.Value.Right, rect.Value.Bottom, 1), textured, 0, 0, 0, 0);
                    }
                    else
                    {
                        width  = num;
                        height = texture.Height;
                        context.CopySubresourceRegion(texture.GetTexture(), sourceSubresource, null, textured, 0, 0, 0, 0);
                    }
                    SharpDX.DataBox box  = context.MapSubresource(textured, 0, MapMode.Read, MapFlags.None, out stream);
                    int             num7 = 2 * width;
                    if (num7 == box.RowPitch)
                    {
                        stream.ReadRange <T>(data, startIndex, elementCount);
                    }
                    else
                    {
                        stream.Seek((long)startIndex, SeekOrigin.Begin);
                        int num8 = Marshal.SizeOf(typeof(T));
                        for (int i = 0; i < height; i++)
                        {
                            int index = (i * num7) / num8;
                            while (index < (((i + 1) * num7) / num8))
                            {
                                data[index] = stream.Read <T>();
                                index++;
                            }
                            if (index >= elementCount)
                            {
                                break;
                            }
                            stream.Seek((long)(box.RowPitch - num7), SeekOrigin.Current);
                        }
                    }
                    stream.Dispose();
                }
            }
        }
Example #48
0
        public void commit(sbyte[] palette, sbyte[] indices)
        {
            switch (this.m_format)
            {
            case 99:
                for (int level = 0; level < this.getNumMipMapLevels(); ++level)
                {
                    sbyte[] mipMapData   = this.getMipMapData(level);
                    int     mipMapWidth  = this.getMipMapWidth(level);
                    int     mipMapHeight = this.getMipMapHeight(level);
                    for (int index1 = 0; index1 < mipMapHeight; ++index1)
                    {
                        for (int index2 = 0; index2 < mipMapWidth; ++index2)
                        {
                            int num1 = 0;
                            int num2 = 0;
                            int num3 = 0;
                            for (int index3 = 0; index3 < 1 << level; ++index3)
                            {
                                for (int index4 = 0; index4 < 1 << level; ++index4)
                                {
                                    uint num4 = (uint)(((index1 << level) + index3) * this.m_width + (index2 << level) + index4);
                                    uint num5 = (uint)(((int)indices[(int)num4] & (int)byte.MaxValue) * 3);
                                    num1 += (int)palette[num5] & (int)byte.MaxValue;
                                    num2 += (int)palette[(num5 + 1U)] & (int)byte.MaxValue;
                                    num3 += (int)palette[(num5 + 2U)] & (int)byte.MaxValue;
                                }
                            }
                            int  num6 = num1 >> level * 2;
                            int  num7 = num2 >> level * 2;
                            int  num8 = num3 >> level * 2;
                            uint num9 = (uint)((index1 * mipMapWidth + index2) * 3);
                            mipMapData[num9]        = (sbyte)num6;
                            mipMapData[(num9 + 1U)] = (sbyte)num7;
                            mipMapData[(num9 + 2U)] = (sbyte)num8;
                            if (index2 == 0 && level == 0)
                            {
                                Color[] data = new Color[mipMapData.Length / 3];
                                for (int index3 = 0; index3 < data.Length; ++index3)
                                {
                                    data[index3] = new Color((int)mipMapData[index3 * 3], (int)mipMapData[index3 * 3 + 1], (int)mipMapData[index3 * 3 + 2]);
                                }
                                this.texture2d = new Microsoft.Xna.Framework.Graphics.Texture2D(JavaLib.GraphicsDevice, this.m_width, this.m_height, true, SurfaceFormat.Color);
                                this.texture2d.SetData <Color>(data);
                            }
                        }
                    }
                }
                break;

            case 100:
                for (int level = 0; level < this.getNumMipMapLevels(); ++level)
                {
                    sbyte[] mipMapData1  = this.getMipMapData(level);
                    int     mipMapWidth  = this.getMipMapWidth(level);
                    int     mipMapHeight = this.getMipMapHeight(level);
                    for (int index1 = 0; index1 < mipMapHeight; ++index1)
                    {
                        for (int index2 = 0; index2 < mipMapWidth; ++index2)
                        {
                            int num1 = 0;
                            int num2 = 0;
                            int num3 = 0;
                            int num4 = 0;
                            for (int index3 = 0; index3 < 1 << level; ++index3)
                            {
                                for (int index4 = 0; index4 < 1 << level; ++index4)
                                {
                                    uint num5 = (uint)(((index1 << level) + index3) * this.m_width + (index2 << level) + index4);
                                    uint num6 = (uint)(((int)indices[num5] & (int)byte.MaxValue) * 4);
                                    num1 += (int)palette[num6] & (int)byte.MaxValue;
                                    num2 += (int)palette[(num6 + 1U)] & (int)byte.MaxValue;
                                    num3 += (int)palette[(num6 + 2U)] & (int)byte.MaxValue;
                                    num4 += (int)palette[(num6 + 3U)] & (int)byte.MaxValue;
                                }
                            }
                            int  num7  = num1 >> level * 2;
                            int  num8  = num2 >> level * 2;
                            int  num9  = num3 >> level * 2;
                            int  num10 = num4 >> level * 2;
                            uint num11 = (uint)((index1 * mipMapWidth + index2) * 4);
                            mipMapData1[num11]        = (sbyte)num7;
                            mipMapData1[(num11 + 1U)] = (sbyte)num8;
                            mipMapData1[(num11 + 2U)] = (sbyte)num9;
                            mipMapData1[(num11 + 3U)] = (sbyte)num10;
                            if (index2 == 0 && level == 0)
                            {
                                sbyte[] mipMapData2 = this.getMipMapData(0);
                                Color[] data        = new Color[this.getMipMapData(0).Length / 4];
                                for (int index3 = 0; index3 < data.Length; ++index3)
                                {
                                    data[index3] = new Color((int)mipMapData2[index3 * 4], (int)mipMapData2[index3 * 4 + 1], (int)mipMapData2[index3 * 4 + 2], (int)mipMapData2[index3 * 4 + 3]);
                                }
                                this.texture2d = new Microsoft.Xna.Framework.Graphics.Texture2D(JavaLib.GraphicsDevice, this.m_width, this.m_height, false, SurfaceFormat.Color);
                                this.texture2d.SetData <Color>(data);
                            }
                        }
                    }
                }
                break;
            }
            this.m_mutable = false;
        }
        }         // Dispose()

        #endregion

        #region Load
        /// <summary>
        /// Load or reload texture.
        /// </summary>
        public virtual void Load()
        {
            string fullFilename =
                Path.Combine(Directories.ContentDirectory, texFilename);

            // Try to load texture
            try
            {
                // Try loading as 2d texture
                internalXnaTexture = BaseGame.Content.Load <Texture2D>(fullFilename);

                // Get info from the texture directly.
                texWidth  = internalXnaTexture.Width;
                texHeight = internalXnaTexture.Height;

                // We will use alpha for Dxt3, Dxt5 or any format starting with "A",
                // there are a lot of those (A8R8G8B8, A4R4G4B4, A8B8G8R8, etc.)
                hasAlpha =
                    internalXnaTexture.Format == SurfaceFormat.Dxt5 ||
                    internalXnaTexture.Format == SurfaceFormat.Dxt3 ||
                    internalXnaTexture.Format.ToString().StartsWith("A");

                loaded = true;

                CalcHalfPixelSize();
            }             // try
            catch (Exception ex)
            {
#if XBOX360
                // Failed to load
                loaded = false;
                // Create dummy empty texture (to prevent any errors in the game)
                internalXnaTexture = new Texture2D(BaseGame.Device,
                                                   16, 16, 0, TextureUsage.None, SurfaceFormat.Dxt1);
                Log.Write("Failed to load texture " + fullFilename +
                          ", will use empty texture! Error: " + ex.ToString());
#else
                // Try again with filename
                // Add default extension if none is given
                if (AddExtensionIfNoneGiven.Length > 0 &&
                    StringHelper.GetExtension(texFilename).Length == 0)
                {
                    texFilename = texFilename + "." + AddExtensionIfNoneGiven;
                }
                // Build full filename
                fullFilename =
                    Directories.ContentDirectory + "\\" + texFilename;

                // Check if file exists, else we can't continue loading!
                if (File.Exists(fullFilename))
                {
                    // Finally load texture
                    internalXnaTexture = Texture2D.FromFile(
                        BaseGame.Device, fullFilename);

                    // Get info from the texture directly.
                    texWidth  = internalXnaTexture.Width;
                    texHeight = internalXnaTexture.Height;

                    // We will use alpha for Dxt3, Dxt5 or any format starting with "A",
                    // there are a lot of those (A8R8G8B8, A4R4G4B4, A8B8G8R8, etc.)
                    hasAlpha =
                        internalXnaTexture.Format == SurfaceFormat.Dxt5 ||
                        internalXnaTexture.Format == SurfaceFormat.Dxt3 ||
                        internalXnaTexture.Format.ToString().StartsWith("A");

                    loaded = true;

                    CalcHalfPixelSize();
                }                 // if (File.Exists)
                else
                {
                    // Failed to load
                    loaded = false;
                    // Create dummy empty texture (to prevent any errors in the game)
                    internalXnaTexture = new Texture2D(BaseGame.Device,
                                                       16, 16, 0, TextureUsage.None, SurfaceFormat.Dxt1);
                    Log.Write("Failed to load texture " + fullFilename +
                              ", will use empty texture! Error: " + ex.ToString());
                } // else
#endif
            }     // catch (ex)
        }         // Load()
Example #50
0
        public override void Draw(Microsoft.Xna.Framework.Graphics.Texture2D ImageToProcess, RenderHelper rHelper, Microsoft.Xna.Framework.GameTime gt, PloobsEngine.Engine.GraphicInfo GraphicInfo, IWorld world, bool useFloatBuffer)
        {
            Texture2D Texture2D = DownSampler.DownShaderBilinearTexture(rHelper, ImageToProcess);

            rHelper.RenderTextureComplete(Texture2D, ImageToProcess.Bounds);
        }
Example #51
0
        public void LoadGraphicsContentLife(Microsoft.Xna.Framework.Graphics.SpriteBatch sprite, Microsoft.Xna.Framework.Graphics.Texture2D texture)
        {
            foreach (Image life in lifes)
            {
                life.LoadGraphicsContent(sprite, texture);
            }

            lifetext = lifes[0].Texture;
        }
Example #52
0
        protected void ListMenuItemsSelected(List <string> Items)
        {
            if (Items == null)
            {
                return;
            }

            for (int I = 0; I < Items.Count; I++)
            {
                switch (ItemSelectionChoice)
                {
                case ItemSelectionChoices.Map:
                    string MapLogicName = Items[0].Substring(0, Items[0].Length - 4).Substring(24);
                    BattleMapViewer.Preload();
                    DeathmatchMap NewMap = new DeathmatchMap(MapLogicName, string.Empty, new Dictionary <string, List <Core.Units.Squad> >());
                    Helper = new DeathmatchMapHelper(NewMap);
                    NewMap.ListGameScreen = new List <GameScreen>();
                    NewMap.Content        = BattleMapViewer.content;
                    NewMap.Load();
                    NewMap.TogglePreview(false);
                    NewMap.CursorPositionVisible = new Vector3(-1, -1, 0);

                    BattleMapViewer.SetListMapScript(NewMap.ListMapScript);
                    BattleMapViewer.Helper.OnSelect = (SelectedObject, RightClick) =>
                    {
                        if (RightClick && SelectedObject != null)
                        {
                            BattleMapViewer.cmsScriptMenu.Show(BattleMapViewer, PointToClient(Cursor.Position));
                        }
                    };

                    for (int S = NewMap.ListMapScript.Count - 1; S >= 0; --S)
                    {
                        BattleMapViewer.Helper.InitScript(NewMap.ListMapScript[S]);
                    }

                    for (int T = 0; T < TerrainAttribute.ListTerrainChangeLocation.Count; T++)
                    {
                        Vector3 NewDestinationPoint = TerrainAttribute.ListTerrainChangeLocation[T].Position;
                        NewMap.LayerManager[0].ListSingleplayerSpawns.Add(new EventPoint(NewDestinationPoint, T.ToString(), 255, 255, 255));
                    }

                    Matrix Projection      = Matrix.CreateOrthographicOffCenter(0, BattleMapViewer.Width, BattleMapViewer.Height, 0, 0, -1f);
                    Matrix HalfPixelOffset = Matrix.CreateTranslation(-0.5f, -0.5f, 0);

                    Matrix projectionMatrix = HalfPixelOffset * Projection;

                    NewMap.fxOutline.Parameters["Projection"].SetValue(projectionMatrix);

                    #region Tiles

                    for (int T = 0; T < TerrainAttribute.ListTileset.Count; ++T)
                    {
                        bool AlreadyExist = false;
                        for (int P = 0; P < NewMap.ListTilesetPreset.Count; ++P)
                        {
                            if (TerrainAttribute.ListTileset[T] == NewMap.ListTilesetPreset[P].TilesetName)
                            {
                                AlreadyExist = true;
                                break;
                            }
                        }

                        if (!AlreadyExist)
                        {
                            Texture2D sprTileset = NewMap.Content.Load <Texture2D>("Maps/Tilesets/" + TerrainAttribute.ListTileset[T]);
                            if (!NewMap.ListTileSet.Contains(sprTileset))
                            {
                                NewMap.ListTilesetPreset.Add(new Terrain.TilesetPreset(TerrainAttribute.ListTileset[T], sprTileset.Width, sprTileset.Height, NewMap.TileSize.X, NewMap.TileSize.Y, NewMap.ListTilesetPreset.Count));
                                NewMap.ListTileSet.Add(sprTileset);
                            }
                        }
                    }

                    for (int T = 0; T < NewMap.ListTilesetPreset.Count; T++)
                    {
                        if (!TerrainAttribute.ListTileset.Contains(NewMap.ListTilesetPreset[T].TilesetName))
                        {
                            TerrainAttribute.ListTileset.Add(NewMap.ListTilesetPreset[T].TilesetName);
                        }

                        ItemInfo Item = BaseEditor.GetItemByKey(BaseEditor.GUIRootPathMapTilesetImages, NewMap.ListTilesetPreset[T].TilesetName);

                        if (Item.Path != null)
                        {
                            if (Item.Name.StartsWith("Tileset presets"))
                            {
                                cboTiles.Items.Add(Item.Name);
                            }
                            else
                            {
                                cboTiles.Items.Add(Item.Name);
                            }
                        }
                        else
                        {
                            MessageBox.Show(NewMap.ListTilesetPreset[T].TilesetName + " not found, loading default tileset instead.");
                            cboTiles.Items.Add("Default");
                        }
                    }

                    #endregion

                    for (int T = 0; T < TerrainAttribute.ListTerrainChangeLocation.Count; T++)
                    {
                        Terrain      ActiveTerrain = TerrainAttribute.ListTerrainChangeLocation[T];
                        int          PosX          = (int)ActiveTerrain.Position.X;
                        int          PosY          = (int)ActiveTerrain.Position.Y;
                        DrawableTile ActiveTile    = TerrainAttribute.ListTileChangeLocation[T];
                        Helper.ReplaceTerrain(PosX, PosY, ActiveTerrain, 0);
                        Helper.ReplaceTile(PosX, PosY, ActiveTile, 0);
                    }

                    BattleMapViewer.ActiveMap = NewMap;

                    BattleMapViewer.RefreshScrollbars();

                    if (NewMap.ListTilesetPreset.Count > 0)
                    {
                        cboTiles.SelectedIndex = 0;
                    }

                    if (cboTiles.SelectedIndex >= 0)
                    {
                        TilesetViewer.InitTileset(NewMap.ListTileSet[cboTiles.SelectedIndex], NewMap.TileSize);
                    }
                    else
                    {
                        TilesetViewer.InitTileset(string.Empty, NewMap.TileSize);
                    }

                    TileAttributesEditor = Helper.GetTileEditor();

                    break;

                case ItemSelectionChoices.Tile:
                    string TilePath = Items[I];
                    if (TilePath != null)
                    {
                        if (TilePath.StartsWith("Content/Maps/Tileset Presets"))
                        {
                            string Name = TilePath.Substring(0, TilePath.Length - 4).Substring(29);
                            Terrain.TilesetPreset NewTileset = Terrain.TilesetPreset.FromFile(Name, BattleMapViewer.ActiveMap.ListTilesetPreset.Count);
                            string Output = BaseEditor.GetItemPathInRoot(BaseEditor.GUIRootPathMapTilesets, NewTileset.TilesetName);
                            BattleMapViewer.ActiveMap.ListTilesetPreset.Add(NewTileset);
                            BattleMapViewer.ActiveMap.ListTileSet.Add(TilesetViewer.content.Load <Microsoft.Xna.Framework.Graphics.Texture2D>("Maps/Tilesets/" + NewTileset.TilesetName));

                            cboTiles.Items.Add(Name);
                            TerrainAttribute.ListTileset.Add(Name);
                        }
                        else
                        {
                            string Name = TilePath.Substring(0, TilePath.Length - 4).Substring(22);
                            if (cboTiles.Items.Contains(Name))
                            {
                                MessageBox.Show("This tile is already listed.\r\n" + Name);
                                return;
                            }
                            Microsoft.Xna.Framework.Graphics.Texture2D Tile = TilesetViewer.content.Load <Microsoft.Xna.Framework.Graphics.Texture2D>("Maps/Tilesets/" + Name);

                            BattleMapViewer.ActiveMap.ListTilesetPreset.Add(new Terrain.TilesetPreset(Name, Tile.Width, Tile.Height, BattleMapViewer.ActiveMap.TileSize.X, BattleMapViewer.ActiveMap.TileSize.Y, BattleMapViewer.ActiveMap.ListTilesetPreset.Count));
                            BattleMapViewer.ActiveMap.ListTileSet.Add(Tile);
                            //Add the file name to the tile combo box.
                            cboTiles.Items.Add(Name);
                            TerrainAttribute.ListTileset.Add(Name);
                        }

                        cboTiles.SelectedIndex = BattleMapViewer.ActiveMap.ListTilesetPreset.Count - 1;

                        if (BattleMapViewer.ActiveMap.ListTileSet.Count == 1)
                        {
                            Terrain      PresetTerrain = ActiveMap.ListTilesetPreset[0].ArrayTerrain[0, 0];
                            DrawableTile PresetTile    = ActiveMap.ListTilesetPreset[0].ArrayTiles[0, 0];

                            //Asign a new tile at the every position, based on its atribtues.
                            for (int X = BattleMapViewer.ActiveMap.MapSize.X - 1; X >= 0; --X)
                            {
                                for (int Y = BattleMapViewer.ActiveMap.MapSize.Y - 1; Y >= 0; --Y)
                                {
                                    Helper.ReplaceTerrain(X, Y, new Terrain(PresetTerrain), 0);
                                    Helper.ReplaceTile(X, Y, new DrawableTile(PresetTile), 0);
                                }
                            }
                        }
                    }
                    break;

                case ItemSelectionChoices.TileAsBackground:
                    string TileAsBackgroundPath = Items[I];
                    if (TileAsBackgroundPath != null)
                    {
                        string TileName = Path.GetFileNameWithoutExtension(TileAsBackgroundPath);
                        if (cboTiles.Items.Contains(TileName))
                        {
                            MessageBox.Show("This tile is already listed.\r\n" + TileName);
                            return;
                        }

                        BattleMapViewer.ActiveMap.ListTileSet.Add(TilesetViewer.content.Load <Texture2D>("Maps/Tilesets/" + TileName));
                        //Add the file name to the tile combo box.
                        cboTiles.Items.Add(TileName);
                        TerrainAttribute.ListTileset.Add(TileName);
                        cboTiles.SelectedIndex = BattleMapViewer.ActiveMap.ListTileSet.Count - 1;

                        //Asign a new tile at the every position, based on its atribtues.
                        for (int X = BattleMapViewer.ActiveMap.MapSize.X - 1; X >= 0; --X)
                        {
                            for (int Y = BattleMapViewer.ActiveMap.MapSize.Y - 1; Y >= 0; --Y)
                            {
                                Helper.ReplaceTerrain(X, Y, new Terrain(X, Y,
                                                                        0, 0, 1, new TerrainActivation[0], new TerrainBonus[0], new int[0]),
                                                      0);

                                Helper.ReplaceTile(X, Y,
                                                   new DrawableTile(
                                                       new Rectangle((X % (ActiveMap.ListTilesetPreset.Last().ArrayTerrain.GetLength(0))) * ActiveMap.TileSize.X,
                                                                     (Y % (ActiveMap.ListTilesetPreset.Last().ArrayTerrain.GetLength(1))) * ActiveMap.TileSize.Y,
                                                                     ActiveMap.TileSize.X, ActiveMap.TileSize.Y),
                                                       cboTiles.Items.Count - 1),
                                                   0);
                            }
                        }
                    }
                    break;
                }
            }
        }
Example #53
0
        public static void Copy(SpanBitmap src, ref XNA.Texture2D dst, bool fit, XNA.GraphicsDevice device, int?width = null, int?height = null, XNA.SurfaceFormat?fmt = null)
        {
            var fmtx = fmt ?? ToSurfaceFormat(src.PixelFormat);

            Copy(src, ref dst, fit, (w, h) => new XNA.Texture2D(device, width ?? w, height ?? h, false, fmtx));
        }
Example #54
0
        public static Basic ToSurface(this Texture2D image, SadConsole.Font font, bool blockMode = false)
        {
            int imageWidth  = image.Width;
            int imageHeight = image.Height;

            Color[] pixels = new Color[imageWidth * imageHeight];
            image.GetData <Color>(pixels);

            Basic surface = new Basic(imageWidth / font.Size.X, imageHeight / font.Size.Y, font);

            global::System.Threading.Tasks.Parallel.For((int)0, (int)(imageHeight / surface.Font.Size.Y), (h) =>
                                                        //for (int h = 0; h < imageHeight / surface.Font.Size.Y; h++)
            {
                int startY = (h * surface.Font.Size.Y);
                //System.Threading.Tasks.Parallel.For(0, imageWidth / surface.Font.Size.X, (w) =>
                for (int w = 0; w < imageWidth / surface.Font.Size.X; w++)
                {
                    int startX = (w * surface.Font.Size.X);

                    float allR = 0;
                    float allG = 0;
                    float allB = 0;

                    for (int y = 0; y < surface.Font.Size.Y; y++)
                    {
                        for (int x = 0; x < surface.Font.Size.X; x++)
                        {
                            int cY = y + startY;
                            int cX = x + startX;

                            Color color = pixels[cY * imageWidth + cX];

                            allR += color.R;
                            allG += color.G;
                            allB += color.B;
                        }
                    }

                    byte sr = (byte)(allR / (surface.Font.Size.X * surface.Font.Size.Y));
                    byte sg = (byte)(allG / (surface.Font.Size.X * surface.Font.Size.Y));
                    byte sb = (byte)(allB / (surface.Font.Size.X * surface.Font.Size.Y));

                    var newColor = new Color(sr, sg, sb);

                    float sbri = newColor.GetBrightness() * 255;

                    if (blockMode)
                    {
                        if (sbri > 204)
                        {
                            surface.SetGlyph(w, h, 219, newColor); //█
                        }
                        else if (sbri > 152)
                        {
                            surface.SetGlyph(w, h, 178, newColor); //▓
                        }
                        else if (sbri > 100)
                        {
                            surface.SetGlyph(w, h, 177, newColor); //▒
                        }
                        else if (sbri > 48)
                        {
                            surface.SetGlyph(w, h, 176, newColor); //░
                        }
                    }
                    else
                    {
                        if (sbri > 230)
                        {
                            surface.SetGlyph(w, h, (int)'#', newColor);
                        }
                        else if (sbri > 207)
                        {
                            surface.SetGlyph(w, h, (int)'&', newColor);
                        }
                        else if (sbri > 184)
                        {
                            surface.SetGlyph(w, h, (int)'$', newColor);
                        }
                        else if (sbri > 161)
                        {
                            surface.SetGlyph(w, h, (int)'X', newColor);
                        }
                        else if (sbri > 138)
                        {
                            surface.SetGlyph(w, h, (int)'x', newColor);
                        }
                        else if (sbri > 115)
                        {
                            surface.SetGlyph(w, h, (int)'=', newColor);
                        }
                        else if (sbri > 92)
                        {
                            surface.SetGlyph(w, h, (int)'+', newColor);
                        }
                        else if (sbri > 69)
                        {
                            surface.SetGlyph(w, h, (int)';', newColor);
                        }
                        else if (sbri > 46)
                        {
                            surface.SetGlyph(w, h, (int)':', newColor);
                        }
                        else if (sbri > 23)
                        {
                            surface.SetGlyph(w, h, (int)'.', newColor);
                        }
                    }
                }
            }
                                                        );

            return(surface);
        }
Example #55
0
    private void OnGUI()
    {
        if (UoTextureExplorerHelper.NeedsLoading)
        {
            if (GUILayout.Button("Load Art"))
            {
                UoTextureExplorerHelper.LoadArt();
            }

            return;
        }

        if (GUILayout.Button("Unload Art"))
        {
            UoTextureExplorerHelper.UnloadArt();
            return;
        }

        if (GUILayout.Button("Make Atlas"))
        {
            UoTextureExplorerHelper.MakeAtlas(rangeMin, rangeMax);
        }

        if (GUILayout.Button("Trigger first texture"))
        {
            UoTextureExplorerHelper.TriggerFirstTexture();
        }

        graphicTypeToDisplay = (GraphicType)EditorGUILayout.EnumPopup(graphicTypeToDisplay);

        rangeMin         = EditorGUILayout.IntField("Range Min", rangeMin);
        rangeMax         = EditorGUILayout.IntField("Range Max", rangeMax);
        skipNullTextures = EditorGUILayout.Toggle("Skip null textures", skipNullTextures);

        int nullTextureCount = 0;

        scrollPos = EditorGUILayout.BeginScrollView(scrollPos);
        EditorGUILayout.BeginVertical();
        var  widthRemaining = position.width;
        Rect rect           = new Rect(0, 0, widthRemaining, 44 + 2);

        for (int i = rangeMin; i <= rangeMax; i++)
        {
            Microsoft.Xna.Framework.Graphics.Texture2D texture = null;
            if (graphicTypeToDisplay == GraphicType.ArtGraphic)
            {
                texture = UoTextureExplorerHelper.GetLandTexture((uint)i);
            }
            else if (graphicTypeToDisplay == GraphicType.GumpGraphic)
            {
                texture = UoTextureExplorerHelper.GetGumpTexture((ushort)i);
            }

            if (widthRemaining < 44)
            {
                GUILayout.Space(44 + 2);
                rect.y        += 44 + 2;
                widthRemaining = rect.width;
            }

            if (texture != null)
            {
                GUI.DrawTexture(new Rect(rect.x + rect.width - widthRemaining, rect.y, 44, 44), texture.UnityTexture);
            }
            else
            {
                nullTextureCount++;
            }

            if (skipNullTextures == false || texture != null)
            {
                widthRemaining -= 44 + 2;
            }
        }
        EditorGUILayout.EndVertical();
        EditorGUILayout.EndScrollView();

        EditorGUILayout.LabelField("Null texture count", nullTextureCount.ToString());
    }
Example #56
0
        /// <summary>
        /// Loads spine texture from the specified WZ path
        /// </summary>
        /// <param name="page"></param>
        /// <param name="path"></param>
        public void Load(AtlasPage page, string path)
        {
            WzObject frameNode = this.ParentNode[path];

            if (frameNode == null)
            {
                return;
            }


            WzCanvasProperty canvasProperty = null;

            WzImageProperty imageChild = (WzImageProperty)ParentNode[path];

            if (imageChild is WzUOLProperty uolProperty)
            {
                WzObject uolLink = uolProperty.LinkValue;

                if (uolLink is WzCanvasProperty uolPropertyLink)
                {
                    canvasProperty = uolPropertyLink;
                }
                else
                {
                    // other unimplemented prop?
                }
            }
            else if (imageChild is WzCanvasProperty property)
            {
                canvasProperty = property;
            }

            if (canvasProperty != null)
            {
                Bitmap bitmap = canvasProperty.GetLinkedWzCanvasBitmap();
                if (bitmap != null)
                {
                    if (graphicsDevice != null)
                    {
                        Texture2D  tex  = new Texture2D(graphicsDevice, bitmap.Width, bitmap.Height, true, SurfaceFormat.Color);
                        BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat);

                        int bufferSize = data.Height * data.Stride;

                        //create data buffer
                        byte[] bytes = new byte[bufferSize];

                        // copy bitmap data into buffer
                        Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);

                        // copy our buffer to the texture
                        tex.SetData(bytes);

                        // unlock the bitmap data
                        bitmap.UnlockBits(data);

                        page.rendererObject = tex;
                        page.width          = bitmap.Width;
                        page.height         = bitmap.Height;
                    }
                }
            }
        }
Example #57
0
        private Microsoft.Xna.Framework.Rectangle?GetSourceRetangleForFrame(AnimationFrameSave afs, Microsoft.Xna.Framework.Graphics.Texture2D texture2D)
        {
            if (afs == null || texture2D == null)
            {
                return(null);
            }
            else
            {
                Microsoft.Xna.Framework.Rectangle rectangle = new Microsoft.Xna.Framework.Rectangle();
                rectangle.X     = Math.MathFunctions.RoundToInt(afs.LeftCoordinate * texture2D.Width);
                rectangle.Width = Math.MathFunctions.RoundToInt(afs.RightCoordinate * texture2D.Width) - rectangle.X;

                rectangle.Y      = Math.MathFunctions.RoundToInt(afs.TopCoordinate * texture2D.Height);
                rectangle.Height = Math.MathFunctions.RoundToInt(afs.BottomCoordinate * texture2D.Height) - rectangle.Y;

                return(rectangle);
            }
        }
Example #58
0
        public override void Draw(Microsoft.Xna.Framework.Graphics.Texture2D ImageToProcess, RenderHelper rHelper, Microsoft.Xna.Framework.GameTime gt, PloobsEngine.Engine.GraphicInfo GraphicInfo, IWorld world, bool useFloatBuffer)
        {
            //mix with last frame downsampled
            if (tex != null)
            {
                rHelper.PushRenderTarget(rtend);
                rHelper.Clear(Color.Black);
                if (useFloatBuffer)
                {
                    rHelper.RenderTextureComplete(ImageToProcess, Color.FromNonPremultiplied(255, 255, 255, 255), GraphicInfo.FullScreenRectangle, Matrix.Identity, null, true, SpriteSortMode.Deferred, SamplerState.PointClamp);
                    rHelper.RenderTextureComplete(tex, Color.FromNonPremultiplied(255, 255, 255, Amount), GraphicInfo.FullScreenRectangle, Matrix.Identity, null, true, SpriteSortMode.Deferred, SamplerState.PointClamp, BlendState.AlphaBlend);
                }
                else
                {
                    rHelper.RenderTextureComplete(ImageToProcess, Color.FromNonPremultiplied(255, 255, 255, 255), GraphicInfo.FullScreenRectangle, Matrix.Identity, null, true, SpriteSortMode.Deferred, GraphicInfo.SamplerState);
                    rHelper.RenderTextureComplete(tex, Color.FromNonPremultiplied(255, 255, 255, Amount), GraphicInfo.FullScreenRectangle, Matrix.Identity, null, true, SpriteSortMode.Deferred, GraphicInfo.SamplerState, BlendState.AlphaBlend);
                }
                end = rHelper.PopRenderTargetAsSingleRenderTarget2D();
            }

            //DownSample
            rHelper.PushRenderTarget(rt);
            rHelper.Clear(Color.Black);
            if (end == null)
            {
                if (useFloatBuffer)
                {
                    rHelper.RenderTextureComplete(ImageToProcess, Color.White, rt.Bounds, Matrix.Identity, ImageToProcess.Bounds, true, SpriteSortMode.Deferred, SamplerState.PointClamp);
                }
                else
                {
                    rHelper.RenderTextureComplete(ImageToProcess, Color.White, rt.Bounds, Matrix.Identity, ImageToProcess.Bounds, true, SpriteSortMode.Deferred, GraphicInfo.SamplerState);
                }
            }
            else
            {
                if (useFloatBuffer)
                {
                    rHelper.RenderTextureComplete(end, Color.White, rt.Bounds, Matrix.Identity, ImageToProcess.Bounds, true, SpriteSortMode.Deferred, SamplerState.PointClamp);
                }
                else
                {
                    rHelper.RenderTextureComplete(end, Color.White, rt.Bounds, Matrix.Identity, ImageToProcess.Bounds, true, SpriteSortMode.Deferred, GraphicInfo.SamplerState);
                }
            }
            tex = rHelper.PopRenderTargetAsSingleRenderTarget2D();

            rHelper.Clear(Color.Black);
            if (end != null)
            {
                if (useFloatBuffer)
                {
                    rHelper.RenderTextureComplete(end, Color.White, GraphicInfo.FullScreenRectangle, Matrix.Identity, null, true, SpriteSortMode.Deferred, SamplerState.PointClamp);
                }
                else
                {
                    rHelper.RenderTextureComplete(end, Color.White, GraphicInfo.FullScreenRectangle, Matrix.Identity, null, true, SpriteSortMode.Deferred, GraphicInfo.SamplerState);
                }
            }
            else
            {
                if (useFloatBuffer)
                {
                    rHelper.RenderTextureComplete(ImageToProcess, Color.White, GraphicInfo.FullScreenRectangle, Matrix.Identity, null, true, SpriteSortMode.Deferred, SamplerState.PointClamp);
                }
                else
                {
                    rHelper.RenderTextureComplete(ImageToProcess, Color.White, GraphicInfo.FullScreenRectangle, Matrix.Identity, null, true, SpriteSortMode.Deferred, GraphicInfo.SamplerState);
                }
            }
        }
Example #59
0
        public static GameObject instance_create(Vector2 position, Type obj, string layer)
        {
            // First we need to convert layer name to actual layer
            RoomLayer realLayer = currentRoom.Layers.FirstOrDefault(x => x.Name == layer);

            GameObject  o = (GameObject)Activator.CreateInstance(obj);
            Spritesheet s = new Spritesheet();

            if (o.Sprite != null)
            {
                s = Sprites.FirstOrDefault(x => x.Name == o.Sprite.TextureSource);
            }

            o.OriginalType = obj;
            o.TypeString   = obj.ToString();


            if (s == null)
            {
                Texture2D tx = ConvertToTexture(SimplexIde.Properties.Resources.Question_16x, GraphicsDevice);

                o.Sprite                    = new Sprite();
                o.Sprite.Texture            = tx;
                o.Sprite.ImageRectangle     = new Microsoft.Xna.Framework.Rectangle(0, 0, 16, 16);
                o.Sprite.TextureRows        = 1;
                o.Sprite.TextureCellsPerRow = 1;
                o.Sprite.ImageSize          = new Vector2(16, 16);
                o.Sprite.FramesCount        = 1;
                o.FramesCount               = 1;
                o.Sprite.cellW              = 16;
                o.Sprite.cellH              = 16;

                o.Position = new Vector2(position.X - 8, position.Y - 8);
                o.Sprite.ImageRectangle = new Microsoft.Xna.Framework.Rectangle(0, 0, 16, 16);
            }
            else
            {
                o.Sprite.Texture            = s.Texture;
                o.Sprite.ImageRectangle     = new Microsoft.Xna.Framework.Rectangle(0, 0, s.CellWidth, s.CellHeight);
                o.Sprite.TextureRows        = s.Rows;
                o.Sprite.TextureCellsPerRow = s.Texture.Width / s.CellWidth;
                o.Sprite.ImageSize          = new Vector2(s.CellWidth, s.CellHeight);
                o.Sprite.FramesCount        = Math.Max((s.Texture.Width / s.CellWidth) * (s.Texture.Height / s.CellHeight) - 1, 1);
                o.FramesCount  = Math.Max(o.Sprite.FramesCount - 1, 1);
                o.Sprite.cellW = s.CellHeight;
                o.Sprite.cellH = s.CellWidth;

                o.Position = new Vector2(position.X - s.CellWidth / 2f, position.Y - s.CellHeight / 2f);
                o.Sprite.ImageRectangle = new Microsoft.Xna.Framework.Rectangle(0, 0, s.CellWidth, s.CellHeight);
            }


            o.LayerName = realLayer.Name;
            o.Layer     = (ObjectLayer)realLayer;

            currentObject = o;
            o.EvtCreate();
            o.EvtCreateEnd();

            o.Layer.Objects.Add(o);
            SceneObjects.Add(o);
            sh.RegisterObject(o);

            if (CollisionsTree.CollisionActiveTypes.Contains(o.GetType()))
            {
                SceneColliders.Add(o);
            }

            return(o);
        }
        internal void DrawSpriteGlyphDF(Texture2D texture, Vector4 dest, Vector4 source, Color color, float font_scale)
        {
            if (!m_DrawString_InProgress)
                Logging.Fatal("BeginDrawString() must be called before DrawSpriteGlyph()");

            Vector4 uv = new Vector4(
                (float)source.X / texture.Width,
                (float)source.Y / texture.Height,
                (float)(source.X + source.Z) / texture.Width,
                (float)(source.Y + source.W) / texture.Height);

            float smoothing = 0.4f * Math.Pow(0.333f, font_scale * 2f) + 0.05f;
            Vector4 extra = new Vector4(0, 0, smoothing, 2);

            VertexPositionTextureHueExtra[] v = new VertexPositionTextureHueExtra[4]
            {
                new VertexPositionTextureHueExtra(new Vector3(dest.X, dest.Y, m_DrawString_Depth), new Vector2(uv.X, uv.Y), color, extra), // top left
                new VertexPositionTextureHueExtra(new Vector3(dest.X + dest.Z, dest.Y, m_DrawString_Depth), new Vector2(uv.Z, uv.Y), color, extra), // top right
                new VertexPositionTextureHueExtra(new Vector3(dest.X, dest.Y + dest.W, m_DrawString_Depth), new Vector2(uv.X, uv.W), color, extra), // bottom left
                new VertexPositionTextureHueExtra(new Vector3(dest.X + dest.Z, dest.Y + dest.W, m_DrawString_Depth), new Vector2(uv.Z, uv.W), color, extra) // bottom right
            };

            for (int i = 0; i < 4; i++)
                m_DrawString_VertexList.Add(v[i]);
        }