void LeakRepro() { for (int i = 0; i < 50; i++) { var rt = new RenderTarget2D( GraphicsDevice, 800, 480, false, SurfaceFormat.Color, DepthFormat.None, 0, RenderTargetUsage.PreserveContents); GraphicsDevice.SetRenderTarget(rt); GraphicsDevice.Clear(Color.Green); GraphicsDevice.SetRenderTarget(null); MemoryStream ms = new MemoryStream(); rt.SaveAsPng(ms, 800, 480); ms.Close(); rt.Dispose(); } GC.Collect(); List<string> buttons = new List<string>(); buttons.Add("Close"); var message = string.Format( "Total memory: {0}\n" + "Used memory: {1}\n", DeviceExtendedProperties.GetValue("DeviceTotalMemory").ToString(), DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage").ToString() ); IAsyncResult ar = Guide.BeginShowMessageBox("Info", message, buttons, 0, MessageBoxIcon.None, null, null); Guide.EndShowMessageBox(ar); }
public void Generate(Block[,,] blocks, ChunkInfo info) { while (RuntimeGame.DeviceForStateValidationOutput == null) continue; lock (RuntimeGame.LockForStateValidationOutput) { Console.Write("Locked graphics. Rendering graph to file..."); RainfallInformation rainfall = info.Objects.First(val => val is RainfallInformation) as RainfallInformation; TemperatureInformation temperature = info.Objects.First(val => val is TemperatureInformation) as TemperatureInformation; PresentationParameters pp = RuntimeGame.DeviceForStateValidationOutput.PresentationParameters; RenderTarget2D renderTarget = new RenderTarget2D(RuntimeGame.DeviceForStateValidationOutput, 200, 200, true, RuntimeGame.DeviceForStateValidationOutput.DisplayMode.Format, DepthFormat.Depth24); RuntimeGame.DeviceForStateValidationOutput.SetRenderTarget(renderTarget); RuntimeGame.ContextForStateValidationOutput.SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone);//, SaveStateMode.None, Matrix.Identity); //graphics.GraphicsDevice.SamplerStates[0].MagFilter = TextureFilter.Point; //graphics.GraphicsDevice.SamplerStates[0].MinFilter = TextureFilter.Point; //graphics.GraphicsDevice.SamplerStates[0].MipFilter = TextureFilter.Point; XnaGraphics graphics = new XnaGraphics(RuntimeGame.ContextForStateValidationOutput); if (File.Exists("state.png")) { using (StreamReader reader = new StreamReader("state.png")) { Texture2D tex = Texture2D.FromStream(RuntimeGame.DeviceForStateValidationOutput, reader.BaseStream); RuntimeGame.ContextForStateValidationOutput.SpriteBatch.Draw(tex, new Rectangle(0, 0, 200, 200), Color.White); } } else { graphics.FillRectangle(0, 0, 200, 200, Color.Red); graphics.FillRectangle(0, 0, 100, 100, Color.White); } for (int x = 0; x < info.Bounds.Width; x++) for (int y = 0; y < info.Bounds.Height; y++) { int r = 100 - (int)(rainfall.Rainfall[x, y] * 100); int t = 100 - (int)(temperature.Temperature[x, y] * 100); graphics.DrawLine(r, t, r + 1, t + 1, 1, new Color(0f, 0f, 0f, 0.1f).ToPremultiplied()); } RuntimeGame.ContextForStateValidationOutput.SpriteBatch.End(); RuntimeGame.DeviceForStateValidationOutput.SetRenderTarget(null); using (StreamWriter writer = new StreamWriter("state.png")) { renderTarget.SaveAsPng(writer.BaseStream, 200, 200); } Console.WriteLine(" done."); } }
void OnClick() { Directory.CreateDirectory("Chunks"); IsometricLighting lighting = new IsometricLighting(); MouseOverList mouseOverNull = new MouseOverList(new MousePicking()); SpriteBatch3D spritebatch = Service.Get<SpriteBatch3D>(); RenderTarget2D render = new RenderTarget2D(spritebatch.GraphicsDevice, Width + WidthExtra * 2, Height + HeightExtra * 2 + HeightExtra2); Map map = new Map(0); for (int chunky = 0; chunky < 10; chunky++) { for (int chunkx = 0; chunkx < 10; chunkx++) { spritebatch.GraphicsDevice.SetRenderTarget(render); spritebatch.Reset(); uint cx = (uint)chunkx + 200; uint cy = (uint)chunky + 200; map.CenterPosition = new Point((int)(cx << 3), (int)(cy << 3)); MapChunk chunk = map.GetMapChunk(cx, cy); chunk.LoadStatics(map.MapData, map); int z = 0; for (int i = 0; i < 64; i++) { int y = (i / 8); int x = (i % 8); int sy = y * 22 + x * 22 + HeightExtra + HeightExtra2; int sx = 22 * 8 - y * 22 + x * 22 + WidthExtra; MapTile tile = chunk.Tiles[i]; tile.ForceSort(); for (int j = 0; j < tile.Entities.Count; j++) { AEntity e = tile.Entities[j]; AEntityView view = e.GetView(); view.Draw(spritebatch, new Vector3(sx, sy, 0), mouseOverNull, map, false); } } spritebatch.SetLightIntensity(lighting.IsometricLightLevel); spritebatch.SetLightDirection(lighting.IsometricLightDirection); spritebatch.GraphicsDevice.Clear(Color.Transparent); spritebatch.FlushSprites(true); spritebatch.GraphicsDevice.SetRenderTarget(null); render.SaveAsPng(new FileStream($"Chunks/{cy}-{cx}.png", FileMode.Create), render.Width, render.Height); } } }
public void UpdateWindow() { tempTextureToConvert = GameFiles.TextureEditorRenderTarget2D; MemoryStream tempMemoryStream = new MemoryStream(); tempTextureToConvert.SaveAsPng(tempMemoryStream, tempTextureToConvert.Width, tempTextureToConvert.Height); tempMemoryStream.Seek(0, SeekOrigin.Begin); Image tempImageToUpdate = System.Drawing.Bitmap.FromStream(tempMemoryStream); tempMemoryStream.Close(); tempMemoryStream = null; iTextureGraphic.Image = tempImageToUpdate; Invalidate(); /* if (FileManager.Get().GizmoSelection != null && FileManager.Get().GizmoSelection.Count >= 1) { tempTextureToConvert = FileManager.Get().GizmoSelection[0].RenderTarget; MemoryStream tempMemoryStream = new MemoryStream(); tempTextureToConvert.SaveAsPng(tempMemoryStream, tempTextureToConvert.Width, tempTextureToConvert.Height); tempMemoryStream.Seek(0, SeekOrigin.Begin); Image tempImageToUpdate = System.Drawing.Bitmap.FromStream(tempMemoryStream); tempMemoryStream.Close(); tempMemoryStream = null; iTextureGraphic.Image = tempImageToUpdate; Invalidate(); } */ }
public static void ExportAnimation(string folderPath, string nameStarter, int width, int height, float framesPerSecond, float totalTime, GraphicsDevice gd, Action<float> update, Action<SpriteBatch, Rectangle> draw, int antialiasingMultiplier = 1) { var width1 = width*antialiasingMultiplier; var height1 = height*antialiasingMultiplier; var renderTarget = new RenderTarget2D(gd, width1, height1, false, SurfaceFormat.Rgba64, DepthFormat.Depth16, 8, RenderTargetUsage.PlatformContents); var spriteBatch1 = new SpriteBatch(gd); gd.PresentationParameters.MultiSampleCount = 8; var currentRenderTarget = Utils.GetCurrentRenderTarget(); gd.SetRenderTarget(renderTarget); var num1 = 1f/framesPerSecond; var num2 = 0.0f; var num3 = 0; if (!Directory.Exists(folderPath)) Directory.CreateDirectory(folderPath); var spriteBatch2 = GuiData.spriteBatch; GuiData.spriteBatch = spriteBatch1; var rectangle = new Rectangle(0, 0, width1, height1); while (num2 < (double) totalTime) { gd.Clear(Color.Transparent); spriteBatch1.Begin(); draw(spriteBatch1, rectangle); spriteBatch1.End(); update(num1); gd.SetRenderTarget(null); var str = string.Concat(nameStarter, "_", num3, ".png"); using (var fileStream = File.Create(folderPath + "/" + str)) renderTarget.SaveAsPng(fileStream, width, height); gd.SetRenderTarget(renderTarget); ++num3; num2 += num1; } GuiData.spriteBatch = spriteBatch2; gd.SetRenderTarget(currentRenderTarget); }
public static void Save(this RenderTarget2D target, string path) { using (var stream = System.IO.File.OpenWrite(path)) target.SaveAsPng(stream, target.Bounds.Width, target.Bounds.Height); }
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); } }
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(); } } } }
public void ComputeLightMap(SpriteBatch batch, Map map, string Path) { Camera cam = new Camera(Vector2.Zero, map.MapBoundaries); cam.Zoom(-1); Vector2 viewFieldDiagonal = new Vector2(cam.ViewSpace.Width *0.5f, cam.ViewSpace.Height *0.5f); cam.SetPos(viewFieldDiagonal); lightMapTarget = new RenderTarget2D(device, map.MapBoundaries.Width, map.MapBoundaries.Height,false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8); Matrix baseProjection = cam.ProjectionMatrix; map.SetUpLightMapPrecomputeLights(); device.SetRenderTarget(lightMapTarget); //Clear Target first device.DepthStencilState = clearStencil; device.RasterizerState = RasterizerState.CullNone; device.BlendState = BlendState.Opaque; shadowEffect.Parameters["View"].SetValue(cam.ViewMatrix); shadowEffect.Parameters["Projection"].SetValue(Matrix.Identity); shadowEffect.Parameters["shadowDarkness"].SetValue(0.9f - 1); shadowEffect.Parameters["viewDistance"].SetValue((float)(1 / (0.001f + 0.999 ))); shadowEffect.CurrentTechnique = shadowEffect.Techniques["Clear"]; device.SetVertexBuffer(clearVBuffer); device.Indices = clearIBuffer; shadowEffect.CurrentTechnique.Passes[0].Apply(); device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 4, 0, 2); //Matrix UpperLeftShift = Matrix.CreateTranslation(-1+(float)cam.ViewSpace.Width / (float)map.MapBoundaries.Width, 1-(float)cam.ViewSpace.Height / (float)map.MapBoundaries.Height, 0); //cam.ProjectionMatrix = baseProjection * Matrix.CreateScale((float)cam.ViewSpace.Width / map.MapBoundaries.Width, (float)cam.ViewSpace.Height / map.MapBoundaries.Height, 1) * UpperLeftShift * Matrix.CreateTranslation(cam.ViewSpace.Left / map.MapBoundaries.Width, cam.ViewSpace.Top / map.MapBoundaries.Height, 0); DrawLights(1, cam, batch, lightMapTarget); //cam.Move(new Vector2(0, viewFieldDiagonal.Y * 2)); RenderTarget2D blurTarget = new RenderTarget2D(device,lightMapTarget.Width,lightMapTarget.Height); shadowEffect.Parameters["xTexelDist"].SetValue(1.0f / (blurTarget.Width / lightMapDownSample)); shadowEffect.Parameters["yTexelDist"].SetValue(1.0f / (blurTarget.Height / lightMapDownSample)); BlurShadowTarget(batch, lightMapTarget, blurTarget); BlurShadowTarget(batch, lightMapTarget, blurTarget); shadowEffect.Parameters["xTexelDist"].SetValue(1.0f / (device.PresentationParameters.BackBufferWidth / lightMapDownSample)); shadowEffect.Parameters["yTexelDist"].SetValue(1.0f / (device.PresentationParameters.BackBufferHeight / lightMapDownSample)); device.SetRenderTarget(null); Clear(); System.IO.FileStream fs = System.IO.File.Open(Path, System.IO.FileMode.Create); lightMapTarget.SaveAsPng(fs, lightMapTarget.Width, lightMapTarget.Height); fs.Close(); lightMap = lightMapTarget; _hasLightmap = true; }
public void SaveResults(string loc) { List<Texture2D> result = new List<Texture2D>(); for (int i = 0; i < points.Length; i++) { List<Vector2> _points = points[i]; if (_points.Count > 0) { int xmin = Int32.MaxValue; int xmax = -1; int ymin = Int32.MaxValue; int ymax = -1; foreach (Vector2 point in _points) { if (point.X < xmin) xmin = (int)point.X; if (point.Y < ymin) ymin = (int)point.Y; if (point.X > xmax) xmax = (int)point.X; if (point.Y > ymax) ymax = (int)point.Y; } int w = xmax * 16 - xmin * 16; int h = ymax * 16 - ymin * 16; w += 16; h += 16; RenderTarget2D target = new RenderTarget2D(GraphicsDevice, w, h); GraphicsDevice.SetRenderTarget(target); GraphicsDevice.Clear(Color.Transparent); SpriteBatch batch = new SpriteBatch(GraphicsDevice); batch.Begin(); foreach (Vector2 point in _points) { Rectangle rect = new Rectangle((int)point.X << 4, (int)point.Y << 4, 16, 16); batch.Draw(Tileset.Texture.Texture, new Vector2(((int)point.X << 4) - xmin * 16, ((int)point.Y << 4) - ymin * 16), rect, Color.White); } batch.End(); GraphicsDevice.SetRenderTarget(null); using (FileStream stream = File.OpenWrite(loc + "\\" + i + ".png")) { target.SaveAsPng(stream, target.Width, target.Height); stream.Flush(); stream.Close(); } } } }
void save(RenderTarget2D r, string n = "ololo") { var t = graphics.GraphicsDevice.GetRenderTargets(); graphics.GraphicsDevice.SetRenderTarget(null); using (var fstr = File.OpenWrite(n + ".png")) { r.SaveAsPng(fstr, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight); } graphics.GraphicsDevice.SetRenderTargets(t); }
public void saveScreenShot(string filename) { Rectangle rect = new Rectangle(sx(0), sy(0), Maze.width, Maze.height); int w = GraphicsDevice.PresentationParameters.BackBufferWidth; int h = GraphicsDevice.PresentationParameters.BackBufferHeight; RenderTarget2D screenShot = new RenderTarget2D(GraphicsDevice, w, h); GraphicsDevice.SetRenderTarget(screenShot); Draw(new GameTime()); GraphicsDevice.SetRenderTarget(null); GraphicsDevice gd = screenShot.GraphicsDevice; RenderTarget2D cropped = new RenderTarget2D(gd, Maze.width, Maze.height); SpriteBatch sb = new SpriteBatch(gd); gd.SetRenderTarget(cropped); gd.Clear(new Color(0, 0, 0, 0)); sb.Begin(); sb.Draw(screenShot, Vector2.Zero, rect, Color.White); sb.End(); gd.SetRenderTarget(null); screenShot.Dispose(); using (FileStream stream = new FileStream(filename, FileMode.Create)) { cropped.SaveAsPng(stream, cropped.Width, cropped.Height); cropped.Dispose(); } }
public static void OutputRendertarget(RenderTarget2D rt2dSource, string sDirectory, string sFileName) { if (!Directory.Exists("sDirectory")) { Directory.CreateDirectory("sDirectory"); } FileStream mos = new FileStream(sDirectory + "/" + sFileName, FileMode.Create, FileAccess.Write); rt2dSource.SaveAsPng(mos, rt2dSource.Width, rt2dSource.Height); mos.Close(); }
private void MenuExtrasMapPreview_Click(object sender, EventArgs e) { if (mTileMap == null || mTileMap.Width == 0 || mTileMap.Height == 0) { return; } var watch = Stopwatch.StartNew(); var pp = GraphicsDevice.PresentationParameters; var renderTarget = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight); var toDelete = new List<string>(); var mapBmp = new Bitmap(mTileMap.WidthInPixels, mTileMap.HeightInPixels); var g = Graphics.FromImage(mapBmp); Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "Preview"); // reset MapView to always display first Screen SetZoom(1.0f); MapVScrollBar.Value = 0; MapHScrollBar.Value = 0; mCamera.X = 0; mCamera.Y = 0; var end = Point2D.Zero; var viewable = new Point2D(RenderDisplayMap.Width / mCamera.TileWidth, RenderDisplayMap.Height / mCamera.TileHeight); for (var mapX = 0; mapX < mTileMap.Width; mapX += viewable.X) { for (var mapY = 0; mapY < mTileMap.Height; mapY += viewable.Y) { GraphicsDevice.SetRenderTarget(renderTarget); GraphicsDevice.Clear(Color.Black); var start = new Point2D(mapX, mapY); end.X = Math.Min(start.X + viewable.X, mTileMap.Width); end.Y = Math.Min(start.Y + viewable.Y, mTileMap.Height); mSpriteBatch.Begin(); mTileMap.Draw(mSpriteBatch, mCamera, mGameTime.ElapsedGameTime.TotalSeconds, (ETileDrawType.BackGround | ETileDrawType.ForeGround | ETileDrawType.Animation), start, end, true); mSpriteBatch.End(); GraphicsDevice.SetRenderTarget(null); var texPath = String.Format(@"{0}Preview\{1}_{2}x{3}.png", AppDomain.CurrentDomain.BaseDirectory, mTileMap.Name, mapX, mapY); renderTarget.SaveAsPng(File.OpenWrite(texPath), renderTarget.Width, renderTarget.Height); using (var img = Image.FromFile(texPath)) { g.DrawImage(img, new Point(mapX * mCamera.TileWidth, mapY * mCamera.TileHeight)); } //mapBmp.Save( String.Format( @"{0}Preview\{1}_Full_{2}x{3}.png", AppDomain.CurrentDomain.BaseDirectory, mTileMap.Name, mapX, mapY ), System.Drawing.Imaging.ImageFormat.Png ); toDelete.Add(texPath); } } // save & clean try { g.Save(); mapBmp.Save(AppDomain.CurrentDomain.BaseDirectory + @"Preview\" + mTileMap.Name + "_Full.png", ImageFormat.Png); mapBmp.Dispose(); g.Dispose(); } catch (Exception ex) { Debug.WriteLine(ex); } foreach (var filepath in toDelete) { try { File.Delete(filepath); } catch { } } toDelete.Clear(); MessageBox.Show("Preview erstellt!\nBenötigte Zeit: " + (watch.ElapsedMilliseconds / 1000) + "sec"); watch.Stop(); }
private void Rebuild(string fIn, string fOut) { // Check Args FileInfo fiIn = new FileInfo(fIn); if(!fiIn.Exists) { Console.WriteLine("File Does Not Exist"); return; } FileInfo fiOut = new FileInfo(fOut); if(!fiOut.Directory.Exists) { Console.WriteLine("Output Directory Does Not Exist"); return; } // Read Model Stream s = File.OpenRead(fiIn.FullName); VertexPositionNormalTexture[] verts; int[] inds; if(!ObjParser.TryParse(s, out verts, out inds, ParsingFlags.ConversionOpenGL)) { s.Dispose(); Console.WriteLine("Could Not Read Model"); return; } s.Dispose(); // Compute The AABB Of The Terrain BoundingBox aabb = ComputeAABB(verts); Vector3 mid = aabb.Max + aabb.Min; Vector3 dif = aabb.Max - aabb.Min; Vector3 top = new Vector3(mid.X, aabb.Max.Y, mid.Z); mid *= 0.5f; fx.FogStart = 1f; fx.FogEnd = aabb.Max.Y - aabb.Min.Y + 1f; fx.World = Matrix.Identity; fx.View = Matrix.CreateLookAt(top + Vector3.UnitY, mid, -Vector3.UnitZ); fx.Projection = Matrix.CreateOrthographic(dif.X, dif.Z, 0, dif.Y + 2f); // Append A Plane At The Bottom int vc = verts.Length, ic = inds.Length; Array.Resize(ref verts, verts.Length + 4); Array.Resize(ref inds, inds.Length + 6); inds[ic++] = vc + 0; inds[ic++] = vc + 1; inds[ic++] = vc + 2; inds[ic++] = vc + 2; inds[ic++] = vc + 1; inds[ic++] = vc + 3; verts[vc++] = new VertexPositionNormalTexture( new Vector3(aabb.Min.X, aabb.Min.Y, aabb.Min.Z), Vector3.UnitY, Vector2.Zero ); verts[vc++] = new VertexPositionNormalTexture( new Vector3(aabb.Max.X, aabb.Min.Y, aabb.Min.Z), Vector3.UnitY, Vector2.UnitX ); verts[vc++] = new VertexPositionNormalTexture( new Vector3(aabb.Min.X, aabb.Min.Y, aabb.Max.Z), Vector3.UnitY, Vector2.UnitY ); verts[vc++] = new VertexPositionNormalTexture( new Vector3(aabb.Max.X, aabb.Min.Y, aabb.Max.Z), Vector3.UnitY, Vector2.One ); // Create Model VertexBuffer vb = new VertexBuffer(G, VertexPositionNormalTexture.VertexDeclaration, verts.Length, BufferUsage.WriteOnly); vb.SetData(verts); IndexBuffer ib = new IndexBuffer(G, IndexElementSize.ThirtyTwoBits, inds.Length, BufferUsage.WriteOnly); ib.SetData(inds); // Render The Height if(rtHeight != null) rtHeight.Dispose(); rtHeight = new RenderTarget2D(G, 4096, 4096, false, SurfaceFormat.Color, DepthFormat.Depth24); G.SetRenderTarget(rtHeight); G.SetVertexBuffer(vb); G.Indices = ib; fx.CurrentTechnique.Passes[0].Apply(); G.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vb.VertexCount, 0, ib.IndexCount / 3); // Dispose Of Buffers G.SetRenderTarget(null); G.Clear(Color.Black); G.SetVertexBuffer(null); G.Indices = null; vb.Dispose(); ib.Dispose(); // Save The Image using(Stream os = File.Create(fiOut.FullName)) { rtHeight.SaveAsPng(os, rtHeight.Width, rtHeight.Height); } ShouldRebuild = false; }
public void SaveCameraAsImage() { //Get the path! SaveFileDialog dialog = new SaveFileDialog(); dialog.Title = "Save Level as Image..."; dialog.Filter = "PNG Image File|*.png"; dialog.InitialDirectory = Ogmo.Project.SavedDirectory; DialogResult result = dialog.ShowDialog(); if (result == DialogResult.Cancel) return; //Draw the level! float scale = Math.Min(Math.Min(4096.0f / Ogmo.Project.CameraSize.Width, 1), Math.Min(4096.0f / Ogmo.Project.CameraSize.Height, 1)); int width = (int)(scale * Ogmo.Project.CameraSize.Width); int height = (int)(scale * Ogmo.Project.CameraSize.Height); Matrix cameraMatrix = Matrix.CreateScale(scale) * Matrix.CreateTranslation(-Level.CameraPosition.X, -Level.CameraPosition.Y, 0); RenderTarget2D texture = new RenderTarget2D(Ogmo.EditorDraw.GraphicsDevice, width, height); Ogmo.EditorDraw.GraphicsDevice.SetRenderTarget(texture); Ogmo.EditorDraw.GraphicsDevice.Clear(Ogmo.Project.BackgroundColor.ToXNA()); for (int i = 0; i < LayerEditors.Count; i++) { if (Ogmo.Project.LayerDefinitions[i].Visible) { Ogmo.EditorDraw.SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, RasterizerState.CullNone, null, LayerEditors[i].DrawMatrix * cameraMatrix); LayerEditors[i].DrawLocal(false, 1); Ogmo.EditorDraw.SpriteBatch.End(); } } Ogmo.EditorDraw.GraphicsDevice.SetRenderTarget(null); //Save it then dispose it Stream stream = dialog.OpenFile(); texture.SaveAsPng(stream, width, height); stream.Close(); texture.Dispose(); }
// Takes a tiny screencap of the current map renderstack (ignoring mcgrender layers) // and sticks it into the given stream. protected void write_thumbnail_screencap(Stream stream) { using (RenderTarget2D screencap = new RenderTarget2D(game.GraphicsDevice, game.screen.width, game.screen.height)) { game.GraphicsDevice.SetRenderTarget(screencap); game.map.renderstack.Draw(); game.GraphicsDevice.SetRenderTarget(null); screencap.SaveAsPng(stream, THUMBNAIL_SIZE.X, THUMBNAIL_SIZE.Y); } }
private void TextureHandler(object sender, EventArgs e) { PictureBox pictureBox = (TextureSelectionPane as TextureSelectionForm).TexturePreview as PictureBox; Texture2D texture = AssetLibrary.LookupTexture(TextureSelectionPane.TextureList.SelectedItem.ToString()); RenderTarget2D transformedTexture = new RenderTarget2D(GraphicsManager.Device, pictureBox.Width, pictureBox.Height); GraphicsManager.Device.SetRenderTarget(transformedTexture); GraphicsManager.Device.Clear(Color.CornflowerBlue); float widthReducedScale = (float)texture.Width / (float)pictureBox.Width; float uScale = widthReducedScale * (float)TextureSelectionPane.UScale.Value; float heightReducedScale = (float)texture.Height / (float)pictureBox.Height; float vScale = heightReducedScale * (float)TextureSelectionPane.VScale.Value; float uOffset = (float)TextureSelectionPane.UOffset.Value; float vOffset = (float)TextureSelectionPane.VOffset.Value; mTextureTransformShader.Parameters["Texture"].SetValue(texture); mTextureTransformShader.Parameters["UVScale"].SetValue(new Vector2(uScale, vScale)); mTextureTransformShader.Parameters["UVOffset"].SetValue(new Vector2(uOffset, vOffset)); GraphicsManager.SpriteBatch.Begin(SpriteSortMode.FrontToBack, null, SamplerState.LinearWrap, null, null, mTextureTransformShader); GraphicsManager.SpriteBatch.Draw(texture, new Rectangle(0, 0, texture.Width, texture.Height), Color.White); GraphicsManager.SpriteBatch.End(); GraphicsManager.Device.SetRenderTarget(null); //Store data from texture in to image handle. MemoryStream ms = new MemoryStream(); transformedTexture.SaveAsPng(ms, transformedTexture.Width, transformedTexture.Height); ms.Seek(0, SeekOrigin.Begin); System.Drawing.Image bmp = System.Drawing.Bitmap.FromStream(ms); ms.Close(); ms = null; pictureBox.Image = bmp; }
private void CreateTexture() { Vector2 textSize = spriteFont.MeasureString(text); int textureWidth = (int)Math.Pow(2, Math.Ceiling(Math.Log(textSize.X, 2))); int textureHeight = (int)Math.Pow(2, Math.Ceiling(Math.Log(textSize.Y, 2))); fontTexture = new Texture2D(spriteBatch.GraphicsDevice, textureWidth, textureHeight); RenderTarget2D target = new RenderTarget2D(spriteBatch.GraphicsDevice, textureWidth, textureHeight); BasicEffect effect = new BasicEffect(spriteBatch.GraphicsDevice); effect.TextureEnabled = true; effect.VertexColorEnabled = true; effect.CurrentTechnique.Passes[0].Apply(); spriteBatch.GraphicsDevice.SetRenderTarget(target); spriteBatch.GraphicsDevice.Clear(Color.Transparent); spriteBatch.Begin(); spriteBatch.DrawString(spriteFont, text, Vector2.Zero, Color.Black); spriteBatch.End(); spriteBatch.GraphicsDevice.SetRenderTarget(null); target.SaveAsPng(new FileStream("testText.png", FileMode.Create), textureWidth, textureHeight); Color[] textureData = new Color[textureWidth * textureHeight]; target.GetData<Color>(textureData); fontTexture.SetData<Color>(textureData); effect.TextureEnabled = true; effect.Texture = fontTexture; //screenPoints[0].TextureCoordinate = new Vector2(0, 0); //screenPoints[1].TextureCoordinate = new Vector2(1, 0); //screenPoints[2].TextureCoordinate = new Vector2(1, 1); //screenPoints[3].TextureCoordinate = new Vector2(0, 1); screenPoints[0].TextureCoordinate = new Vector2(0, 0); screenPoints[1].TextureCoordinate = new Vector2(textSize.X / textureWidth, 0); screenPoints[2].TextureCoordinate = new Vector2(textSize.X / textureWidth, textSize.Y / textureHeight); screenPoints[3].TextureCoordinate = new Vector2(0, textSize.Y / textureHeight); }
private void CheckKeyboardMouseInput() { #region take these out if(MainGame.GlobalInputHelper.CurrentKeyboardState.IsKeyDown(Keys.Up)) { MainGame.GameCamera.Move(new Vector2i(0, -1)); } if (MainGame.GlobalInputHelper.CurrentKeyboardState.IsKeyDown(Keys.Right)) { MainGame.GameCamera.Move(new Vector2i(1, 0)); } if (MainGame.GlobalInputHelper.CurrentKeyboardState.IsKeyDown(Keys.Down)) { MainGame.GameCamera.Move(new Vector2i(0, 1)); } if (MainGame.GlobalInputHelper.CurrentKeyboardState.IsKeyDown(Keys.Left)) { MainGame.GameCamera.Move(new Vector2i(-1, 0)); } if(MainGame.GlobalInputHelper.CurrentKeyboardState.IsKeyDown(Keys.R)) { world.GetClientPlayer().Move(new Vector2(22 * 32, 16 * 32)); } #endregion if (MainGame.GlobalInputHelper.IsMouseInsideWindow()) { #if DEBUG if(MainGame.GlobalInputHelper.IsNewPress(Keys.F4)) { MainGame.GameOptions.LightsDisabled = !MainGame.GameOptions.LightsDisabled; } if(MainGame.GlobalInputHelper.IsNewPress(Keys.L)) { MainMessageQueue.AddMessage(new Minecraft2DMessage { Sender = "GAME", Content = "Test", Global = true }); } #endif if (MainGame.GlobalInputHelper.IsNewPress(Keys.F2)) { if (!Directory.Exists("Screenshots")) Directory.CreateDirectory("Screenshots"); DateTime nnow = DateTime.Now; if (MainGame.GlobalInputHelper.CurrentKeyboardState.IsKeyDown(Keys.LeftAlt)) { using (FileStream f = File.Create(Path.Combine("Screenshots", $"Screenshot_{nnow.Month}-{nnow.Day}-{nnow.Year}-{nnow.Hour}-{nnow.Minute}-{nnow.Second}.png"))) { worldRenderTarget.SaveAsPng(f, MainGame.GlobalGraphicsDeviceManager.PreferredBackBufferWidth, MainGame.GlobalGraphicsDeviceManager.PreferredBackBufferHeight); f.Close(); } MainMessageQueue.AddMessage(new Minecraft2DMessage { Content = "Screenshot captured!", Global = false, To = MainGame.GameOptions.Username }); } else { RenderTarget2D allTogether = new RenderTarget2D(MainGame.GlobalGraphicsDevice, MainGame.GlobalGraphicsDeviceManager.PreferredBackBufferWidth, MainGame.GlobalGraphicsDeviceManager.PreferredBackBufferHeight); MainGame.GlobalGraphicsDevice.SetRenderTarget(allTogether); MainGame.GlobalGraphicsDevice.Clear(Color.White); MainGame.GlobalSpriteBatch.Begin(SpriteSortMode.Texture, MainGame.Multiply, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone); MainGame.GlobalSpriteBatch.Draw(worldRenderTarget, new Rectangle(0, 0, MainGame.GlobalGraphicsDeviceManager.PreferredBackBufferWidth, MainGame.GlobalGraphicsDeviceManager.PreferredBackBufferHeight), Color.White); MainGame.GlobalSpriteBatch.Draw(worldLightmapPass, new Rectangle(0, 0, MainGame.GlobalGraphicsDeviceManager.PreferredBackBufferWidth, MainGame.GlobalGraphicsDeviceManager.PreferredBackBufferHeight), Color.White); MainGame.GlobalSpriteBatch.End(); MainGame.GlobalGraphicsDevice.SetRenderTarget(null); using (FileStream f = File.Create(Path.Combine("Screenshots", $"Screenshot_{nnow.Month}-{nnow.Day}-{nnow.Year}-{nnow.Hour}-{nnow.Minute}-{nnow.Second}.png"))) { allTogether.SaveAsPng(f, MainGame.GlobalGraphicsDeviceManager.PreferredBackBufferWidth, MainGame.GlobalGraphicsDeviceManager.PreferredBackBufferHeight); f.Close(); } MainMessageQueue.AddMessage(new Minecraft2DMessage { Content = "Screenshot captured!", Global = false, Sender = "GAME", To = MainGame.GameOptions.Username }); } } if (MainGame.GlobalInputHelper.CurrentMouseState.ScrollWheelValue > MainGame.GlobalInputHelper.LastMouseState.ScrollWheelValue) { currentTileIndex++; if (currentTileIndex >= TilesList.Length) currentTileIndex = 0; PlacingTile = TilesList[currentTileIndex]; } if (MainGame.GlobalInputHelper.CurrentMouseState.ScrollWheelValue < MainGame.GlobalInputHelper.LastMouseState.ScrollWheelValue) { currentTileIndex--; if (currentTileIndex < 0) currentTileIndex = TilesList.Length - 1; PlacingTile = TilesList[currentTileIndex]; } if (MainGame.GlobalInputHelper.CurrentMouseState.LeftButton == ButtonState.Pressed) { if (MainGame.GameCamera != null) { Matrix inverseViewMatrix = Matrix.Invert(MainGame.GameCamera.get_transformation(MainGame.GlobalGraphicsDevice)); Vector2 worldMousePosition = Vector2.Transform(new Vector2(MainGame.GlobalInputHelper.CurrentMouseState.X, MainGame.GlobalInputHelper.CurrentMouseState.Y), inverseViewMatrix); Tile airP = PresetBlocks.TilesList.Find(x => x.Name == "minecraft:air").AsTile(); airP.Position = new Vector2((float)Math.Floor(worldMousePosition.X / 32), (float)Math.Floor(worldMousePosition.Y / 32)); world.SetTile((int)worldMousePosition.X, (int)worldMousePosition.Y, airP); } } else if (MainGame.GlobalInputHelper.CurrentMouseState.RightButton == ButtonState.Pressed) { Matrix inverseViewMatrix = Matrix.Invert(MainGame.GameCamera.get_transformation(MainGame.GlobalGraphicsDevice)); Vector2 worldMousePosition = Vector2.Transform(new Vector2(MainGame.GlobalInputHelper.CurrentMouseState.X, MainGame.GlobalInputHelper.CurrentMouseState.Y), inverseViewMatrix); Tile toPlace = PlacingTile.AsTile(); toPlace.Position = new Vector2((int)worldMousePosition.X, (int)worldMousePosition.Y); toPlace.TimePlaced = world.WorldTime; if (world.HasRoomForEntity(toPlace.Bounds, true, true)) { if (world.GetTile((int)worldMousePosition.X, (int)worldMousePosition.Y).Type != toPlace.Type) world.SetTile((int)worldMousePosition.X, (int)worldMousePosition.Y, toPlace); } } else if (MainGame.GlobalInputHelper.CurrentMouseState.MiddleButton == ButtonState.Pressed) { Matrix inverseViewMatrix = Matrix.Invert(MainGame.GameCamera.get_transformation(MainGame.GlobalGraphicsDevice)); Vector2 worldMousePosition = Vector2.Transform(new Vector2(MainGame.GlobalInputHelper.CurrentMouseState.X, MainGame.GlobalInputHelper.CurrentMouseState.Y), inverseViewMatrix); Tile toPlace = PlacingTile.AsTile(); toPlace.IsBackground = true; toPlace.Position = new Vector2((int)worldMousePosition.X, (int)worldMousePosition.Y); if (world.GetTile((int)worldMousePosition.X, (int)worldMousePosition.Y).Type != toPlace.Type) world.SetTile((int)worldMousePosition.X, (int)worldMousePosition.Y, toPlace); } if (MainGame.GlobalInputHelper.IsNewPress(Keys.F3)) { MainGame.GameOptions.ShowDebugInformation = !MainGame.GameOptions.ShowDebugInformation; } if (MainGame.GlobalInputHelper.IsNewPress(Keys.Escape)) { world.WorldObj.SaveWorld(); MainGame.manager.PushScreen(GameScreens.MAIN); } } }
/// <summary> /// Creates a screenshot of the game and saves it to a file. /// </summary> /// <param name="filename">The file to save the screenshot to</param> /// <param name="resolution">The width/height of the image</param> /// <returns>True if the screenshot could be taken, false otherwise</returns> public bool TakeScreenshot(string filename, Point resolution) { try { using (RenderTarget2D renderTarget = new RenderTarget2D(GraphicsDevice, resolution.X, resolution.Y, false, SurfaceFormat.Color, DepthFormat.Depth24)) { GraphicsDevice.SetRenderTarget(renderTarget); DrawSky(new DwarfTime(), Camera.ViewMatrix, 1.0f); Draw3DThings(new DwarfTime(), DefaultShader, Camera.ViewMatrix); DrawComponents(new DwarfTime(), DefaultShader, Camera.ViewMatrix, ComponentManager.WaterRenderType.None, 0); GraphicsDevice.SetRenderTarget(null); renderTarget.SaveAsPng(new FileStream(filename, FileMode.Create), resolution.X, resolution.Y); GraphicsDevice.Textures[0] = null; GraphicsDevice.Indices = null; GraphicsDevice.SetVertexBuffer(null); } } catch(IOException e) { Console.Error.WriteLine(e.Message); return false; } return true; }
public static void TakeScreenshot(RenderTarget2D renderScreen) { string filename = "Screenshots/TVR_" + System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + "_" + System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Second.ToString() + "_" + System.DateTime.Now.Millisecond.ToString() + ".png"; Stream st = new FileStream(filename, FileMode.Create); renderScreen.SaveAsPng(st, 1920, 1080); st.Close(); }