public static void Create(Submarine sub)
        {
            int width = 4096; int height = 4096;

            Rectangle subDimensions = sub.CalculateDimensions(false);
            Vector2   viewPos       = subDimensions.Center.ToVector2();
            float     scale         = Math.Min(width / (float)subDimensions.Width, height / (float)subDimensions.Height);

            var viewMatrix = Matrix.CreateTranslation(new Vector3(width / 2.0f, height / 2.0f, 0));
            var transform  = Matrix.CreateTranslation(
                new Vector3(-viewPos.X, viewPos.Y, 0)) *
                             Matrix.CreateScale(new Vector3(scale, scale, 1)) *
                             viewMatrix;

            using (RenderTarget2D rt = new RenderTarget2D(
                       GameMain.Instance.GraphicsDevice,
                       width, height, false, SurfaceFormat.Color, DepthFormat.None))
                using (SpriteBatch spriteBatch = new SpriteBatch(GameMain.Instance.GraphicsDevice))
                {
                    Viewport prevViewport = GameMain.Instance.GraphicsDevice.Viewport;
                    GameMain.Instance.GraphicsDevice.Viewport = new Viewport(0, 0, width, height);
                    GameMain.Instance.GraphicsDevice.SetRenderTarget(rt);
                    GameMain.Instance.GraphicsDevice.Clear(Color.Transparent);

                    spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.NonPremultiplied, null, null, null, null, transform);
                    Submarine.Draw(spriteBatch);
                    Submarine.DrawFront(spriteBatch);
                    Submarine.DrawDamageable(spriteBatch, null);
                    spriteBatch.End();

                    GameMain.Instance.GraphicsDevice.SetRenderTarget(null);
                    GameMain.Instance.GraphicsDevice.Viewport = prevViewport;
                    using (FileStream fs = File.Open("wikiimage.png", System.IO.FileMode.Create))
                    {
                        rt.SaveAsPng(fs, width, height);
                    }
                }
        }
        private void GenerateTownSprite_OnClick(UIMouseEvent evt, UIElement listeningElement)
        {
            Main.NewText("Creating TownNPC sprite from current Player");

            int            frames       = 25;
            RenderTarget2D renderTarget = new RenderTarget2D(Main.graphics.GraphicsDevice, 40, frames * 58);

            Main.instance.GraphicsDevice.SetRenderTarget(renderTarget);
            Main.instance.GraphicsDevice.Clear(Color.Transparent);
            Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise);

            Main.gameMenu = true;
            // TODO: Figure out how to get all poses.
            for (int i = 0; i < frames; i++)
            {
                Main.LocalPlayer.PlayerFrame();
                Main.LocalPlayer.direction = -1;

                // Right now this code simply uses the Player animation frames, but they don't match up to TownNPC frames, and there are only 20 instead of ~25
                Main.LocalPlayer.bodyFrame.Y = i * 56;
                Main.LocalPlayer.legFrame.Y  = i * 56;

                Main.instance.DrawPlayer(Main.LocalPlayer, Main.screenPosition + /*Main.LocalPlayer.position +*/ new Vector2(10, i * 58), 0f, Vector2.Zero, 0f);                 // add Main.screenPosition since DrawPlayer will subtract it
            }
            Main.gameMenu = false;

            Main.spriteBatch.End();
            Main.instance.GraphicsDevice.SetRenderTarget(null);

            Directory.CreateDirectory(folder);
            string path = Path.Combine(folder, "ModdersToolkit_ExportedTownNPCSprite.png");

            using (Stream stream = File.OpenWrite(path)) {
                renderTarget.SaveAsPng(stream, 40, frames * 58);
            }

            //	Process.Start(folder);
        }
        /// <summary>Write an asset instance to disk.</summary>
        /// <param name="asset">The asset value.</param>
        /// <param name="toPathWithoutExtension">The absolute path to the export file, without the file extension.</param>
        /// <param name="relativePath">The relative path within the content folder.</param>
        /// <param name="platform">The operating system running the unpacker.</param>
        /// <param name="error">An error phrase indicating why writing to disk failed (if applicable).</param>
        /// <returns>Returns whether writing to disk completed successfully.</returns>
        public override bool TryWriteFile(object asset, string toPathWithoutExtension, string relativePath, Platform platform, out string error)
        {
            SpriteFont font = (SpriteFont)asset;

            // get texture
            Texture2D texture = platform == Platform.Windows
                ? this.RequireField <Texture2D>(font, "textureValue")
                : this.RequireProperty <Texture2D>(font, "Texture");

            // save texture
            using (Stream stream = File.Create($"{toPathWithoutExtension}.png"))
            {
                if (platform.IsMono() && texture.Format == SurfaceFormat.Dxt3) // MonoGame can't read DXT3 textures directly, need to export through GPU
                {
                    using (RenderTarget2D renderTarget = this.RenderWithGpu(texture))
                        renderTarget.SaveAsPng(stream, texture.Width, texture.Height);
                }
                else
                {
                    texture.SaveAsPng(stream, texture.Width, texture.Height);
                }
            }

            // save font data
            var data = new
            {
                font.LineSpacing,
                font.Spacing,
                font.DefaultCharacter,
                font.Characters,
                Glyphs = this.GetGlyphs(font, platform)
            };

            File.WriteAllText($"{toPathWithoutExtension}.{this.GetDataExtension()}", this.FormatData(data));

            error = null;
            return(true);
        }
Example #4
0
 internal void PrintScreen()
 {
     using (SaveFileDialog dialog = new SaveFileDialog())
     {
         dialog.DefaultExt       = "png";
         dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
         dialog.Filter           = $"{Catalog.GetString("Image files (*.png)")}|*.png";
         if (dialog.ShowDialog() == DialogResult.OK)
         {
             byte[]         backBuffer     = new byte[graphicsDeviceManager.PreferredBackBufferWidth * graphicsDeviceManager.PreferredBackBufferHeight * 4];
             GraphicsDevice graphicsDevice = graphicsDeviceManager.GraphicsDevice;
             using (RenderTarget2D screenshot = new RenderTarget2D(graphicsDevice, graphicsDeviceManager.PreferredBackBufferWidth, graphicsDeviceManager.PreferredBackBufferHeight, false, graphicsDevice.PresentationParameters.BackBufferFormat, DepthFormat.None))
             {
                 graphicsDevice.GetBackBufferData(backBuffer);
                 screenshot.SetData(backBuffer);
                 using (FileStream stream = File.OpenWrite(dialog.FileName))
                 {
                     screenshot.SaveAsPng(stream, graphicsDeviceManager.PreferredBackBufferWidth, graphicsDeviceManager.PreferredBackBufferHeight);
                 }
             }
         }
     }
 }
        private static void CaptureScreen()
        {
            try
            {
                Core.GameMessage.HideMessage();

                var fileName = $"{DateTime.Now:yyyy-MM-dd_HH.mm.ss}.png";
                var file     = new ScreenshotsFolder().CreateFile(fileName, CreationCollisionOption.ReplaceExisting);

                if (!Core.GraphicsManager.IsFullScreen)
                {
                    using (var b = new System.Drawing.Bitmap(Core.WindowSize.Width, Core.WindowSize.Height))
                        using (var g = System.Drawing.Graphics.FromImage(b))
                            using (var fileStream = file.Open(FileAccess.ReadAndWrite))
                            {
                                g.CopyFromScreen(Core.Window.ClientBounds.X, Core.Window.ClientBounds.Y, 0, 0, new System.Drawing.Size(b.Width, b.Height));
                                b.Save(fileStream, ImageFormat.Png);
                            }
                }
                else
                {
                    using (var screenshot = new RenderTarget2D(Core.GraphicsDevice, Core.WindowSize.Width, Core.WindowSize.Height, false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8))
                        using (var fileStream = file.Open(FileAccess.ReadAndWrite))
                        {
                            Core.GraphicsDevice.SetRenderTarget(screenshot);
                            Core.Draw();
                            Core.GraphicsDevice.SetRenderTarget(null);

                            screenshot.SaveAsPng(fileStream, Core.WindowSize.Width, Core.WindowSize.Height);
                        }
                }

                Core.GameMessage.SetupText($"{Localization.GetString("game_message_screenshot")}{fileName}", FontManager.MainFont, Color.White);
                Core.GameMessage.ShowMessage(12, Core.GraphicsDevice);
            }
            catch (Exception ex) { Logger.Log(Logger.LogTypes.ErrorMessage, $"Basic.vb: {Localization.GetString("game_message_screenshot_failed")}. More information: {ex.Message}"); }
        }
Example #6
0
 private Texture2D PreMultiply(Texture2D texture)
 {
     try
     {
         RenderTarget2D result = new RenderTarget2D(Game1.graphics.GraphicsDevice, texture.Width, texture.Height);
         Game1.graphics.GraphicsDevice.SetRenderTarget(result);
         Game1.graphics.GraphicsDevice.Clear(Color.Black);
         Game1.spriteBatch.Begin(SpriteSortMode.Immediate, ModEntry.BlendColor);
         Game1.spriteBatch.Draw(texture, texture.Bounds, Color.White);
         Game1.spriteBatch.End();
         Game1.spriteBatch.Begin(SpriteSortMode.Immediate, ModEntry.BlendAlpha);
         Game1.spriteBatch.Draw(texture, texture.Bounds, Color.White);
         Game1.spriteBatch.End();
         Game1.graphics.GraphicsDevice.SetRenderTarget(null);
         MemoryStream stream = new MemoryStream();
         result.SaveAsPng(stream, texture.Width, texture.Height);
         return(Texture2D.FromStream(Game1.graphics.GraphicsDevice, stream));
     }
     catch (Exception err)
     {
         this.Monitor.Log($"Failed to PreMultiply texture, alpha will not work properly\n{err.Message}\n{err.StackTrace}", LogLevel.Warn);
         return(texture);
     }
 }
Example #7
0
        private void SaveScreenshot(RenderTarget2D rt)
        {
            const string screenshotDir = "Screenshots";

            Task.Run(() =>
            {
                Directory.CreateDirectory(screenshotDir);

                string path;
                string filename;
                int i = 1;
                do
                {
                    filename = $"{DateTime.Now.ToUnix()}-{i}.png";
                    path     = Path.Combine(screenshotDir, filename);
                    i++;
                }while (File.Exists(path));

                using var fs = new FileStream(path, FileMode.Create);
                rt.SaveAsPng(fs, rt.Width, rt.Height);

                logger.Log(LogLevel.Debug, "Writing screenshot " + filename);
            });
        }
Example #8
0
 public void DumpAll(string dumploc)
 {
     for (int i = 0; i < BUFFER_SIZE; i++)
     {
         Selection selection = Buffer[i];
         Rectangle selrect   = selection.Region;
         if (selrect != Rectangle.Empty)
         {
             RenderTarget2D target = new RenderTarget2D(GraphicsDevice, selrect.Width, selrect.Height);
             GraphicsDevice.SetRenderTarget(target);
             GraphicsDevice.Clear(Color.Transparent);
             SpriteBatch spriteBatch = new SpriteBatch(GraphicsDevice);
             spriteBatch.Begin();
             spriteBatch.Draw(Texture, new Rectangle(0, 0, selrect.Width, selrect.Height), new Rectangle(selrect.X, selrect.Y, selrect.Width, selrect.Height), Color.White);
             spriteBatch.End();
             GraphicsDevice.SetRenderTarget(null);
             using (FileStream stream = File.OpenWrite(dumploc + "\\" + i + ".png")) {
                 target.SaveAsPng(stream, target.Width, target.Height);
                 stream.Flush();
                 stream.Close();
             }
         }
     }
 }
Example #9
0
        public void SavePictureOfMap(string loc)
        {
            GraphicsDevice graphicsdevice = World.ViewData.GraphicsDevice;
            RenderTarget2D target         = new RenderTarget2D(graphicsdevice, CurrentMap.Width << 4, CurrentMap.Height << 4);

            graphicsdevice.SetRenderTarget(target);

            Vector2 cScrolling = World.Camera.Location;
            float   cScale     = World.Camera.Scale;
            float   cRotation  = World.Camera.Rotation;

            World.Camera.Reset();

            RenderMap(CurrentMap);

            World.Camera.Location = cScrolling;
            World.Camera.Scale    = cScale;
            World.Camera.Rotation = cRotation;

            graphicsdevice.SetRenderTarget(null);
            using (FileStream fs = File.OpenWrite(loc)) {
                target.SaveAsPng(fs, target.Width, target.Height);
            }
        }
Example #10
0
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            int    i;
            Random rnd = new Random();

            GraphicsDevice.SetRenderTarget(rt2d);
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();
            for (i = 0; i < 1000; i++)
            {
                Rectangle rect = new Rectangle(rnd.Next() % 1920, rnd.Next() % 1080, 256, 256);
                spriteBatch.Draw(tex, rect, Color.White);
            }

            spriteBatch.End();

            GraphicsDevice.SetRenderTarget(null);


            spriteBatch.Begin();
            spriteBatch.Draw(rt2d, new Rectangle(0, 0, 800, 600), Color.White);
            spriteBatch.End();


            MemoryStream ms = new MemoryStream();

            rt2d.SaveAsPng(ms, rt2d.Width, rt2d.Height);

            string fn = String.Format("o:\\test\\output_{0:0000}.png", numPng++);

            File.WriteAllBytes(fn, ms.ToArray());


            base.Draw(gameTime);
        }
Example #11
0
        private void export(RenderQueueEntry render)
        {
            GameLocation loc = render.loc;

            //int oldZoom = Game1.pixelZoom;
            //Game1.pixelZoom = 4;
            SpriteBatch    b          = Game1.spriteBatch;// new SpriteBatch(Game1.graphics.GraphicsDevice);
            GraphicsDevice dev        = Game1.graphics.GraphicsDevice;
            var            display    = Game1.mapDisplayDevice;
            RenderTarget2D output     = null;
            RenderTarget2D oldOutput  = null;
            RenderTarget2D myLighting = null;
            Stream         stream     = null;
            bool           begun      = false;
            Rectangle      oldView    = new Rectangle();
            float          oldZoomL   = Game1.options.zoomLevel;

            Game1.options.zoomLevel = 0.25f;
            try
            {
                Log.info("Rendering " + loc.Name + "...");
                output = new RenderTarget2D(dev, loc.map.DisplayWidth / 4, loc.map.DisplayHeight / 4);
                RectangleX viewportX = new RectangleX(0, 0, output.Width, output.Height);
                Rectangle  viewport  = new Rectangle(0, 0, output.Width * 4, output.Height * 4);
                oldView        = Game1.viewport;
                Game1.viewport = viewport;

                Matrix transform = Matrix.CreateScale(0.25f);

                if (loc is DecoratableLocation)
                {
                    foreach (Furniture f in (loc as DecoratableLocation).furniture)
                    {
                        f.updateDrawPosition();
                    }
                }

                if (render.Lighting)
                {
                    int   num1 = 32;
                    float num2 = 1f;
                    if (Game1.options != null)
                    {
                        num1 = Game1.options.lightingQuality;
                        num2 = Game1.options.zoomLevel;
                    }
                    int width  = (int)((double)output.Width * (1.0 / (double)num2) + (double)Game1.tileSize) / (num1 / 2);
                    int height = (int)((double)output.Height * (1.0 / (double)num2) + (double)Game1.tileSize) / (num1 / 2);
                    myLighting = new RenderTarget2D(dev, width, height, false, SurfaceFormat.Color, DepthFormat.None, 0, RenderTargetUsage.PreserveContents);
                    if (Game1.drawLighting)
                    {
                        dev.SetRenderTarget(myLighting);
                        dev.Clear(Color.White * 0f);
                        b.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, SamplerState.PointClamp, null, null, null, transform);
                        b.Draw(Game1.staminaRect, myLighting.Bounds, loc.Name.Equals("UndergroundMine") ? Game1.mine.getLightingColor(null /*gameTime*/) : ((!Game1.ambientLight.Equals(Color.White) && (!Game1.isRaining || !loc.IsOutdoors)) ? Game1.ambientLight : Game1.outdoorLight));
                        for (int i = 0; i < Game1.currentLightSources.Count; i++)
                        {
                            //if (Utility.isOnScreen(Game1.currentLightSources.ElementAt(i).position, (int)(Game1.currentLightSources.ElementAt(i).radius * (float)Game1.tileSize * 4f)))
                            {
                                b.Draw(Game1.currentLightSources.ElementAt(i).lightTexture, Game1.currentLightSources.ElementAt(i).position.Value / (float)(Game1.options.lightingQuality / 2), new Microsoft.Xna.Framework.Rectangle?(Game1.currentLightSources.ElementAt(i).lightTexture.Bounds), Game1.currentLightSources.ElementAt(i).color.Value, 0f, new Vector2((float)Game1.currentLightSources.ElementAt(i).lightTexture.Bounds.Center.X, (float)Game1.currentLightSources.ElementAt(i).lightTexture.Bounds.Center.Y), Game1.currentLightSources.ElementAt(i).radius.Value / (float)(Game1.options.lightingQuality / 2), SpriteEffects.None, 0.9f);
                            }
                        }
                        b.End();
                        //dev.SetRenderTarget((Game1.options.zoomLevel == 1f) ? null : this.screen);
                    }
                    if (Game1.bloomDay && Game1.bloom != null)
                    {
                        Game1.bloom.BeginDraw();
                    }
                }
                dev.SetRenderTarget(output);
                dev.Clear(Color.Black);
                {
                    if (loc != Game1.currentLocation)
                    {
                        loc.map.LoadTileSheets(display);
                    }

                    b.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null, transform);
                    begun = true;
                    if (render.Tiles)
                    {
                        display.BeginScene(b);
                        loc.map.GetLayer("Back").Draw(Game1.mapDisplayDevice, new xTile.Dimensions.Rectangle(0, 0, output.Width * 4, output.Height * 4), xTile.Dimensions.Location.Origin, false, 4);
                        loc.drawWater(b);
                    }
                    if (render.Characters)
                    {
                        var chars = loc.characters.ToList();
                        if (render.Event && Game1.CurrentEvent != null && loc == Game1.currentLocation)
                        {
                            chars = Game1.CurrentEvent.actors;
                        }

                        foreach (NPC npc in chars)
                        {
                            if (!npc.swimming.Value && !npc.HideShadow && !npc.IsInvisible && !loc.shouldShadowBeDrawnAboveBuildingsLayer(npc.getTileLocation()))
                            {
                                b.Draw(Game1.shadowTexture, Game1.GlobalToLocal(viewport, npc.position + new Vector2((float)(npc.Sprite.SpriteWidth * Game1.pixelZoom) / 2f, (float)(npc.GetBoundingBox().Height + (npc.IsMonster ? 0 : (Game1.pixelZoom * 3))))), new Microsoft.Xna.Framework.Rectangle?(Game1.shadowTexture.Bounds), Color.White, 0f, new Vector2((float)Game1.shadowTexture.Bounds.Center.X, (float)Game1.shadowTexture.Bounds.Center.Y), ((float)Game1.pixelZoom + (float)npc.yJumpOffset / 40f) * npc.Scale, SpriteEffects.None, Math.Max(0f, (float)npc.getStandingY() / 10000f) - 1E-06f);
                            }
                        }
                    }
                    if (render.Player && Game1.currentLocation == loc)
                    {
                        if (Game1.displayFarmer && !Game1.player.swimming.Value && !Game1.player.isRidingHorse() && !Game1.currentLocation.shouldShadowBeDrawnAboveBuildingsLayer(Game1.player.getTileLocation()))
                        {
                            b.Draw(Game1.shadowTexture, Game1.GlobalToLocal(Game1.player.position + new Vector2(32f, 24f)), new Microsoft.Xna.Framework.Rectangle?(Game1.shadowTexture.Bounds), Color.White, 0f, new Vector2((float)Game1.shadowTexture.Bounds.Center.X, (float)Game1.shadowTexture.Bounds.Center.Y), 4f - (((Game1.player.running || Game1.player.UsingTool) && Game1.player.FarmerSprite.currentAnimationIndex > 1) ? ((float)Math.Abs(FarmerRenderer.featureYOffsetPerFrame[Game1.player.FarmerSprite.CurrentFrame]) * 0.5f) : 0f), SpriteEffects.None, 0f);
                        }
                    }
                    if (render.Tiles)
                    {
                        loc.map.GetLayer("Buildings").Draw(Game1.mapDisplayDevice, new xTile.Dimensions.Rectangle(0, 0, output.Width * 4, output.Height * 4), xTile.Dimensions.Location.Origin, false, 4);
                        display.EndScene();
                    }
                    b.End();
                    begun = false;

                    b.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null, transform);
                    begun = true;
                    if (render.Characters)
                    {
                        var chars = loc.characters.ToList();
                        if (render.Event && Game1.CurrentEvent != null && loc == Game1.currentLocation)
                        {
                            chars = Game1.CurrentEvent.actors;
                        }

                        foreach (NPC npc in chars)
                        {
                            if (!npc.swimming.Value && !npc.HideShadow && !npc.IsInvisible && !loc.shouldShadowBeDrawnAboveBuildingsLayer(npc.getTileLocation()))
                            {
                                b.Draw(Game1.shadowTexture, Game1.GlobalToLocal(viewport, npc.position + new Vector2((float)(npc.Sprite.SpriteWidth * Game1.pixelZoom) / 2f, (float)(npc.GetBoundingBox().Height + (npc.IsMonster ? 0 : (Game1.pixelZoom * 3))))), new Microsoft.Xna.Framework.Rectangle?(Game1.shadowTexture.Bounds), Color.White, 0f, new Vector2((float)Game1.shadowTexture.Bounds.Center.X, (float)Game1.shadowTexture.Bounds.Center.Y), ((float)Game1.pixelZoom + (float)npc.yJumpOffset / 40f) * npc.Scale, SpriteEffects.None, Math.Max(0f, (float)npc.getStandingY() / 10000f) - 1E-06f);
                            }
                        }
                    }
                    if (render.Player && Game1.currentLocation == loc)
                    {
                        if (Game1.displayFarmer && !Game1.player.swimming.Value && !Game1.player.isRidingHorse() && Game1.currentLocation.shouldShadowBeDrawnAboveBuildingsLayer(Game1.player.getTileLocation()))
                        {
                            b.Draw(Game1.shadowTexture, Game1.GlobalToLocal(Game1.player.position + new Vector2(32f, 24f)), new Microsoft.Xna.Framework.Rectangle?(Game1.shadowTexture.Bounds), Color.White, 0f, new Vector2((float)Game1.shadowTexture.Bounds.Center.X, (float)Game1.shadowTexture.Bounds.Center.Y), 4f - (((Game1.player.running || Game1.player.UsingTool) && Game1.player.FarmerSprite.currentAnimationIndex > 1) ? ((float)Math.Abs(FarmerRenderer.featureYOffsetPerFrame[Game1.player.FarmerSprite.CurrentFrame]) * 0.5f) : 0f), SpriteEffects.None, Math.Max(0.0001f, (float)Game1.player.getStandingY() / 10000f + 0.00011f) - 0.0001f);
                        }
                        if (Game1.displayFarmer)
                        {
                            Game1.player.draw(b);
                        }
                    }
                    if (render.Event && loc == Game1.currentLocation)
                    {
                        if ((Game1.eventUp || Game1.killScreen) && !Game1.killScreen && Game1.currentLocation.currentEvent != null)
                        {
                            loc.currentEvent.draw(b);
                        }
                    }
                    if (render.Location)
                    {
                        if (Game1.player.currentUpgrade != null && Game1.player.currentUpgrade.daysLeftTillUpgradeDone <= 3 && loc.Name.Equals("Farm"))
                        {
                            b.Draw(Game1.player.currentUpgrade.workerTexture, Game1.GlobalToLocal(viewport, Game1.player.currentUpgrade.positionOfCarpenter), new Microsoft.Xna.Framework.Rectangle?(Game1.player.currentUpgrade.getSourceRectangle()), Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, (Game1.player.currentUpgrade.positionOfCarpenter.Y + (float)(Game1.tileSize * 3 / 4)) / 10000f);
                        }

                        var charsField   = Helper.Reflection.GetField <NetCollection <NPC> >(loc, "characters");
                        var farmersField = Helper.Reflection.GetField <FarmerCollection>(loc, "farmers");
                        var chars        = loc.characters;
                        var farmers      = loc.farmers;
                        try
                        {
                            if (!render.Player)
                            {
                                var type = typeof(Game1).Assembly.GetType("StardewValley.Network.FarmerCollection");
                                var val  = (FarmerCollection)type.GetConstructor(new Type[] { typeof(GameLocation) }).Invoke(new object[] { loc });
                                farmersField.SetValue(val);
                            }
                            if (!render.Characters)
                            {
                                charsField.SetValue(new NetCollection <NPC>());
                            }

                            loc.draw(b);
                        }
                        finally
                        {
                            farmersField.SetValue(farmers);
                            charsField.SetValue(chars);
                        }
                    }
                    if (render.Player && Game1.currentLocation == loc)
                    {
                        if (Game1.player.ActiveObject == null && (Game1.player.UsingTool || Game1.pickingTool) && Game1.player.CurrentTool != null && (!Game1.player.CurrentTool.Name.Equals("Seeds") || Game1.pickingTool))
                        {
                            Game1.drawTool(Game1.player);
                        }
                    }
                    if (render.Location)
                    {
                        if (loc.Name.Equals("Farm"))
                        {
                            Helper.Reflection.GetMethod(Game1.game1, "drawFarmBuildings").Invoke();
                        }
                    }
                    if (render.Location)
                    {
                        if (Game1.tvStation >= 0)
                        {
                            b.Draw(Game1.tvStationTexture, Game1.GlobalToLocal(viewport, new Vector2((float)(6 * Game1.tileSize + Game1.tileSize / 4), (float)(2 * Game1.tileSize + Game1.tileSize / 2))), new Microsoft.Xna.Framework.Rectangle?(new Microsoft.Xna.Framework.Rectangle(Game1.tvStation * 24, 0, 24, 15)), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 1E-08f);
                        }
                    }
                    if (render.Tiles)
                    {
                        display.BeginScene(b);
                        loc.map.GetLayer("Front").Draw(Game1.mapDisplayDevice, new xTile.Dimensions.Rectangle(0, 0, output.Width * 4, output.Height * 4), xTile.Dimensions.Location.Origin, false, 4);
                        display.EndScene();
                    }
                    if (render.Location)
                    {
                        loc.drawAboveFrontLayer(b);
                    }
                    b.End();
                    begun = false;

                    b.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null, transform);
                    begun = true;
                    if (render.Location)
                    {
                        if (loc.Name.Equals("Farm") && Game1.stats.SeedsSown >= 200u)
                        {
                            b.Draw(Game1.debrisSpriteSheet, Game1.GlobalToLocal(viewport, new Vector2((float)(3 * Game1.tileSize + Game1.tileSize / 4), (float)(Game1.tileSize + Game1.tileSize / 3))), new Microsoft.Xna.Framework.Rectangle?(Game1.getSourceRectForStandardTileSheet(Game1.debrisSpriteSheet, 16, -1, -1)), Color.White);
                            b.Draw(Game1.debrisSpriteSheet, Game1.GlobalToLocal(viewport, new Vector2((float)(4 * Game1.tileSize + Game1.tileSize), (float)(2 * Game1.tileSize + Game1.tileSize))), new Microsoft.Xna.Framework.Rectangle?(Game1.getSourceRectForStandardTileSheet(Game1.debrisSpriteSheet, 16, -1, -1)), Color.White);
                            b.Draw(Game1.debrisSpriteSheet, Game1.GlobalToLocal(viewport, new Vector2((float)(5 * Game1.tileSize), (float)(2 * Game1.tileSize))), new Microsoft.Xna.Framework.Rectangle?(Game1.getSourceRectForStandardTileSheet(Game1.debrisSpriteSheet, 16, -1, -1)), Color.White);
                            b.Draw(Game1.debrisSpriteSheet, Game1.GlobalToLocal(viewport, new Vector2((float)(3 * Game1.tileSize + Game1.tileSize / 2), (float)(3 * Game1.tileSize))), new Microsoft.Xna.Framework.Rectangle?(Game1.getSourceRectForStandardTileSheet(Game1.debrisSpriteSheet, 16, -1, -1)), Color.White);
                            b.Draw(Game1.debrisSpriteSheet, Game1.GlobalToLocal(viewport, new Vector2((float)(5 * Game1.tileSize - Game1.tileSize / 4), (float)Game1.tileSize)), new Microsoft.Xna.Framework.Rectangle?(Game1.getSourceRectForStandardTileSheet(Game1.debrisSpriteSheet, 16, -1, -1)), Color.White);
                            b.Draw(Game1.debrisSpriteSheet, Game1.GlobalToLocal(viewport, new Vector2((float)(4 * Game1.tileSize), (float)(3 * Game1.tileSize + Game1.tileSize / 6))), new Microsoft.Xna.Framework.Rectangle?(Game1.getSourceRectForStandardTileSheet(Game1.debrisSpriteSheet, 16, -1, -1)), Color.White);
                            b.Draw(Game1.debrisSpriteSheet, Game1.GlobalToLocal(viewport, new Vector2((float)(4 * Game1.tileSize + Game1.tileSize / 5), (float)(2 * Game1.tileSize + Game1.tileSize / 3))), new Microsoft.Xna.Framework.Rectangle?(Game1.getSourceRectForStandardTileSheet(Game1.debrisSpriteSheet, 16, -1, -1)), Color.White);
                        }
                    }
                    if (render.Player && Game1.currentLocation == loc)
                    {
                        var meth = typeof(Game1).GetMethod("checkBigCraftableBoundariesForFrontLayer", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                        if (Game1.displayFarmer && Game1.player.ActiveObject != null && Game1.player.ActiveObject.bigCraftable.Value && (bool)meth.Invoke(Game1.game1, new object[] { }) && Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location(Game1.player.getStandingX(), Game1.player.getStandingY()), viewport.Size) == null)
                        {
                            Game1.drawPlayerHeldObject(Game1.player);
                        }
                        else if (Game1.displayFarmer && Game1.player.ActiveObject != null && ((Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location((int)Game1.player.position.X, (int)Game1.player.position.Y - Game1.tileSize * 3 / 5), viewport.Size) != null && !Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location((int)Game1.player.position.X, (int)Game1.player.position.Y - Game1.tileSize * 3 / 5), viewport.Size).TileIndexProperties.ContainsKey("FrontAlways")) || (Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location(Game1.player.GetBoundingBox().Right, (int)Game1.player.position.Y - Game1.tileSize * 3 / 5), viewport.Size) != null && !Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location(Game1.player.GetBoundingBox().Right, (int)Game1.player.position.Y - Game1.tileSize * 3 / 5), viewport.Size).TileIndexProperties.ContainsKey("FrontAlways"))))
                        {
                            Game1.drawPlayerHeldObject(Game1.player);
                        }
                        if ((Game1.player.UsingTool || Game1.pickingTool) && Game1.player.CurrentTool != null && (!Game1.player.CurrentTool.Name.Equals("Seeds") || Game1.pickingTool) && Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location(Game1.player.getStandingX(), (int)Game1.player.position.Y - Game1.tileSize * 3 / 5), viewport.Size) != null && Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location(Game1.player.getStandingX(), Game1.player.getStandingY()), viewport.Size) == null)
                        {
                            Game1.drawTool(Game1.player);
                        }
                    }
                    if (render.Tiles)
                    {
                        if (loc.map.GetLayer("AlwaysFront") != null)
                        {
                            display.BeginScene(b);
                            loc.map.GetLayer("AlwaysFront").Draw(Game1.mapDisplayDevice, new xTile.Dimensions.Rectangle(0, 0, output.Width * 4, output.Height * 4), xTile.Dimensions.Location.Origin, false, 4);
                            display.EndScene();
                        }
                    }
                    if (render.Player && Game1.currentLocation == loc)
                    {
                        if (Game1.toolHold > 400f && Game1.player.CurrentTool.UpgradeLevel >= 1 && Game1.player.canReleaseTool)
                        {
                            Color color = Color.White;
                            switch ((int)(Game1.toolHold / 600f) + 2)
                            {
                            case 1:
                                color = Tool.copperColor;
                                break;

                            case 2:
                                color = Tool.steelColor;
                                break;

                            case 3:
                                color = Tool.goldColor;
                                break;

                            case 4:
                                color = Tool.iridiumColor;
                                break;
                            }
                            b.Draw(Game1.littleEffect, new Microsoft.Xna.Framework.Rectangle((int)Game1.player.getLocalPosition(viewport).X - 2, (int)Game1.player.getLocalPosition(viewport).Y - (Game1.player.CurrentTool.Name.Equals("Watering Can") ? 0 : Game1.tileSize) - 2, (int)(Game1.toolHold % 600f * 0.08f) + 4, Game1.tileSize / 8 + 4), Color.Black);
                            b.Draw(Game1.littleEffect, new Microsoft.Xna.Framework.Rectangle((int)Game1.player.getLocalPosition(viewport).X, (int)Game1.player.getLocalPosition(viewport).Y - (Game1.player.CurrentTool.Name.Equals("Watering Can") ? 0 : Game1.tileSize), (int)(Game1.toolHold % 600f * 0.08f), Game1.tileSize / 8), color);
                        }
                    }
                    if (render.Weather)
                    {
                        if (Game1.isDebrisWeather && loc.IsOutdoors && !loc.ignoreDebrisWeather.Value && !loc.Name.Equals("Desert") && viewport.X > -10)
                        {
                            using (List <WeatherDebris> .Enumerator enumerator4 = Game1.debrisWeather.GetEnumerator())
                            {
                                while (enumerator4.MoveNext())
                                {
                                    enumerator4.Current.draw(b);
                                }
                            }
                        }
                    }
                    if (render.Event)
                    {
                        if (Game1.farmEvent != null)
                        {
                            Game1.farmEvent.draw(b);
                        }
                    }
                    if (render.Lighting)
                    {
                        if (loc.LightLevel > 0f && Game1.timeOfDay < 2000)
                        {
                            b.Draw(Game1.fadeToBlackRect, output.Bounds, Color.Black * loc.LightLevel);
                        }
                        if (Game1.screenGlow)
                        {
                            b.Draw(Game1.fadeToBlackRect, output.Bounds, Game1.screenGlowColor * Game1.screenGlowAlpha);
                        }
                    }
                    if (render.Location)
                    {
                        loc.drawAboveAlwaysFrontLayer(b);
                    }
                    if (render.Player && Game1.currentLocation == loc)
                    {
                        if (Game1.player.CurrentTool != null && Game1.player.CurrentTool is FishingRod && ((Game1.player.CurrentTool as FishingRod).isTimingCast || (Game1.player.CurrentTool as FishingRod).castingChosenCountdown > 0f || (Game1.player.CurrentTool as FishingRod).fishCaught || (Game1.player.CurrentTool as FishingRod).showingTreasure))
                        {
                            Game1.player.CurrentTool.draw(b);
                        }
                    }
                    if (render.Weather)
                    {
                        if (Game1.isRaining && loc.IsOutdoors && !loc.Name.Equals("Desert") && !(loc is Summit) && (!Game1.eventUp || loc.isTileOnMap(new Vector2((float)(viewport.X / Game1.tileSize), (float)(viewport.Y / Game1.tileSize)))))
                        {
                            for (int ix = 0; ix < output.Bounds.Width / oldView.Width * 4; ++ix)
                            {
                                for (int iy = 0; iy < output.Bounds.Height / oldView.Height * 4; ++iy)
                                {
                                    var offset = new Vector2(ix * oldView.Width, iy * oldView.Height);
                                    for (int j = 0; j < Game1.rainDrops.Length; j++)
                                    {
                                        b.Draw(Game1.rainTexture, offset + Game1.rainDrops[j].position, new Microsoft.Xna.Framework.Rectangle?(Game1.getSourceRectForStandardTileSheet(Game1.rainTexture, Game1.rainDrops[j].frame, -1, -1)), Color.White);
                                    }
                                }
                            }
                        }
                    }
                    b.End();
                    begun = false;

                    if (render.Event && Game1.currentLocation == loc)
                    {
                        b.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null, transform);
                        begun = true;
                        if (Game1.eventUp && Game1.currentLocation.currentEvent != null)
                        {
                            foreach (NPC current7 in Game1.currentLocation.currentEvent.actors)
                            {
                                if (current7.isEmoting)
                                {
                                    Vector2 localPosition = current7.getLocalPosition(viewport);
                                    localPosition.Y -= (float)(Game1.tileSize * 2 + Game1.pixelZoom * 3);
                                    if (current7.Age == 2)
                                    {
                                        localPosition.Y += (float)(Game1.tileSize / 2);
                                    }
                                    else if (current7.Gender == 1)
                                    {
                                        localPosition.Y += (float)(Game1.tileSize / 6);
                                    }
                                    b.Draw(Game1.emoteSpriteSheet, localPosition, new Microsoft.Xna.Framework.Rectangle?(new Microsoft.Xna.Framework.Rectangle(current7.CurrentEmoteIndex * (Game1.tileSize / 4) % Game1.emoteSpriteSheet.Width, current7.CurrentEmoteIndex * (Game1.tileSize / 4) / Game1.emoteSpriteSheet.Width * (Game1.tileSize / 4), Game1.tileSize / 4, Game1.tileSize / 4)), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, (float)current7.getStandingY() / 10000f);
                                }
                            }
                        }
                        b.End();
                        begun = false;
                    }

                    if (render.Lighting)
                    {
                        if (Game1.drawLighting)
                        {
                            b.Begin(SpriteSortMode.Deferred, Helper.Reflection.GetField <BlendState>(Game1.game1, "lightingBlend").GetValue(), SamplerState.LinearClamp, null, null, null, transform);
                            begun = true;
                            b.Draw(myLighting, Vector2.Zero, new Microsoft.Xna.Framework.Rectangle?(myLighting.Bounds), Color.White, 0f, Vector2.Zero, (float)(Game1.options.lightingQuality / 2) * 4, SpriteEffects.None, 1f);
                            if (render.Weather && Game1.isRaining && loc.IsOutdoors && !(loc is Desert))
                            {
                                b.Draw(Game1.staminaRect, output.Bounds, Color.OrangeRed * 0.45f);
                            }
                            b.End();
                            begun = false;
                        }
                    }
                }

                // This fixes the saved texture being transparent when there is lighting
                // Not a very CLEAN fix... But it works
                oldOutput = output;
                output    = new RenderTarget2D(dev, oldOutput.Width, oldOutput.Height);
                dev.SetRenderTarget(output);
                dev.Clear(Color.Black);
                b.Begin();
                begun = true;
                b.Draw(oldOutput, new Vector2(0, 0), Color.White);
                b.End();
                begun = false;
                dev.SetRenderTarget(null);

                string name = loc.Name;
                if (loc.uniqueName.Value != null)
                {
                    name = loc.uniqueName.Value;
                }

                string dirPath   = Path.Combine(Constants.ExecutionPath, "MapExport");
                string imagePath = Path.Combine(dirPath, $"{name}.png");
                Log.info($"Saving {name} to {Path.GetFullPath(imagePath)}...");

                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }

                stream = File.Create(imagePath);
                output.SaveAsPng(stream, output.Width, output.Height);
                stream.Dispose();
            }
            catch (Exception e)
            {
                Log.error("Exception: " + e);
            }
            finally
            {
                display.EndScene();
                if (begun)
                {
                    b.End();
                }
                dev.SetRenderTarget(null);
                stream?.Dispose();
                oldOutput?.Dispose();
                output?.Dispose();
                myLighting?.Dispose();
                //Game1.pixelZoom = oldZoom;
                Game1.viewport          = oldView;
                Game1.options.zoomLevel = oldZoomL;
            }

            if (loc is DecoratableLocation location)
            {
                foreach (Furniture f in location.furniture)
                {
                    f.updateDrawPosition();
                }
            }
        }
Example #12
0
            public RenderPipelineWorld(
                IAssetManager assetManager,
                I2DRenderUtilities renderUtilities,
                IGraphicsFactory graphicsFactory,
                IAssert assert,
                ITestAttachment testAttachment,
                IRenderTargetBackBufferUtilities renderTargetBackBufferUtilities,
                IGraphicsBlit graphicsBlit)
            {
                _renderUtilities                 = renderUtilities;
                _assert                          = assert;
                _testAttachment                  = testAttachment;
                _texture                         = assetManager.Get <TextureAsset>("texture.Player");
                _invertPostProcess               = graphicsFactory.CreateInvertPostProcessingRenderPass();
                _blurPostProcess                 = graphicsFactory.CreateBlurPostProcessingRenderPass();
                _customPostProcess               = graphicsFactory.CreateCustomPostProcessingRenderPass("effect.MakeRed");
                _captureInlinePostProcess        = graphicsFactory.CreateCaptureInlinePostProcessingRenderPass();
                _renderTargetBackBufferUtilities = renderTargetBackBufferUtilities;
                _graphicsBlit                    = graphicsBlit;
                _captureInlinePostProcess.RenderPipelineStateAvailable = (gameContext, renderContext, previousPass, d) =>
                {
                    if (!_isValidRun)
                    {
                        return;
                    }

                    _renderTarget = _renderTargetBackBufferUtilities.UpdateCustomRenderTarget(_renderTarget, renderContext, SurfaceFormat.Color, DepthFormat.None, 1);

                    // Blit to the capture target.
                    _graphicsBlit.Blit(renderContext, d, _renderTarget);

#if MANUAL_TEST
#elif RECORDING
                    using (var writer = new StreamWriter("output" + _frame + ".png"))
                    {
                        _renderTarget.SaveAsPng(writer.BaseStream, Width, Height);
                    }
#else
                    var baseStream =
                        typeof(RenderPipelineWorld).Assembly.GetManifestResourceStream(
                            "Protogame.Tests.Expected.RenderPipeline.output" + _frame + ".png");
                    _assert.NotNull(baseStream);
                    var memoryStream = new MemoryStream();
                    _renderTarget.SaveAsPng(memoryStream, Width, Height);
                    // ReSharper disable once AssignNullToNotNullAttribute
                    var expected = new Bitmap(baseStream);
                    var actual   = new Bitmap(memoryStream);

                    _assert.Equal(expected.Height, actual.Height);
                    _assert.Equal(expected.Width, actual.Width);
                    var totalPixelValues     = 0L;
                    var incorrectPixelValues = 0L;
                    for (var x = 0; x < expected.Width; x++)
                    {
                        for (var y = 0; y < expected.Height; y++)
                        {
                            var expectedPixel = expected.GetPixel(x, y);
                            var actualPixel   = actual.GetPixel(x, y);

                            totalPixelValues += 255 * 4;

                            if (expectedPixel != actualPixel)
                            {
                                var diffA = System.Math.Abs((int)actualPixel.A - (int)expectedPixel.A);
                                var diffR = System.Math.Abs((int)actualPixel.R - (int)expectedPixel.R);
                                var diffG = System.Math.Abs((int)actualPixel.G - (int)expectedPixel.G);
                                var diffB = System.Math.Abs((int)actualPixel.B - (int)expectedPixel.B);

                                incorrectPixelValues += (diffA + diffR + diffG + diffB);
                            }
                        }
                    }

                    var percentage = (100 - ((incorrectPixelValues / (double)totalPixelValues) * 100f));

                    var combination = _combinations[_frame % _combinations.Count];
                    _testAttachment.Attach("name-" + combination.Id, combination.Name);
                    _testAttachment.Attach("expected-" + combination.Id, baseStream);
                    _testAttachment.Attach("actual-" + combination.Id, memoryStream);
                    _testAttachment.Attach("threshold-" + combination.Id, 99.9);
                    _testAttachment.Attach("measured-" + combination.Id, percentage);

                    if (percentage <= 99.9f)
                    {
                        combination.FailureMessage = "The actual rendered image did not match the expected image close enough (99.9%).";
                    }

                    //memoryStream.Dispose();
                    //baseStream.Dispose();
#endif

#if MANUAL_TEST
                    _manualTest++;
                    if (_manualTest % 60 == 0)
                    {
                        _frame++;
                    }
#else
                    _frame++;
#endif
                };

                this.Entities = new List <IEntity>();
            }
Example #13
0
 private void ScreenshotThread()
 {
     using (var stream = System.IO.File.OpenWrite(DateTime.Now.Ticks.ToString() + ".png"))
         rawScreen.SaveAsPng(stream, Kafe.ScreenWidth, Kafe.ScreenHeight);
 }
        /// <summary>
        /// Saves the render target contained as a .png file
        /// in the output folder for the game.
        /// </summary>
        /// <param name="name">The name to give the saved image.</param>
        public void Save(string name)
        {
            Stream stream = new FileStream(name + ".png", FileMode.OpenOrCreate, FileAccess.ReadWrite);

            renderTarget.SaveAsPng(stream, (int)Common.ScreenResolution.X, (int)Common.ScreenResolution.Y);
        }
Example #15
0
        /// <summary>
        /// Method designed for Stage texture loading.
        /// </summary>
        /// <param name="texturePointer">Absolute pointer to TIM texture header in stageBuffer</param>
        private void ReadTexture(uint texturePointer, BinaryReader br)
        {
            TIM2 textureInterface = new TIM2(br, texturePointer);

            if (Memory.EnableDumpingData || EnableDumpingData)
            {
                IEnumerable <Model> temp = (from mg in modelGroups
                                            from m in mg
                                            select m).Where(x => x.vertices != null && x.triangles != null && x.quads != null);
                //IOrderedEnumerable<byte> cluts = temp.SelectMany(x => x.quads.Select(y => y.clut)).Union(temp.SelectMany(x => x.triangles.Select(y => y.clut))).Distinct().OrderBy(x => x);
                //IOrderedEnumerable<byte> unks = temp.SelectMany(x => x.quads.Select(y => y.UNK)).Union(temp.SelectMany(x => x.triangles.Select(y => y.UNK))).Distinct().OrderBy(x => x);
                //IOrderedEnumerable<byte> hides = temp.SelectMany(x => x.quads.Select(y => y.bHide)).Union(temp.SelectMany(x => x.triangles.Select(y => y.bHide))).Distinct().OrderBy(x => x);
                //IOrderedEnumerable<byte> gpu = temp.SelectMany(x => x.quads.Select(y => y.GPU)).Union(temp.SelectMany(x => x.triangles.Select(y => y.GPU))).Distinct().OrderBy(x => x);
                //IOrderedEnumerable<Color> color = temp.SelectMany(x => x.quads.Select(y => y.Color)).Union(temp.SelectMany(x => x.triangles.Select(y => y.Color))).Distinct().OrderBy(x => x.R).ThenBy(x => x.G).ThenBy(x => x.B);
                var tuv = (from m in temp
                           where m.triangles != null && m.triangles.Length > 0
                           from t in m.triangles
                           where t != null
                           select new { t.clut, t.TexturePage, t.MinUV, t.MaxUV, t.Rectangle }).Distinct().OrderBy(x => x.TexturePage).ThenBy(x => x.clut).ToList();
                var quv = (from m in temp
                           where m.quads != null && m.quads.Length > 0
                           from q in m.quads
                           where q != null
                           select new { q.clut, q.TexturePage, q.MinUV, q.MaxUV, q.Rectangle }).Distinct().OrderBy(x => x.TexturePage).ThenBy(x => x.clut) /*.Where(x => x.Rectangle.Height > 0 && x.Rectangle.Width > 0)*/.ToList();
                var all = tuv.Union(quv);
                foreach (var tpGroup in all.GroupBy(x => x.TexturePage))
                {
                    byte texturepage = tpGroup.Key;
                    foreach (var clutGroup in tpGroup.GroupBy(x => x.clut))
                    {
                        byte   clut     = clutGroup.Key;
                        string filename = Path.GetFileNameWithoutExtension(Memory.Encounters.Filename);
                        string p        = Path.Combine(Path.GetTempPath(), "Battle Stages", filename, "Reference");
                        Directory.CreateDirectory(p);
                        filename = $"{filename}_{clut}_{texturepage}.png";
                        using (Texture2D tex = textureInterface.GetTexture(clut))
                            using (RenderTarget2D tmp = new RenderTarget2D(Memory.graphics.GraphicsDevice, 256, 256))
                            {
                                Memory.graphics.GraphicsDevice.SetRenderTarget(tmp);
                                Memory.SpriteBatchStartAlpha();
                                Memory.graphics.GraphicsDevice.Clear(Color.TransparentBlack);
                                foreach (Rectangle r in clutGroup.Select(x => x.Rectangle))
                                {
                                    Rectangle src = r;
                                    Rectangle dst = r;
                                    src.Offset(texturepage * 128, 0);
                                    Memory.spriteBatch.Draw(tex, dst, src, Color.White);
                                }
                                Memory.SpriteBatchEnd();
                                Memory.graphics.GraphicsDevice.SetRenderTarget(null);
                                using (FileStream fs = new FileStream(Path.Combine(p, filename), FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                                    tmp.SaveAsPng(fs, 256, 256);
                            }
                    }
                }
            }
            Width  = textureInterface.GetWidth;
            Height = textureInterface.GetHeight;
            string path = Path.Combine(Path.GetTempPath(), "Battle Stages", Path.GetFileNameWithoutExtension(Memory.Encounters.Filename));

            Directory.CreateDirectory(path);

            if (Memory.EnableDumpingData || EnableDumpingData)
            {
                string fullpath = Path.Combine(path, $"{Path.GetFileNameWithoutExtension(Memory.Encounters.Filename)}_Clut.png");
                if (!File.Exists(fullpath))
                {
                    textureInterface.SaveCLUT(fullpath);
                }
            }

            textures = new TextureHandler[textureInterface.GetClutCount];
            for (ushort i = 0; i < textureInterface.GetClutCount; i++)
            {
                textures[i] = TextureHandler.Create(Memory.Encounters.Filename, textureInterface, i);
                if (Memory.EnableDumpingData || EnableDumpingData)
                {
                    textures[i].Save(path, false);
                }
            }
        }
Example #16
0
 /// <summary>
 /// Saves a PNG file of the surface.
 /// </summary>
 public void Save(string Path)
 {
     _target.SaveAsPng(new FileStream(Path, FileMode.Create), Width, Height);
 }
Example #17
0
        public static void CreateandSaveFloorMapImage(bool[,] FloorMap, Vector2 MapSize, int Version, List <Room> Rooms)
        {
            RenderTarget2D Target  = new RenderTarget2D(ScreenManager.Instance.GraphicsDevice, (int)MapSize.X * 8, (int)MapSize.Y * 8);
            ContentManager content = new ContentManager(ScreenManager.Instance.Content.ServiceProvider, "Content");


            ScreenManager.Instance.GraphicsDevice.SetRenderTarget(Target);
            ScreenManager.Instance.GraphicsDevice.Clear(Color.Transparent);
            ScreenManager.Instance.SpriteBatch.Begin();

            Texture2D Floor = content.Load <Texture2D>(FloorPath);
            Texture2D Void  = content.Load <Texture2D>(VoidPath);


            for (int X = 0; X < MapSize.X; X++)
            {
                for (int Y = 0; Y < MapSize.Y; Y++)
                {
                    if (FloorMap[X, Y])
                    {
                        ScreenManager.Instance.SpriteBatch.Draw(Floor, new Rectangle(X * 8, Y * 8, 8, 8), Color.White);
                    }
                    else
                    {
                        ScreenManager.Instance.SpriteBatch.Draw(Void, new Rectangle(X * 8, Y * 8, 8, 8), Color.White);
                    }
                }
            }

            int EntryRoom  = -1;
            int BossRoom   = -1;
            int StairsRoom = -1;

            for (int I = 0; I < Rooms.Count; I++)
            {
                if (Rooms[I].Purpose == "Entry")
                {
                    EntryRoom = I;
                }
                else if (Rooms[I].Purpose == "Stairs")
                {
                    StairsRoom = I;
                }
                else if (Rooms[I].Purpose == "Boss")
                {
                    BossRoom = I;
                }
            }

            if (EntryRoom >= 0)
            {
                Texture2D Entry = content.Load <Texture2D>(EntryPath);
                for (int X = Rooms[EntryRoom].Location.X; X < Rooms[EntryRoom].Location.Right; X++)
                {
                    for (int Y = Rooms[EntryRoom].Location.Y; Y < Rooms[EntryRoom].Location.Bottom; Y++)
                    {
                        ScreenManager.Instance.SpriteBatch.Draw(Entry, new Rectangle(X * 8, Y * 8, 8, 8), Color.White);
                    }
                }
            }
            if (BossRoom >= 0)
            {
                Texture2D Boss = content.Load <Texture2D>(BossPath);
                for (int X = Rooms[BossRoom].Location.X; X < Rooms[BossRoom].Location.Right; X++)
                {
                    for (int Y = Rooms[BossRoom].Location.Y; Y < Rooms[BossRoom].Location.Bottom; Y++)
                    {
                        ScreenManager.Instance.SpriteBatch.Draw(Boss, new Rectangle(X * 8, Y * 8, 8, 8), Color.White);
                    }
                }
            }
            if (StairsRoom >= 0)
            {
                Texture2D Stairs = content.Load <Texture2D>(StairsPath);
                for (int X = Rooms[StairsRoom].Location.X; X < Rooms[StairsRoom].Location.Right; X++)
                {
                    for (int Y = Rooms[StairsRoom].Location.Y; Y < Rooms[StairsRoom].Location.Bottom; Y++)
                    {
                        ScreenManager.Instance.SpriteBatch.Draw(Stairs, new Rectangle(X * 8, Y * 8, 8, 8), Color.White);
                    }
                }
            }



            ScreenManager.Instance.SpriteBatch.End();



            var ImageStream = new FileStream("Content/Dungeon Imaging/Output/Map_" + Version + "_FloorPlan.png", FileMode.Create);


            Target.SaveAsPng(ImageStream, Target.Width, Target.Height);

            ImageStream.Close();


            ScreenManager.Instance.GraphicsDevice.SetRenderTarget(null);
            content.Unload();
        }
Example #18
0
        /**
         * Saves a png to disk containing the whole animation sprite sheet, where the sprites
         * are orderd according to their column values.
         */
        public void GetAnimationSheet()
        {
            SerializableDictionary <string, int> stripeColumns = FolderSettings.Instance.StripeColumn;

            // Sort columns and get size of the needed render target.
            List <KeyValuePair <string, int> > columnPairs = new List <KeyValuePair <string, int> >();
            int targetWidth  = 0;
            int targetHeight = 0;

            foreach (var pair in stripeColumns)
            {
                columnPairs.Add(pair);

                Texture2D texture = LoadedTextures[pair.Key];
                targetHeight += texture.Height;
                if (targetWidth < texture.Width)
                {
                    targetWidth = texture.Width;
                }
            }
            columnPairs.Sort((A, B) =>
            {
                if (B.Value > A.Value)
                {
                    return(-1);
                }
                else
                {
                    return(1);
                }
            }
                             );

            // Set up a render target to write the images on.
            RenderTarget2D renderTarget = new RenderTarget2D(GraphicsDevice, targetWidth, targetHeight);

            GraphicsDevice.SetRenderTarget(renderTarget);
            GraphicsDevice.Clear(Color.Transparent);
            _spriteBatch.Begin();

            // Draw images to render target.
            int startHeight = 0;

            foreach (var pair in columnPairs)
            {
                Texture2D stripe = LoadedTextures[pair.Key];
                _spriteBatch.Draw(stripe, new Vector2(0, startHeight), Color.White);
                startHeight += stripe.Height;
            }

            _spriteBatch.End();

            GraphicsDevice.SetRenderTarget(null);

            // Save render target to disk.
            string path = System.Windows.Forms.Application.StartupPath + "\\AnimationSheets\\";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            using (Stream stream = File.OpenWrite(path + DateTime.Now.ToString("dd-mm-yy_HH-mm-ss") + ".png"))
            {
                if (stream != null)
                {
                    renderTarget.SaveAsPng(stream, renderTarget.Width, renderTarget.Height);
                    stream.Close();
                }
            }

            renderTarget.Dispose();
            renderTarget = null;
        }
Example #19
0
        public void Draw(Renderer2D renderer, Matrix cam, Rectangle areaOfInfluence)
        {
            renderTarget?.Dispose();
            renderTarget     = new RenderTarget2D(renderer.GraphicsDevice, areaOfInfluence.Width, areaOfInfluence.Height);
            oldRenderTargets = renderer.GraphicsDevice.GetRenderTargets();
            renderer.GraphicsDevice.SetRenderTarget(null);
            renderer.GraphicsDevice.SetRenderTarget(renderTarget);
            renderer.GraphicsDevice.Clear(Color.TransparentBlack);

            renderer.End();
            renderer.Begin();
            int x;
            int y;

            int[]     data;
            TileSet   tileSet;
            int       actualData;
            Rectangle sourceRectangle;

            foreach (var layer in map.Layers)
            {
                data = layer.GetRawData();

                for (int i = 0; i < data.Length; i++)
                {
                    if (data[i] == 0)
                    {
                        continue;
                    }
                    x = 16 * (i % map.TileSize.X);
                    y = 16 * (i / map.TileSize.X);
                    if (x + 16 < areaOfInfluence.X || y + 16 < areaOfInfluence.Y ||
                        x - 16 > areaOfInfluence.Right || y - 16 > areaOfInfluence.Bottom)
                    {
                        continue;
                    }

                    tileSet = tileSetsShadow.TileSets.FirstOrDefault(t => t.Name == tileSetsMap.IndexToTileSet(data[i]).Name + "_shadow");

                    if (tileSet == null)
                    {
                        continue;
                    }


                    actualData = tileSetsMap.ShortenIndex(data[i]) + 1;
                    if (tileSetsMap.IsAnimation(data[i]))
                    {
                        var tile = animatedTileLightings.FirstOrDefault(t => t.Index == new DataTypes.Index2((i % map.TileSize.X), (i / map.TileSize.X)));
                        renderer.Draw(tile.Current(), new Rectangle(x - areaOfInfluence.X, y - areaOfInfluence.Y, 16, 16), Color.White);
                        continue;
                    }
                    sourceRectangle = tileSetsShadow.GetSourceRectangle(actualData);

                    renderer.Draw(tileSet.Texture, new Rectangle(x - areaOfInfluence.X, y - areaOfInfluence.Y, 16, 16), sourceRectangle, Color.White);                     //16  //
                }
            }
            renderer.End();
            renderer.GraphicsDevice.SetRenderTarget(null);
            renderer.GraphicsDevice.SetRenderTargets(oldRenderTargets);
            renderer.Begin(cam);
            using (FileStream fs = new FileStream("obstacles.png", FileMode.Create))
                renderTarget.SaveAsPng(fs, renderTarget.Width, renderTarget.Height);
        }
Example #20
0
        public async void SaveScreenshot(ClipboardContents clipboard = ClipboardContents.URL, bool openURL = false)
        {
            int shotNumber = 0;

            Directory.CreateDirectory("Screenshots");
            string path = Path.Combine(Application.StartupPath, "Screenshots", "photovs_screenshot_" + shotNumber.ToString().PadLeft(3, '0') + ".png");

            while (File.Exists(path))
            {
                shotNumber++;
                path = Path.Combine(Application.StartupPath, "Screenshots", "photovs_screenshot_" + shotNumber.ToString().PadLeft(3, '0') + ".png");
            }

            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                Console.WriteLine("Copied to clipboard and saved screenshot to ", path);
                renderTarget2.SaveAsPng(fs, GAME_WIDTH, GAME_HEIGHT);
            }

            using (MemoryStream mem = new MemoryStream())
            {
                // save game screenshot to memory
                renderTarget2.SaveAsPng(mem, GAME_WIDTH, GAME_HEIGHT);

                using (var w = new WebClient())
                {
                    // upload to Imgur
                    // oh yeah, you all can see this too. oh well.
                    string clientID = "36e2260c96b7e67";
                    w.Headers.Add("Authorization", "Client-ID " + clientID);
                    var values = new NameValueCollection
                    {
                        { "image", Convert.ToBase64String(mem.GetBuffer()) }
                    };

                    byte[] response = w.UploadValues("https://api.imgur.com/3/upload.xml", values);

                    // parse through XML and get a link back
                    using (MemoryStream res = new MemoryStream(response))
                    {
                        var xml  = XDocument.Load(res);
                        var data = xml.Descendants("data");

                        foreach (var d in data)
                        {
                            var val = d.Element("link").Value;

                            if (clipboard == ClipboardContents.Image)
                            {
                                Clipboard.SetImage(System.Drawing.Image.FromFile(path));
                            }
                            else
                            {
                                Clipboard.SetText(val);
                            }

                            Console.WriteLine($"Screenshot uploaded to {val}");

                            // send to discord
                            using (WebClient client = new WebClient())
                            {
                                HttpResponseMessage resp = await new HttpClient().PostAsync("https://discordapp.com/api/webhooks/482641656361910272/ZKZfPujN8SfUBznuwqLUu_HJ2o-58ws_r5Whd3bcOalT2woGmjMTYAbwK7zuqFXY0rIl",
                                                                                            new StringContent("{\"embeds\":[{\"image\":{\"url\":\"" + val + "\"}}]}", Encoding.UTF8, "application/json"));
                                //Console.WriteLine(resp.ToString());
                                Console.WriteLine("Screenshot posted in PhotoVs Discord");
                            }

                            if (openURL)
                            {
                                try
                                {
                                    Process.Start(val);
                                }
                                catch (System.ComponentModel.Win32Exception)
                                {
                                    Process.Start("IExplore.exe", val);
                                }
                            }
                        }
                    }
                }
            }
        }
Example #21
0
        /// <summary>
        /// Handle the behaviour of the listener when the user load a saved game or
        /// save the current game.
        /// </summary>
        /// <param name="producedEvent"><c>IEventData</c> that contains the produced event.</param>
        /// <returns>True if the event has been processed and false otherwise.</returns>
        public bool HandleEvent(IEventData producedEvent)
        {
            if (producedEvent is EventData_SaveGame)
            {
                SavedGame savedGame = new SavedGame();

                savedGame.Date              = DateTime.Now.ToString();
                savedGame.MapName           = ((EventData_SaveGame)producedEvent).MapName;
                savedGame.Percent           = 0.5f;
                savedGame.CapturedImage     = null;
                savedGame.PlayerName        = ((EventData_SaveGame)producedEvent).Player.DModel.Model.FileName;
                savedGame.PlayerPosition    = ((EventData_SaveGame)producedEvent).Player.Position;
                savedGame.PlayerRotation    = ((EventData_SaveGame)producedEvent).Player.Rotation;
                savedGame.PlayerScale       = ((EventData_SaveGame)producedEvent).Player.Scale;
                savedGame.PlayerMaxSpeed    = ((EventData_SaveGame)producedEvent).Player.MaxSpeed;
                savedGame.PlayerCurrentLife = ((EventData_SaveGame)producedEvent).Player.Life;
                savedGame.PlayerMaxLife     = ((EventData_SaveGame)producedEvent).Player.MaxLife;
                savedGame.Debolio           = ((Player)((EventData_SaveGame)producedEvent).Player).Debolio;
                savedGame.Aerogel           = ((Player)((EventData_SaveGame)producedEvent).Player).Aerogel;
                savedGame.Fulereno          = ((Player)((EventData_SaveGame)producedEvent).Player).Fulereno;
                savedGame.TotalPoints       = ((Player)((EventData_SaveGame)producedEvent).Player).TotalPoints;

                savedGame.PlayerNumberOfObjects         = ((Player)((EventData_SaveGame)producedEvent).Player).Objects.Count;
                savedGame.PlayerObjectType              = new List <string>();
                savedGame.PlayerObjectName              = new List <string>();
                savedGame.PlayerObjectTextureName       = new List <string>();
                savedGame.PlayerObjectPosition          = new List <int>();
                savedGame.PlayerObjectEquipped          = new List <bool>();
                savedGame.PlayerObjectWeaponCurrentAmmo = new List <int>();
                savedGame.PlayerObjectWeaponTotalAmmo   = new List <int>();
                savedGame.PlayerObjectWeaponPower       = new List <int>();
                savedGame.PlayerObjectWeaponType        = new List <Objects.Gun.ShotType>();
                savedGame.PlayerObjectArmatureSkill     = new List <int>();
                savedGame.PlayerObjectArmatureDefense   = new List <int>();
                savedGame.PlayerObjectArmatureType      = new List <Armature.ArmatureType>();
                savedGame.PlayerObjectAmmoAmount        = new List <int>();
                savedGame.PlayerObjectAmmoType          = new List <Objects.Gun.ShotType>();
                foreach (Objects.Object playerObject in ((Player)((EventData_SaveGame)producedEvent).Player).Objects)
                {
                    savedGame.PlayerObjectName.Add(playerObject.Name);
                    savedGame.PlayerObjectTextureName.Add(playerObject.TextureName);
                    savedGame.PlayerObjectPosition.Add(playerObject.Position);
                    savedGame.PlayerObjectEquipped.Add(playerObject.IsEquipped);
                    if (playerObject is Armature)
                    {
                        savedGame.PlayerObjectType.Add("Armature");
                        savedGame.PlayerObjectArmatureSkill.Add(((Armature)playerObject).Skill);
                        savedGame.PlayerObjectArmatureDefense.Add(((Armature)playerObject).Defense);
                        savedGame.PlayerObjectArmatureType.Add(((Armature)playerObject).Type);
                    }
                    else if (playerObject is Weapon)
                    {
                        savedGame.PlayerObjectType.Add("Weapon");
                        savedGame.PlayerObjectWeaponCurrentAmmo.Add(((Weapon)playerObject).CurrentAmmo);
                        savedGame.PlayerObjectWeaponTotalAmmo.Add(((Weapon)playerObject).TotalAmmo);
                        savedGame.PlayerObjectWeaponPower.Add(((Weapon)playerObject).Power);
                        savedGame.PlayerObjectWeaponType.Add(((Weapon)playerObject).Type);
                    }
                    else if (playerObject is Ammo)
                    {
                        savedGame.PlayerObjectType.Add("Ammo");
                        savedGame.PlayerObjectAmmoAmount.Add(((Ammo)playerObject).Amount);
                        savedGame.PlayerObjectAmmoType.Add(((Ammo)playerObject).Type);
                    }
                    else
                    {
                        savedGame.PlayerObjectType.Add("Object");
                    }
                }

                savedGame.NumberOfEnemies = ((EventData_SaveGame)producedEvent).Enemies.Length;
                savedGame.EnemyName       = new List <string>();
                savedGame.EnemyPosition   = new List <Vector3>();
                savedGame.EnemyRotation   = new List <Vector3>();
                savedGame.EnemyScale      = new List <Vector3>();
                savedGame.EnemyMaxSpeed   = new List <Vector2>();
                savedGame.EnemyLife       = new List <int>();
                savedGame.EnemyMaxLife    = new List <int>();
                savedGame.EnemyAttack     = new List <int>();
                foreach (Objects.Enemy enemy in ((EventData_SaveGame)producedEvent).Enemies)
                {
                    savedGame.EnemyName.Add(enemy.DModel.Model.FileName);
                    savedGame.EnemyPosition.Add(enemy.Position);
                    savedGame.EnemyRotation.Add(enemy.Rotation);
                    savedGame.EnemyScale.Add(enemy.Scale);
                    savedGame.EnemyMaxSpeed.Add(enemy.MaxSpeed);
                    savedGame.EnemyLife.Add(enemy.Life);
                    savedGame.EnemyMaxLife.Add(enemy.MaxLife);
                    savedGame.EnemyAttack.Add(enemy.Attack);
                }

                DateTime dateTime = DateTime.Now;
                FileHelper.WriteSavedGame("MetalSpace " + dateTime.Year +
                                          (dateTime.Month.ToString().Length == 1 ? "0" + dateTime.Month.ToString() : dateTime.Month.ToString()) +
                                          (dateTime.Day.ToString().Length == 1 ? "0" + dateTime.Day.ToString() : dateTime.Day.ToString()) + " " +
                                          (dateTime.Hour.ToString().Length == 1 ? "0" + dateTime.Hour.ToString() : dateTime.Hour.ToString()) +
                                          (dateTime.Minute.ToString().Length == 1 ? "0" + dateTime.Minute.ToString() : dateTime.Minute.ToString()) +
                                          (dateTime.Second.ToString().Length == 1 ? "0" + dateTime.Second.ToString() : dateTime.Second.ToString()) +
                                          ".xml", savedGame);

                PresentationParameters parametros = EngineManager.GameGraphicsDevice.PresentationParameters;

                RenderTarget2D datosTextura = new RenderTarget2D(EngineManager.GameGraphicsDevice,
                                                                 256, 256, true, SurfaceFormat.Bgr565, DepthFormat.Depth24);

                EngineManager.GameGraphicsDevice.SetRenderTarget(datosTextura);
                ScreenManager.GetScreen("ContinueGame").Draw(new GameTime());
                EngineManager.GameGraphicsDevice.SetRenderTarget(null);

                datosTextura.SaveAsPng(FileHelper.SaveGameContentFile("MetalSpace " + dateTime.Year +
                                                                      (dateTime.Month.ToString().Length == 1 ? "0" + dateTime.Month.ToString() : dateTime.Month.ToString()) +
                                                                      (dateTime.Day.ToString().Length == 1 ? "0" + dateTime.Day.ToString() : dateTime.Day.ToString()) + " " +
                                                                      (dateTime.Hour.ToString().Length == 1 ? "0" + dateTime.Hour.ToString() : dateTime.Hour.ToString()) +
                                                                      (dateTime.Minute.ToString().Length == 1 ? "0" + dateTime.Minute.ToString() : dateTime.Minute.ToString()) +
                                                                      (dateTime.Second.ToString().Length == 1 ? "0" + dateTime.Second.ToString() : dateTime.Second.ToString()) +
                                                                      ".png"), 256, 256);

                return(true);
            }
            else if (producedEvent is EventData_LoadSavedGame)
            {
                if (ScreenManager.GetScreen("LoadGames") != null)
                {
                    ScreenManager.RemoveScreen("Background");
                    ScreenManager.RemoveScreen("MainMenu");
                    ScreenManager.RemoveScreen("LoadGames");

                    SavedGame savedGame = FileHelper.ReadSavedGame(((EventData_LoadSavedGame)producedEvent).Filename);

                    ScreenManager.AddScreen("LoadingScreen", new LoadingGame(savedGame.MapName, true, savedGame));

                    return(true);
                }

                if (ScreenManager.GetScreen("MainMenu") != null)
                {
                    ScreenManager.RemoveScreen("Background");
                    ScreenManager.RemoveScreen("MainMenu");

                    if (((EventData_LoadSavedGame)producedEvent).Filename != null)
                    {
                        SavedGame savedGame = FileHelper.ReadSavedGame(((EventData_LoadSavedGame)producedEvent).Filename);
                        ScreenManager.AddScreen("LoadingScreen", new LoadingGame(savedGame.MapName, true, savedGame));
                    }
                    else
                    {
                        ScreenManager.AddScreen("LoadingScreen", new LoadingGame("Map_1_2.txt", true, null));
                    }

                    return(true);
                }

                if (ScreenManager.GetScreen("ContinueGame") != null)
                {
                    ScreenManager.RemoveScreen("ContinueGame");

                    if (((EventData_LoadSavedGame)producedEvent).Filename != null)
                    {
                        SavedGame savedGame = FileHelper.ReadSavedGame(((EventData_LoadSavedGame)producedEvent).Filename);
                        ScreenManager.AddScreen("LoadingScreen", new ChangingGame(savedGame.MapName, savedGame));
                    }
                    else
                    {
                        ScreenManager.AddScreen("LoadingScreen", new ChangingGame("Map_1_2.txt", null));
                    }

                    return(true);
                }
            }

            return(false);
        }
Example #22
0
 public void SaveCap(System.IO.Stream stream)
 {
     masterRenderingTarget.SaveAsPng(stream, masterRenderingTarget.Width, masterRenderingTarget.Height);
 }
Example #23
0
    internal static int Main(string[] args)
    {
        int argCount = args.Length;

        string sourceFile       = string.Empty;
        string outputDirectory  = string.Empty;
        string contentDirectory = @".\";
        int    thumbnailSize    = 512;

        print(" Troya Engine - Thumbnail Utility v" + AssemblyInfo.Version);

        if (argCount > 1)
        {
            for (int i = 0; i < argCount; i++)
            {
                string arg = args[i];
                string val = string.Empty;

                if (i + 1 < argCount)
                {
                    val = args[i + 1];
                }

                switch (arg)
                {
                // Input XNB file:
                case "/xnb":
                    if (val.EndsWith(".xnb"))
                    {
                        if (File.Exists(val))
                        {
                            sourceFile = Path.GetFullPath(val);
                        }
                        else
                        {
                            print("Error: File does not exists! " + val, true);
                            return(MSG_ERROR);
                        }
                    }
                    else
                    {
                        print("Error: File format does not supported! Supported format is: *.xnb", true);
                        return(MSG_ERROR);
                    }
                    break;

                case "/content":
                    contentDirectory = val;
                    break;

                // Thumbnail size:
                case "/size":
                    int.TryParse(val, out thumbnailSize);

                    if (thumbnailSize > 2048)
                    {
                        thumbnailSize = 2048;
                    }
                    else if (thumbnailSize < 32)
                    {
                        thumbnailSize = 32;
                    }
                    break;

                // Output directory:
                case "/out":
                    string dirPath = Path.GetFullPath(val);

                    if (!Directory.Exists(dirPath))
                    {
                        Directory.CreateDirectory(dirPath);
                    }

                    outputDirectory = dirPath;
                    break;
                }
            }

            if (!string.IsNullOrEmpty(sourceFile))
            {
                string outputFile = (Path.GetFileNameWithoutExtension(sourceFile) + ".png");

                if (string.IsNullOrEmpty(outputDirectory))
                {
                    string filePath = Path.GetFullPath(sourceFile);
                    string fileName = Path.GetFileName(sourceFile);
                    string path     = filePath.Replace(fileName, string.Empty);

                    outputDirectory = Path.GetFullPath(path);
                }

                print(" Size: " + thumbnailSize.ToString( ) + " x " + thumbnailSize.ToString( ));
                print(" Source File: " + sourceFile);
                print(" Output File: " + outputFile);
                print(" Destination: " + outputDirectory);

                try {
                    Renderer       renderer = new Renderer(thumbnailSize, thumbnailSize);
                    RenderTarget2D target   = renderer.RenderToTarget2D(contentDirectory, sourceFile);

                    target.SaveAsPng(File.Create(Path.Combine(outputDirectory, outputFile)), thumbnailSize, thumbnailSize);
                } catch (Exception ex) {
                    print(ex.Message, true);
                    return(MSG_ERROR);
                }

                print("Thumbnail created!\r\n");
                return(MSG_SUCCESS);
            }
            else
            {
                print("Error: Missing arguments. Check README.txt\r\n", true);
                return(MSG_ERROR);
            }
        }

        return(MSG_NOP);
    }
Example #24
0
        protected override void Draw(GameTime gameTime)
        {
            if (Keyboard.GetState().IsKeyDown(Keys.F2) && Keyboard.GetState().IsKeyDown(Keys.F3) && cycling == false)
            {
                cycling = true;
            }
            if (cycling)
            {
                GameResources.loopcolor();
            }
            Window.Title = "Rizumu: " + GameResources.selected.Substring(14);
            KeyboardState oldstate = kstate;

            kstate = Keyboard.GetState();
            if (kstate.IsKeyDown(Keys.F12) && !oldstate.IsKeyDown(Keys.F12))
            {
                rt = new RenderTarget2D(GraphicsDevice, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight, false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8);
                GraphicsDevice.SetRenderTarget(rt);
                stream  = new FileStream("screenshots/screenshot" + DateTime.Now.Ticks + ".png", FileMode.Create, FileAccess.Write, FileShare.None);
                pressed = true;
            }
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin();

            if (GameResources.GameScreen == 0)
            {
                GameScreens.MainMenu.draw(spriteBatch);
            }
            if (GameResources.GameScreen == 1)
            {
                GameScreens.SongList.draw(spriteBatch);
            }
            if (GameResources.GameScreen == 2)
            {
                GameScreens.MapScreen.draw(spriteBatch, gameTime);
            }
            if (GameResources.GameScreen == 3)
            {
                GameScreens.Score.draw(spriteBatch);
            }
            if (GameResources.GameScreen == 4)
            {
                GameScreens.Options.draw(spriteBatch);
            }
            if (GameResources.GameScreen == 5)
            {
                GameScreens.Keybinds.draw(spriteBatch);
            }
            if (GameResources.GameScreen == 6)
            {
                GameScreens.Offset.draw(spriteBatch);
            }

            // Cursor!
            mstate    = Mouse.GetState();
            cursorbox = new Rectangle(mstate.X + GameResources.Cursor.Width / 2, mstate.Y + GameResources.Cursor.Height / 2, 1, 1);
            cursor    = new Sprite(spriteBatch, mstate.X, mstate.Y, GameResources.Cursor, GameResources.basecolor);
            if (GameResources.showcursor)
            {
                cursor.draw();
            }

            Text.draw(GameResources.debug, "Github Build", 0, graphics.PreferredBackBufferHeight - 20, spriteBatch);

            int ci = 0;

            while (ci < GameResources.comments.Count)
            {
                string[] s    = GameResources.comments[ci];
                string   text = s[0];
                int      x    = int.Parse(s[1]);
                int      y    = int.Parse(s[2]);
                Text.draw(GameResources.font, text, x, y, spriteBatch);
                x = x + 10;
                GameResources.comments[ci] = new string[] { text, x.ToString(), y.ToString() };
                ci++;
            }

            spriteBatch.End();
            if (pressed)
            {
                rt.SaveAsPng(stream, 1080, 720);
                stream.Close();
                GraphicsDevice.SetRenderTarget(null);
                pressed = false;
            }
            if (Keyboard.GetState().IsKeyDown(Keys.F5))
            {
                GameResources.GameScreen = 5;
            }
            if (Keyboard.GetState().IsKeyDown(Keys.F6) && GameResources.GameScreen == 5)
            {
                GameResources.GameScreen = 0;
            }

            base.Draw(gameTime);
        }
Example #25
0
        public void ExportPhysicsPathsToPNG(string path)
        {
            List <PhysicsPath> physObjects = Editor.Instance.PhysicObjects;

            // Get extent first.
            foreach (PhysicsPath physicObject in physObjects)
            {
                physicObject.SetExtent();
            }
            Vector2 topLeft     = Editor.Instance.PhysicsExtentTopLeft;
            Vector2 bottomRight = Editor.Instance.PhysicsExtentBottomRight;

            // Set up render target.
            int pictureWidth  = (int)bottomRight.X - (int)topLeft.X;
            int pictureHeight = (int)bottomRight.Y - (int)topLeft.Y;
            int tileIdx       = 0;

            // Save the physics paths as 4096x4096 png tiles
            while (pictureWidth > 0)
            {
                int renderWidth  = Math.Min(4096, pictureWidth);
                int renderHeight = Math.Min(4096, pictureHeight);
                pictureWidth -= renderWidth;

                RenderTarget2D renderTarget = new RenderTarget2D(GraphicsDevice, renderWidth, renderHeight);

                GraphicsDevice.SetRenderTarget(renderTarget);
                GraphicsDevice.Clear(Color.Transparent);

                // Draw polygons to render target;
                spriteBatch.Begin();
                for (int i = 0; i < physObjects.Count; i++)
                {
                    // Zero out polygons so they fit into render target.
                    var curObject = (PhysicsPath)physObjects[i].clone();
                    curObject.setPosition(curObject.Position - topLeft);

                    Primitives.Instance.drawPolygon(spriteBatch, curObject.WorldPoints, Color.Black, 1);
                }
                spriteBatch.End();

                GraphicsDevice.SetRenderTarget(null);

                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }

                using (System.IO.Stream stream = System.IO.File.OpenWrite(path + "\\" + DateTime.Now.ToString("dd-mm-yy_HH-mm-ss") + "_" + tileIdx.ToString() + ".png"))
                {
                    if (stream != null)
                    {
                        renderTarget.SaveAsPng(stream, renderTarget.Width, renderTarget.Height);
                        stream.Close();
                    }
                }

                // update top left corner.
                topLeft.X += renderWidth;

                renderTarget.Dispose();
                renderTarget = null;
                tileIdx++;
            }
        }
Example #26
0
 public void SaveScreenshot(Stream stream)
 {
     FinalRender.SaveAsPng(stream, FinalRender.Width, FinalRender.Height);
 }
Example #27
0
        /// <summary>
        /// Used to load the tree texture by batching together the textures from XNB into a custom render target
        /// </summary>
        private void loadTreeTexture()
        {
            // the list of seasons
            var seasons = new[] { "spring", "summer", "fall", "winter" };

            // create a render target to prepare the tree texture to
            var texture = new RenderTarget2D(Game1.graphics.GraphicsDevice, 144, 96 * seasons.Length);

            // set the render target and clear the buffer
            Game1.graphics.GraphicsDevice.SetRenderTarget(texture);
            Game1.graphics.GraphicsDevice.Clear(Color.Transparent);

            // begin drawing session
            Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null);

            for (int s = 0; s < seasons.Length; s++)
            {
                // loop through the three trees in the game
                for (int i = 0; i < 3; i++)
                {
                    // get the current season
                    string season = seasons[s];

                    // spring and summer share the same texture for the pine tree
                    if (i == 2 && season.Equals("summer"))
                    {
                        season = "spring";
                    }

                    // load the texture into memory
                    string treeString = $"TerrainFeatures\\tree{i + 1}_{season}";

                    // get the current tree's texture
                    Texture2D currentTreeTexture = Game1.content.Load <Texture2D>(treeString);

                    // draw the trunk of the tree
                    Game1.spriteBatch.Draw(
                        currentTreeTexture,
                        new Vector2((48 * i) + 16, (96 * (s + 1)) - 32),
                        Tree.stumpSourceRect,
                        Color.White);

                    // draw the top of the tree
                    Game1.spriteBatch.Draw(
                        currentTreeTexture,
                        new Vector2(48 * i, 96 * s),
                        Tree.treeTopSourceRect,
                        Color.White);
                }
            }
            Game1.spriteBatch.End();

            // reset the render target back to the back buffer
            Game1.graphics.GraphicsDevice.SetRenderTarget(null);

            // create memory stream to save texture as PNG
            var stream = new MemoryStream();

            texture.SaveAsPng(stream, texture.Width, texture.Height);

            // return our tree texture
            treeTexture = Texture2D.FromStream(Game1.graphics.GraphicsDevice, stream);
        }
Example #28
0
        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            if (take_screen_shot)
            {
                renderTarget = new RenderTarget2D(GraphicsDevice, screen_size.X, screen_size.Y);
                GraphicsDevice.SetRenderTarget(renderTarget);
            }
            GraphicsDevice.Clear(Color.Black);
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullNone);
            Vector2 size = new Vector2();

            switch (gstate)
            {
            case 10:     //title screen
                menu.draw_menu(spriteBatch, display);
                break;

            case 60:
                saved_players.draw_list(spriteBatch, display);
                break;

            case 70:
                saved_players.draw_create_chracter(spriteBatch, display, input);
                break;

            case 90:    //server choosing world to use or to create a new world.
                world_manager.draw_choosing_menu(spriteBatch, display);
                break;

            case 91:    //choosing the world to create
                world_definition_manager.draw_choosing_menu(spriteBatch, display);
                break;

            case 92:    //creating a new world... show status text.
                world_definition_manager.creating_draw(spriteBatch, display);
                break;

            case 95:    //client waiting to connect
                size = display.font.MeasureString("Waiting for Initialization");
                display.draw_text(spriteBatch, display.font, "@11Waiting for Initialization", (int)((screen_size.X / 2) - (size.X / 2)), (int)screen_size.Y / 2, screen_size.X);
                break;

            case 100:     //in-game
                Vector2 mouse_world_pos = new Vector2(world.top_left.X + input.mouse_now.X, world.top_left.Y + input.mouse_now.Y);
                if (game_my_user_id != -1)
                {
                    world.total_fps.stop();
                    world.total_fps.start();
                    world.frame_render_time.start();
                    if (settings.use_hardware_lighting)
                    {
                        lighting.draw_scene(spriteBatch, display, world, input, GraphicsDevice);
                    }
                    else
                    {
                        world.draw_world(game_my_user_id, spriteBatch, display, input);
                    }
                    display.draw_fade_text(spriteBatch, world.top_left);
                    world.draw_hud(game_my_user_id, spriteBatch, display, input);
                    world.frame_render_time.stop();
                }
                else
                {
                    size = display.font.MeasureString("Waiting for Initialization");
                    display.draw_text(spriteBatch, display.font, "@11Waiting for Initialization", (int)((screen_size.X / 2) - (size.X / 2)), (int)screen_size.Y / 2, screen_size.X);
                }
                if (draw_debug && world.players.Count > 0)
                {
                    //display.draw_text(spriteBatch, "@00" + network_server.udp_server.Statistics.ToString(), 4, 155, screen_size.X, false);
                    display.draw_text(spriteBatch, "@00" + world.ToString(), 4, 155, screen_size.X, false);
                    string  stats    = world.frame_render_time.ToString();
                    Vector2 size_str = display.middle_font.MeasureString(stats);
                    display.draw_text(spriteBatch, display.middle_font, "@07" + stats, screen_size.X - (int)size_str.X, screen_size.Y - (int)size_str.Y, screen_size.X);

                    stats    = world.water_update_time.ToString();
                    size_str = display.middle_font.MeasureString(stats);
                    display.draw_text(spriteBatch, display.middle_font, "@07" + stats, screen_size.X - (int)size_str.X, screen_size.Y - (int)size_str.Y - 30, screen_size.X);

                    stats    = world.light_time.ToString();
                    size_str = display.middle_font.MeasureString(stats);
                    display.draw_text(spriteBatch, display.middle_font, "@07" + stats, screen_size.X - (int)size_str.X, screen_size.Y - (int)size_str.Y - 60, screen_size.X);

                    stats    = world.updating.ToString();
                    size_str = display.middle_font.MeasureString(stats);
                    display.draw_text(spriteBatch, display.middle_font, "@07" + stats, screen_size.X - (int)size_str.X, screen_size.Y - (int)size_str.Y - 90, screen_size.X);

                    stats    = world.total_fps.ToString();
                    size_str = display.middle_font.MeasureString(stats);
                    display.draw_text(spriteBatch, display.middle_font, "@07" + stats, screen_size.X - (int)size_str.X, screen_size.Y - (int)size_str.Y - 120, screen_size.X);

                    stats    = world.world_generation.ToString();
                    size_str = display.middle_font.MeasureString(stats);
                    display.draw_text(spriteBatch, display.middle_font, "@07" + stats, screen_size.X - (int)size_str.X, screen_size.Y - (int)size_str.Y - 150, screen_size.X);

                    stats    = world.flowing_blocks.ToString();
                    size_str = display.middle_font.MeasureString(stats);
                    display.draw_text(spriteBatch, display.middle_font, "@07" + stats, screen_size.X - (int)size_str.X, screen_size.Y - (int)size_str.Y - 180, screen_size.X);
                }
                if (world.players.Count > 0 && settings.show_ping && play_type != "Single Player")
                {
                    string  stats    = "";
                    Vector2 size_str = new Vector2();

                    if (game_server)
                    {
                        stats    = "Hosting";
                        size_str = display.small_font.MeasureString(stats);
                        display.draw_text(spriteBatch, display.small_font, Display.color_code + "00Hosting", screen_size.X - (int)size_str.X, 0, 220);
                    }
                    else if (network_client.udp_client.Connections.Count > 0)
                    {
                        stats    = "ping: " + Math.Round(network_client.udp_client.Connections[0].AverageRoundtripTime * 1000f, 1).ToString() + "ms";
                        size_str = display.small_font.MeasureString(stats);
                        display.draw_text(spriteBatch, display.small_font, Display.color_code + "00" + stats, screen_size.X - (int)size_str.X, 0, 120);
                    }
                    else
                    {
                        stats    = "ping: DISCONNECTED";
                        size_str = display.small_font.MeasureString(stats);
                        display.draw_text(spriteBatch, display.small_font, Display.color_code + "00ping: @07DISCONNECTED", screen_size.X - (int)size_str.X, 0, 220);
                    }
                }
                break;
            }
            display.draw_messages(spriteBatch, input);
            if (draw_debug)
            {
                display.draw_text_with_outline(spriteBatch, display.small_font, Display.color_code + "00" + debug, 4, 204, screen_size.X, AccColors.Adamantium);
            }
            spriteBatch.Draw(display.sprites, new Rectangle(input.mouse_now.X, input.mouse_now.Y, (int)(16.0 * 2), (int)(16.0 * 2)), display.mouse, Color.White);
            spriteBatch.End();

            if (take_screen_shot)
            {
                GraphicsDevice.SetRenderTarget(null);
                try
                {
                    System.IO.Directory.CreateDirectory(@"screenshots");
                }
                catch
                {
                }
                System.IO.StreamWriter w = new System.IO.StreamWriter(@"screenshots/screenshot_" + DateTime.Now.Ticks.ToString() + ".png");
                renderTarget.SaveAsPng(w.BaseStream, screen_size.X, screen_size.Y);
                w.Close();
                Exilania.display.add_message("@05Screenshot Saved.");
                if (settings.use_hardware_lighting)
                {
                    /*w = new System.IO.StreamWriter(@"screenshots/screenshot_" + DateTime.Now.Ticks.ToString() + "lights.png");
                     * lighting.lightsTarget.SaveAsPng(w.BaseStream, lighting.lightsTarget.Width, lighting.lightsTarget.Height);
                     * w.Close();*/
                }
                take_screen_shot = false;
                spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone);
                spriteBatch.Draw(renderTarget, new Vector2(0, 0), Color.White);
                spriteBatch.End();
            }
            base.Draw(gameTime);
        }
Example #29
0
        private unsafe int HandleSDLEvent(IntPtr userdata, IntPtr ptr)
        {
            SDL_Event *e = (SDL_Event *)ptr;

            switch (e->type)
            {
            case SDL.SDL_EventType.SDL_AUDIODEVICEADDED:
                Console.WriteLine("AUDIO ADDED: {0}", e->adevice.which);

                break;

            case SDL.SDL_EventType.SDL_AUDIODEVICEREMOVED:
                Console.WriteLine("AUDIO REMOVED: {0}", e->adevice.which);

                break;


            case SDL.SDL_EventType.SDL_WINDOWEVENT:

                switch (e->window.windowEvent)
                {
                case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_ENTER:
                    Mouse.MouseInWindow = true;

                    break;

                case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_LEAVE:
                    Mouse.MouseInWindow = false;

                    break;

                case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_FOCUS_GAINED:
                    Plugin.OnFocusGained();

                    break;

                case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_FOCUS_LOST:
                    Plugin.OnFocusLost();

                    break;
                }

                break;

            case SDL.SDL_EventType.SDL_KEYDOWN:

                Keyboard.OnKeyDown(e->key);

                if (Plugin.ProcessHotkeys((int)e->key.keysym.sym, (int)e->key.keysym.mod, true))
                {
                    _ignoreNextTextInput = false;
                    UIManager.KeyboardFocusControl?.InvokeKeyDown(e->key.keysym.sym, e->key.keysym.mod);

                    _scene.OnKeyDown(e->key);
                }
                else
                {
                    _ignoreNextTextInput = true;
                }

                break;

            case SDL.SDL_EventType.SDL_KEYUP:

                Keyboard.OnKeyUp(e->key);
                UIManager.KeyboardFocusControl?.InvokeKeyUp(e->key.keysym.sym, e->key.keysym.mod);
                _scene.OnKeyUp(e->key);
                Plugin.ProcessHotkeys(0, 0, false);

                if (e->key.keysym.sym == SDL_Keycode.SDLK_PRINTSCREEN)
                {
                    string path = Path.Combine(FileSystemHelper.CreateFolderIfNotExists(CUOEnviroment.ExecutablePath, "Data", "Client", "Screenshots"), $"screenshot_{DateTime.Now:yyyy-MM-dd_hh-mm-ss}.png");

                    using (Stream stream = File.Create(path))
                    {
                        _buffer.SaveAsPng(stream, _buffer.Width, _buffer.Height);

                        GameActions.Print($"Screenshot stored in: {path}", 0x44, MessageType.System);
                    }
                }

                break;

            case SDL.SDL_EventType.SDL_TEXTINPUT:

                if (_ignoreNextTextInput)
                {
                    break;
                }

                string s = StringHelper.ReadUTF8(e->text.text);

                if (!string.IsNullOrEmpty(s))
                {
                    UIManager.KeyboardFocusControl?.InvokeTextInput(s);
                    _scene.OnTextInput(s);
                }
                break;

            case SDL.SDL_EventType.SDL_MOUSEMOTION:
                Mouse.Update();

                if (Mouse.IsDragging)
                {
                    UIManager.OnMouseDragging();
                    _scene.OnMouseDragging();
                }

                if (Mouse.IsDragging && !_dragStarted)
                {
                    _dragStarted = true;
                }

                break;

            case SDL.SDL_EventType.SDL_MOUSEWHEEL:
                Mouse.Update();
                bool isup = e->wheel.y > 0;

                Plugin.ProcessMouse(0, e->wheel.y);

                UIManager.OnMouseWheel(isup);
                _scene.OnMouseWheel(isup);

                break;

            case SDL.SDL_EventType.SDL_MOUSEBUTTONUP:
            case SDL.SDL_EventType.SDL_MOUSEBUTTONDOWN:
                Mouse.Update();
                bool isDown = e->type == SDL.SDL_EventType.SDL_MOUSEBUTTONDOWN;

                if (_dragStarted && !isDown)
                {
                    _dragStarted = false;
                }

                SDL.SDL_MouseButtonEvent mouse = e->button;

                switch ((uint)mouse.button)
                {
                case SDL_BUTTON_LEFT:

                    if (isDown)
                    {
                        Mouse.Begin();
                        Mouse.LButtonPressed    = true;
                        Mouse.LDropPosition     = Mouse.Position;
                        Mouse.CancelDoubleClick = false;
                        uint ticks = Time.Ticks;

                        if (Mouse.LastLeftButtonClickTime + Mouse.MOUSE_DELAY_DOUBLE_CLICK >= ticks)
                        {
                            Mouse.LastLeftButtonClickTime = 0;

                            bool res = UIManager.ValidForDClick() ? UIManager.OnLeftMouseDoubleClick() : _scene.OnLeftMouseDoubleClick();

                            if (!res)
                            {
                                _scene.OnLeftMouseDown();
                                UIManager.OnLeftMouseButtonDown();
                            }
                            else
                            {
                                Mouse.LastLeftButtonClickTime = 0xFFFF_FFFF;
                            }

                            break;
                        }

                        _scene.OnLeftMouseDown();
                        UIManager.OnLeftMouseButtonDown();

                        Mouse.LastLeftButtonClickTime = Mouse.CancelDoubleClick ? 0 : ticks;
                    }
                    else
                    {
                        if (Mouse.LastLeftButtonClickTime != 0xFFFF_FFFF)
                        {
                            if (!UIManager.HadMouseDownOnGump(MouseButtonType.Left))
                            {
                                _scene.OnLeftMouseUp();
                            }
                            UIManager.OnLeftMouseButtonUp();
                        }
                        Mouse.LButtonPressed = false;
                        Mouse.End();
                    }

                    break;

                case SDL_BUTTON_MIDDLE:

                    if (isDown)
                    {
                        Mouse.Begin();
                        Mouse.MButtonPressed    = true;
                        Mouse.MDropPosition     = Mouse.Position;
                        Mouse.CancelDoubleClick = false;
                        uint ticks = Time.Ticks;

                        if (Mouse.LastMidButtonClickTime + Mouse.MOUSE_DELAY_DOUBLE_CLICK >= ticks)
                        {
                            Mouse.LastMidButtonClickTime = 0;

                            if (!_scene.OnMiddleMouseDoubleClick())
                            {
                                _scene.OnMiddleMouseDown();
                                UIManager.OnMiddleMouseButtonDown();
                            }

                            break;
                        }

                        Plugin.ProcessMouse(e->button.button, 0);

                        _scene.OnMiddleMouseDown();
                        UIManager.OnMiddleMouseButtonDown();

                        Mouse.LastMidButtonClickTime = Mouse.CancelDoubleClick ? 0 : ticks;
                    }
                    else
                    {
                        if (Mouse.LastMidButtonClickTime != 0xFFFF_FFFF)
                        {
                            if (!UIManager.HadMouseDownOnGump(MouseButtonType.Middle))
                            {
                                _scene.OnMiddleMouseUp();
                            }
                            UIManager.OnMiddleMouseButtonUp();
                        }

                        Mouse.MButtonPressed = false;
                        Mouse.End();
                    }

                    break;

                case SDL_BUTTON_RIGHT:

                    if (isDown)
                    {
                        Mouse.Begin();
                        Mouse.RButtonPressed    = true;
                        Mouse.RDropPosition     = Mouse.Position;
                        Mouse.CancelDoubleClick = false;
                        uint ticks = Time.Ticks;

                        if (Mouse.LastRightButtonClickTime + Mouse.MOUSE_DELAY_DOUBLE_CLICK >= ticks)
                        {
                            Mouse.LastRightButtonClickTime = 0;

                            bool res = _scene.OnRightMouseDoubleClick() || UIManager.OnRightMouseDoubleClick();

                            if (!res)
                            {
                                _scene.OnRightMouseDown();
                                UIManager.OnRightMouseButtonDown();
                            }
                            else
                            {
                                Mouse.LastRightButtonClickTime = 0xFFFF_FFFF;
                            }

                            break;
                        }

                        _scene.OnRightMouseDown();
                        UIManager.OnRightMouseButtonDown();

                        Mouse.LastRightButtonClickTime = Mouse.CancelDoubleClick ? 0 : ticks;
                    }
                    else
                    {
                        if (Mouse.LastRightButtonClickTime != 0xFFFF_FFFF)
                        {
                            if (!UIManager.HadMouseDownOnGump(MouseButtonType.Right))
                            {
                                _scene.OnRightMouseUp();
                            }
                            UIManager.OnRightMouseButtonUp();
                        }
                        Mouse.RButtonPressed = false;
                        Mouse.End();
                    }

                    break;

                case SDL_BUTTON_X1:
                case SDL_BUTTON_X2:
                    if (isDown)
                    {
                        Mouse.Begin();
                        Mouse.XButtonPressed    = true;
                        Mouse.CancelDoubleClick = false;
                        Plugin.ProcessMouse(e->button.button, 0);
                        _scene.OnExtraMouseDown(mouse.button - 1);
                        UIManager.OnExtraMouseButtonDown(mouse.button - 1);
                    }
                    else
                    {
                        if (!UIManager.HadMouseDownOnGump(MouseButtonType.XButton1) && !UIManager.HadMouseDownOnGump(MouseButtonType.XButton2))
                        {
                            _scene.OnExtraMouseUp(mouse.button - 1);
                        }
                        UIManager.OnExtraMouseButtonUp(mouse.button - 1);

                        Mouse.XButtonPressed = false;
                        Mouse.End();
                    }

                    break;
                }

                break;
            }

            return(0);
        }
Example #30
0
 void _saveRTasPNG(RenderTarget2D rt, string filename)
 {
     stream = System.IO.File.Create(filename);
     rt.SaveAsPng(stream, rt.Width, rt.Height);
     stream.Close();
 }