{"id":31251,"date":"2020-12-14T09:00:13","date_gmt":"2020-12-14T16:00:13","guid":{"rendered":"https:\/\/devblogs.microsoft.com\/dotnet\/?p=31251"},"modified":"2022-06-08T14:56:20","modified_gmt":"2022-06-08T21:56:20","slug":"creating-a-game-art-asset-pipeline-in-net","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/dotnet\/creating-a-game-art-asset-pipeline-in-net\/","title":{"rendered":"[Guest Post] Creating a game art asset pipeline in .NET"},"content":{"rendered":"<p><em>This is a guest post by Sam Eddy, a programmer at Kelsam Games. Kelsam&#8217;s games are written in C# using .NET and the MonoGame framework.<\/em><\/p>\n<p><img decoding=\"async\" class=\"aligncenter\" src=\"https:\/\/devblogs.microsoft.com\/dotnet\/wp-content\/uploads\/sites\/10\/2020\/12\/kelsamHeaderLogo.png\" alt=\"Kelsam logo\" \/><\/p>\n<p>Hello .NET community! I am Sam from <a href=\"https:\/\/kelsam.net\/\">Kelsam Games<\/a>, and I have been using .NET to write software for over 10 years, since the XNA days. Nowadays, my wife Kelsie and I write our games using the <a href=\"https:\/\/devblogs.microsoft.com\/dotnet\/tag\/monogame\/\">MonoGame framework<\/a> (one of the spiritual successors of XNA). In this post I would like to share details of one of the tools we use in the development process of our newest game, and how .NET was instrumental in its creation.<\/p>\n<p>When we started the newest version of our game <a href=\"https:\/\/muffed.kelsam.net\/\">Cymatically Muffed<\/a>, we knew we needed to create better development tools that could reduce, or even eliminate, the friction between the art development process and programming. We used to make art assets, then compile them into MonoGame-based assets using a content building tool included with MonoGame. Then, we would re-compile the game (sometimes, depending on changes needed), then pass it back to the designer to test and experiment with. This was the process for every little change, making it quite painful to iterate and improve art, levels, and other features.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter\" src=\"https:\/\/devblogs.microsoft.com\/dotnet\/wp-content\/uploads\/sites\/10\/2020\/12\/art-factory.png\" alt=\"a screenshot of Art Factory\" \/><\/p>\n<p>Enter Art Factory! Art Factory is a simple tool that we built using .NET which removes pain points in the game art creation pipeline! Using Art Factory, Kelsie, our artist, can draw new assets, modify existing ones, and have them all appear in her working game environment without even needing to notify me &#8211; let alone wait on me. Using .NET, Art Factory takes all the assets she passes it and builds them into neatly organized sprite sheets, generates a simple DLL for the game engine, generates some dynamic JavaScript for the online level editor, and builds the generated sprite sheets for various platform targets. Art Factory then copies everything it generated into the artist\u2019s environment and onto the server for the online level editor. Super slick! Now, with the aid of this simple tool, an artist can re-hash and iterate on levels, art, and other features quickly without the involvement of a programmer. .NET made making this tool super simple to pull off programmatically speaking, giving us all the functionality we needed to generate the sprite sheets, DLLs, and JavaScript text files. It also runs MonoGame content building commands and copies and uploads the built files. Using .NET, Art Factory was created in less than a day. (woop woop!)<\/p>\n<h2>Creating Dynamic Enums<\/h2>\n<p>A super helpful part of Art Factory is that it creates a DLL with dynamically generated enums that I can use in-engine. Using .NET&#8217;s System.Reflection, I can easily compile a simple DLL (see code snippet below) that the engine reads so I can enum-reference visual effects, stuff objects, and other data types in the code. This is super useful for keeping my code really readable and maintainable while allowing me to dynamically generate the data from the source files that the artist creates. Best of both worlds.<\/p>\n<p>Generating a DLL in .NET is literally this simple (this is a snippet that generates a simple enum of our visual effects):<\/p>\n<pre><code class=\"csharp\">int counter = 0;\r\nAppDomain currDomain = AppDomain.CurrentDomain;\r\nAssemblyName name = new AssemblyName(\"DynEnums\");\r\nstring dllFile = name.Name + \".dll\";\r\nAssemblyBuilder assemblyBuilder = currDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave);\r\nModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(name.Name, dllFile);\r\n\r\nEnumBuilder vfxTypeEnum = moduleBuilder.DefineEnum(\"Muffed.VfxType\", TypeAttributes.Public, typeof(int));\r\nforeach (string vfxType in vfxTypes)\r\n{\r\n    vfxTypeEnum.DefineLiteral(vfxType, counter);\r\n    counter++;\r\n}\r\nvfxTypeEnum.CreateType();\r\n\r\nassemblyBuilder.Save(dllFile);\r\n<\/code><\/pre>\n<h2>Creating Sprite Sheets<\/h2>\n<p>Using System.Drawing, we can load up all our images and tile them into sprite sheets (or atlases) with just a few lines of C#. This way the script can take all the files from the artist and sort them into a performance-friendly atlas for the engine to parse. It can also generate some simple JSON for both the editor and the engine to parse for simple information like the locations and sizes of each object in the atlases. Using a few APIs in .NET, we can load up all the images, sort them by size, and place them all into a series of atlases (sprite sheets):<\/p>\n<p>Here&#8217;s how we can load all the images and sort them by size:<\/p>\n<pre><code class=\"csharp\">foreach (string file in Directory.GetFiles(STUFFS_SOURCES_FOLDER, \"*.png\").ToList())\t\r\n{\t\r\n    FileInfo fileInfo = new FileInfo(file);\t\r\n    string stuffSlug = fileInfo.Name.Replace(fileInfo.Extension, \"\");\t\r\n    stuffImgs[stuffSlug] = Image.FromFile(file);\t\r\n}\t\r\nstuffImgs = stuffImgs.OrderByDescending(si =&gt; si.Value.Height).ThenByDescending(si =&gt; si.Value.Width).ToDictionary(si =&gt; si.Key, si =&gt; si.Value);\r\n<\/code><\/pre>\n<p>We can then loop through the images and place them in a series of atlases:<\/p>\n<pre><code class=\"csharp\">graphics.DrawImage(\r\n    image: image,\r\n    destRect: destRect,\r\n    srcX: srcRect.X,\r\n    srcY: srcRect.Y,\r\n    srcWidth: srcRect.Width,\r\n    srcHeight: srcRect.Height,\r\n    srcUnit: GraphicsUnit.Pixel,\r\n    imageAttrs: imageAttrs\r\n);\r\n<\/code><\/pre>\n<p>Once our atlas is ready, we trim it to the actual used size and export it:<\/p>\n<pre><code class=\"csharp\">Rectangle furthestX = stuffRects.Values.OrderByDescending(r =&gt; r.X + r.Width).ToArray()[0];\r\nRectangle furthestY = stuffRects.Values.OrderByDescending(r =&gt; r.Y + r.Height).ToArray()[0];\r\nbitmap = new Bitmap(furthestX.X + furthestX.Width + SPRITE_PADDING, furthestY.Y + furthestY.Height + SPRITE_PADDING);\r\ngraphics = Graphics.FromImage(bitmap);\r\nDrawImage(atlases.Last(), destRect: new Rectangle(0, 0, bitmap.Width, bitmap.Height), srcRect: new Rectangle(0, 0, bitmap.Width, bitmap.Height));\r\ngraphics.Save();\r\n<\/code><\/pre>\n<h2>Building MonoGame Assets From Sprite Sheets<\/h2>\n<p>We can also use System.IO and System.Diagnostics to generate and process a MGCB (MonoGame Content Builder) file for our assets:<\/p>\n<pre><code class=\"csharp\">static void BuildAssets()\r\n{\r\n    \/\/ create MGCB\r\n    File.WriteAllText(\"assets.mgcb\", GenFullMgcb());\r\n\r\n    \/\/ clean\/rebuild mgcb\r\n    Console.WriteLine(\"nnBuilding generated assets...n\");\r\n    ProcessStartInfo startInfo = new ProcessStartInfo\r\n    {\r\n        FileName = @\"mgcb.exe\",\r\n        Arguments = @\"\/@:assets.mgcb \/clean \/rebuild\",\r\n        UseShellExecute = false,\r\n    };\r\n    Process process = Process.Start(startInfo);\r\n    process.WaitForExit();\r\n}\r\n<\/code><\/pre>\n<h2>Using the Generated Files<\/h2>\n<p>Using System.Net, we can FTP into our VPS and upload the web assets:<\/p>\n<pre><code class=\"csharp\">using (WebClient client = new WebClient())\r\n{\r\n    string baseFtpPath = @\"ftp:\/\/domain.suf\/path\/to\/upload\/\";\r\n    client.Credentials = new NetworkCredential(\"USER\", \"PASS\");\r\n\r\n    Console.WriteLine(\"Uploading: dyn.css\");\r\n    client.UploadFile(baseFtpPath + \"dyn.css\", WebRequestMethods.Ftp.UploadFile, cssPath);\r\n    Console.WriteLine(\"Uploading: dyn.js\");\r\n    client.UploadFile(baseFtpPath + \"dyn.js\", WebRequestMethods.Ftp.UploadFile, jsPath);\r\n\r\n    foreach (string file in Directory.GetFiles(RESULTS_FOLDER + \"web\/stuffs\/\", \"*.png\"))\r\n    {\r\n        Console.WriteLine(\"Uploading: \" + file);\r\n        client.UploadFile(baseFtpPath + \"images\/stuffs\/\" + new FileInfo(file).Name, WebRequestMethods.Ftp.UploadFile, file);\r\n    }\r\n}\r\n<\/code><\/pre>\n<p>Using System.IO, we can also copy our assets over to the artist&#8217;s working environment:<\/p>\n<pre><code class=\"csharp\">File.Copy(RESULTS_FOLDER + \"DynEnums.dll\", \"..\/..\/KelsEnv\/DynEnums.dll\", overwrite: true);\r\n<\/code><\/pre>\n<h2>Check Out Cymatically Muffed<\/h2>\n<p>Hopefully through this article you can see how simple it can be to use .NET to create some powerful tools for your own workflow and increase your productivity dramatically!<\/p>\n<p><a href=\"https:\/\/muffed.kelsam.net\/\">Cymatically Muffed<\/a> is proudly created using MonoGame and .NET. It is available now for Windows PC via <a href=\"https:\/\/store.steampowered.com\/app\/661200\/Cymatically_Muffed\/\">Steam<\/a>, and is coming soon to Xbox One, MacOS, and Linux! MacOS and Linux coming soon thanks to MonoGame 3.8 supporting .NET Core 3.1, which allows us to compile our engine for other platforms with a single command!<\/p>\n<p>Game on!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Check out how a game studio used .NET to create a game art asset pipeline.<\/p>\n","protected":false},"author":48128,"featured_media":31252,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[685,756,7184],"tags":[4,78,7180],"class_list":["post-31251","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-dotnet","category-csharp","category-game-development","tag-net","tag-game-development","tag-monogame"],"acf":[],"blog_post_summary":"<p>Check out how a game studio used .NET to create a game art asset pipeline.<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts\/31251","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/users\/48128"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/comments?post=31251"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts\/31251\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/media\/31252"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/media?parent=31251"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/categories?post=31251"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/tags?post=31251"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}