示例#1
0
		public override Dictionary<string, FileOutput> Package(
			BuildContext buildContext,
			string projectId,
			Dictionary<string, ParseTree.Executable[]> finalCode,
			List<string> filesToCopyOver,
			ICollection<ParseTree.StructDefinition> structDefinitions,
			string inputFolder,
			SpriteSheetBuilder spriteSheet)
		{
			Dictionary<string, FileOutput> output = new Dictionary<string, FileOutput>();
			List<string> concatenatedCode = new List<string>();
			Dictionary<string, string> replacements = new Dictionary<string, string>()
			{
				{ "PROJECT_ID", projectId },
			};

			concatenatedCode.Add(this.GetPyGameCode("Header.py", replacements));
			concatenatedCode.Add(this.Translator.NL);
			concatenatedCode.Add(this.GetPyGameCode("AsyncHttpFetcher.py", replacements));
			concatenatedCode.Add(this.Translator.NL);
			this.Translator.TranslateGlobals(concatenatedCode, finalCode);
			concatenatedCode.Add(this.Translator.NL);
			this.Translator.TranslateSwitchLookups(concatenatedCode, finalCode);
			concatenatedCode.Add(this.Translator.NL);
			this.Translator.TranslateFunctions(concatenatedCode, finalCode);
			concatenatedCode.Add(this.Translator.NL);
			concatenatedCode.Add(this.GetPyGameCode("Footer.py", replacements));
			concatenatedCode.Add(this.Translator.NL);

			output["game.py"] = new FileOutput()
			{
				Type = FileOutputType.Text,
				TextContent = string.Join("", concatenatedCode)
			};

			foreach (string file in filesToCopyOver)
			{
				output[file] = new FileOutput()
				{
					Type = FileOutputType.Copy,
					RelativeInputPath = file,
				};
			}

			return output;
		}
示例#2
0
		public override Dictionary<string, FileOutput> Package(
			BuildContext buildContext,
			string projectId,
			Dictionary<string, ParseTree.Executable[]> finalCode,
			List<string> filesToCopyOver,
			ICollection<ParseTree.StructDefinition> structDefinitions,
			string inputFolder,
			SpriteSheetBuilder spriteSheet)
		{
			Dictionary<string, FileOutput> output = new Dictionary<string, FileOutput>();
			string package = "com." + projectId.ToLowerInvariant() + ".app";
			string pathToJavaCode = "app/src/main/java/" + package.Replace('.', '/');

			Dictionary<string, string> replacements = new Dictionary<string, string>() {
				{ "PROJECT_TITLE", projectId },
				{ "PROJECT_ID", projectId },
				{ "PACKAGE", package },
				{ "CURRENT_YEAR", DateTime.Now.Year.ToString() },
				{ "COPYRIGHT", "©" },
			};

			foreach (string simpleCopyText in new string[] {
				// Boilerplate Android project stuff
				"build.gradle|AndroidProject/Boilerplate/BuildGradle.txt",
				"gradle.properties|AndroidProject/Boilerplate/GradleProperties.txt",
				"gradlew|AndroidProject/Boilerplate/Gradlew.txt",
				"gradlew.bat|AndroidProject/Boilerplate/GradlewBat.txt",
				projectId + ".iml|AndroidProject/Boilerplate/ProjectIml.txt",
				"android.iml|AndroidProject/Boilerplate/AndroidIml.txt",
				"settings.gradle|AndroidProject/Boilerplate/SettingsGradle.txt",
				"gradle/wrapper/gradle-wrapper.jar|AndroidProject/Boilerplate/GradleWrapperJar",
				"gradle/wrapper/gradle-wrapper.properties|AndroidProject/Boilerplate/GradleWrapperProperties.txt",
				"app/app.iml|AndroidProject/Boilerplate/AppIml.txt",
				"app/build.gradle|AndroidProject/Boilerplate/AppBuildGradle.txt",
				"app/src/main/res/layout/activity_game.xml|AndroidProject/Boilerplate/ResLayoutActivityGameXml.txt",
				"app/src/main/res/values/attrs.xml|AndroidProject/Boilerplate/ResValuesAttrsXml.txt",
				"app/src/main/res/values/colors.xml|AndroidProject/Boilerplate/ResValuesColorsXml.txt",
				"app/src/main/res/values/strings.xml|AndroidProject/Boilerplate/ResValuesStringsXml.txt",
				"app/src/main/res/values/styles.xml|AndroidProject/Boilerplate/ResValuesStylesXml.txt",
				"app/src/main/res/values-v11/styles.xml|AndroidProject/Boilerplate/ResValuesV11StylesXml.txt",
				"app/src/main/res/drawable-hdpi/ic_launcher.png|AndroidProject/Boilerplate/ResDrawableHdpiIcLauncher.png",
				"app/src/main/res/drawable-mdpi/ic_launcher.png|AndroidProject/Boilerplate/ResDrawableMdpiIcLauncher.png",
				"app/src/main/res/drawable-xhdpi/ic_launcher.png|AndroidProject/Boilerplate/ResDrawableXhdpiIcLauncher.png",
				"app/src/main/res/drawable-xxhdpi/ic_launcher.png|AndroidProject/Boilerplate/ResDrawableXxhdpiIcLauncher.png",
				pathToJavaCode + "/util/SystemUiHider.java|AndroidProject/Boilerplate/JavaUtilSystemUiHider.txt",
				pathToJavaCode + "/util/SystemUiHiderBase.java|AndroidProject/Boilerplate/JavaUtilSystemUiHiderBase.txt",
				pathToJavaCode + "/util/SystemUiHiderHoneycomb.java|AndroidProject/Boilerplate/JavaUtilSystemUiHiderHoneycomb.txt",
				"app/src/main/AndroidManifest.xml|AndroidProject/Boilerplate/AndroidManifestXml.txt",
				"app/src/main/ic_launcher-web.png|AndroidProject/Boilerplate/IcLauncherWeb.png",
				".idea/copyright/profiles_settings.xml|AndroidProject/Boilerplate/Idea/CopyrightProfilesSettingsXml.txt",
				".idea/libraries/support_v4_18_0_0.xml|AndroidProject/Boilerplate/Idea/LibrariesSupportXml.txt",
				".idea/scopes/scope_settings.xml|AndroidProject/Boilerplate/Idea/ScopeSettingsXml.txt",
				".idea/.name|AndroidProject/Boilerplate/Idea/DotName.txt",
				".idea/compiler.xml|AndroidProject/Boilerplate/Idea/CompilerXml.txt",
				".idea/encodings.xml|AndroidProject/Boilerplate/Idea/EncodingsXml.txt",
				".idea/gradle.xml|AndroidProject/Boilerplate/Idea/GradleXml.txt",
				".idea/misc.xml|AndroidProject/Boilerplate/Idea/MiscXml.txt",
				".idea/modules.xml|AndroidProject/Boilerplate/Idea/ModulesXml.txt",
				".idea/vcs.xml|AndroidProject/Boilerplate/Idea/VcsXml.txt",
				".idea/workspace.xml|AndroidProject/Boilerplate/Idea/WorkspaceXml.txt",

				// Crayon Android stuff
				pathToJavaCode + "/AndroidTranslationHelper.java|AndroidProject/AndroidTranslationHelper.txt",
				pathToJavaCode + "/GlUtil.java|AndroidProject/GlUtil.txt",
				pathToJavaCode + "/GameActivity.java|AndroidProject/GameActivity.txt",
				pathToJavaCode + "/OpenGlRenderer.java|AndroidProject/OpenGlRenderer.txt",
				pathToJavaCode + "/CrayonGlRenderer.java|AndroidProject/CrayonGlRenderer.txt",
				pathToJavaCode + "/CrayonGlSurfaceView.java|AndroidProject/CrayonGlSurfaceView.txt",

				// Generic Crayon Java stuff
				pathToJavaCode + "/AsyncMessageQueue.java|Project/AsyncMessageQueue.txt",
				pathToJavaCode + "/TranslationHelper.java|Project/TranslationHelper.txt",
				pathToJavaCode + "/Image.java|Project/Image.txt",
				pathToJavaCode + "/JsonParser.java|Project/JsonParser.txt",
			}) {
				string[] parts = simpleCopyText.Split('|');
				string target = parts[0];
				string source = parts[1];
				bool isBinary = !source.EndsWith(".txt");
				if (isBinary)
				{
					output[target] = new FileOutput()
					{
						Type = FileOutputType.Binary,
						BinaryContent = Util.ReadBytesInternally("Translator/Java/" + source)
					};
				}
				else
				{
					string text = Util.ReadFileInternally("Translator/Java/" + source);
					output[target] = new FileOutput()
					{
						Type = FileOutputType.Text,
						TextContent = Constants.DoReplacements(text, replacements)
					};
				}
			}

			foreach (string basicFile in new string[] { 
				"AsyncMessageQueue",
				"TranslationHelper",
				//"Start",
				//"GameWindow",
				//"RenderEngine",
				"Image",
				"JsonParser"
			})
			{
				output[pathToJavaCode + "/" + basicFile + ".java"] = new FileOutput()
				{
					Type = FileOutputType.Text,
					TextContent = Constants.DoReplacements(
						Util.ReadFileInternally("Translator/Java/Project/" + basicFile + ".txt"),
						replacements)
				};
			}

			string[] items = finalCode.Keys.OrderBy<string, string>(s => s.ToLowerInvariant()).ToArray();

			List<string> crayonWrapper = new List<string>();
			crayonWrapper.Add(string.Join("\n",
				"package %%%PACKAGE%%%;",
				"",
				"import java.util.ArrayList;",
				"import java.util.HashMap;",
				"import java.util.Stack;",
				"",
				"final class CrayonWrapper {",
				"    private CrayonWrapper() {}",
				""));

			this.Translator.CurrentIndention++;
			foreach (string finalCodeKey in items)
			{
				this.Translator.Translate(crayonWrapper, finalCode[finalCodeKey]);
			}
			this.Translator.CurrentIndention--;

			crayonWrapper.Add(string.Join("\n",
				"}",
				""));

			output[pathToJavaCode + "/CrayonWrapper.java"] = new FileOutput()
			{
				Type = FileOutputType.Text,
				TextContent = Constants.DoReplacements(string.Join("", crayonWrapper), replacements)
			};

			string crayonHeader = string.Join(this.Translator.NL, new string[] {
					"package " + package + ";",
					"",
					"import java.util.ArrayList;",
					"import java.util.HashMap;",
					"import java.util.Stack;",
					"",
					""
				});


			string nl = this.Translator.NL;

			foreach (StructDefinition structDefinition in structDefinitions)
			{
				string structName = structDefinition.Name.Value;
				string filename = structName + ".java";

				List<string> codeContents = new List<string>();

				codeContents.Add("class " + structName + " {" + nl);
				codeContents.Add("    public " + structName + "(");
				List<string> types = new List<string>();
				for (int i = 0; i < structDefinition.FieldsByIndex.Length; ++i)
				{
					string type;
					Annotation typeAnnotation = structDefinition.Types[i];
					if (typeAnnotation == null)
					{
						throw new Exception("Are there any of these left?");
					}
					else
					{
						type = this.GetTypeStringFromAnnotation(typeAnnotation.FirstToken, typeAnnotation.GetSingleArgAsString(null), false, false);
					}
					types.Add(type);

					if (i > 0) codeContents.Add(", ");
					codeContents.Add(type);
					codeContents.Add(" v_" + structDefinition.FieldsByIndex[i]);
				}
				codeContents.Add(") {" + nl);

				for (int i = 0; i < structDefinition.FieldsByIndex.Length; ++i)
				{
					codeContents.Add("        this." + structDefinition.FieldsByIndex[i] + " = v_" + structDefinition.FieldsByIndex[i] + ";" + nl);
				}

				codeContents.Add("    }" + nl + nl);
				for (int i = 0; i < structDefinition.FieldsByIndex.Length; ++i)
				{
					codeContents.Add("    public ");
					codeContents.Add(types[i]);
					codeContents.Add(" " + structDefinition.FieldsByIndex[i] + ";" + nl);
				}

				codeContents.Add("}" + nl);

				string fileContents = string.Join("", codeContents);
				string header = "package " + package + ";" + nl + nl;

				bool useList = fileContents.Contains("ArrayList<");
				bool useHashMap = fileContents.Contains("HashMap<");
				bool useStack = fileContents.Contains("Stack<");
				if (useList || useHashMap || useStack)
				{
					if (useList) header += "import java.util.ArrayList;" + nl;
					if (useHashMap) header += "import java.util.HashMap;" + nl;
					if (useStack) header += "import java.util.Stack;" + nl;
					header += nl;
				}
				fileContents = header + fileContents;

				output[pathToJavaCode + "/" + filename] = new FileOutput()
				{
					Type = FileOutputType.Text,
					TextContent = fileContents
				};

				output["app/src/main/res/bytecode/ByteCode.txt"] = new FileOutput()
				{
					Type = FileOutputType.Text,
					TextContent = this.Context.ByteCodeString
				};
			}

			foreach (string file in filesToCopyOver)
			{
				System.Drawing.Bitmap bmpHack = null;
				if (file.ToLowerInvariant().EndsWith(".png"))
				{
					bmpHack = HackUtil.ReEncodePngImageForJava(System.IO.Path.Combine(inputFolder, file));
				}

				if (bmpHack != null)
				{
					output["app/src/main/res/images/" + file] = new FileOutput()
					{
						Type = FileOutputType.Image,
						Bitmap = bmpHack
					};
				}
				else
				{
					output["app/src/main/res/images/" + file] = new FileOutput()
					{
						Type = FileOutputType.Copy,
						RelativeInputPath = file
					};
				}
			}

			output["app/src/main/res/raw/bytes.txt"] = new FileOutput()
			{
				Type = FileOutputType.Text,
				TextContent = this.Context.ByteCodeString
			};

			return output;
		}
示例#3
0
		public override Dictionary<string, FileOutput> Package(
			BuildContext buildContext,
			string projectId,
			Dictionary<string, ParseTree.Executable[]> finalCode,
			List<string> filesToCopyOver,
			ICollection<ParseTree.StructDefinition> structDefinitions,
			string inputFolder,
			SpriteSheetBuilder spriteSheet)
		{
			Dictionary<string, FileOutput> output = new Dictionary<string, FileOutput>();

			Dictionary<string, string> replacements = new Dictionary<string, string>()
			{
				{ "JS_FILE_PREFIX", "'" + this.jsFolderPrefix + "'" },
				{ "PROJECT_ID", projectId },
			};

			output["index.html"] = new FileOutput()
			{
				Type = FileOutputType.Text,
				TextContent = this.GenerateHtmlFile()
			};

			List<string> codeJs = new List<string>();

			foreach (string jsFile in new string[] {
				"game_code.js",
				"input.js",
				"drawing.js",
				"sound.js",
				"file_io.js",
				"fake_disk.js",
				"http.js",
				"interpreter_helpers.js",
			})
			{
				codeJs.Add(Minify(Util.ReadFileInternally("Translator/JavaScript/Browser/" + jsFile)));
				codeJs.Add(this.Translator.NL);
			}

			foreach (string component in finalCode.Keys)
			{
				this.Translator.Translate(codeJs, finalCode[component]);
				codeJs.Add(this.Translator.NL);
			}

			string codeJsText = Constants.DoReplacements(string.Join("", codeJs), replacements);

			if (this.IsMin)
			{
				codeJsText = JavaScriptMinifier.Minify(codeJsText);
			}

			output["code.js"] = new FileOutput()
			{
				Type = FileOutputType.Text,
				TextContent = codeJsText
			};



			output["bytecode.js"] = new FileOutput()
			{
				Type = FileOutputType.Text,
				TextContent = string.Join("\n", new string[] {
					"var CRAYON = {};",
					"CRAYON.getByteCode = function() {",
					"\treturn \"" + this.Context.ByteCodeString + "\";",
					"};",
					""
				})
			};

			HashSet<string> binaryFileTypes = new HashSet<string>(
				"JPG PNG GIF JPEG BMP MP3 OGG".Split(' '));

			Dictionary<string, string> textResources = new Dictionary<string, string>();

			foreach (string file in filesToCopyOver)
			{
				string[] parts = file.Split('.');
				bool isBinary = file.Length > 1 && binaryFileTypes.Contains(parts[parts.Length - 1].ToUpperInvariant());

				if (isBinary)
				{
					output[file] = new FileOutput()
					{
						Type = FileOutputType.Copy,
						RelativeInputPath = file
					};
					textResources[file] = null;
				}
				else
				{
					textResources[file] = Util.ReadFileExternally(System.IO.Path.Combine(inputFolder, file), false);
				}
			}

			if (textResources.Count > 0)
			{
				output["resources.js"] = new FileOutput()
				{
					TextContent = BuildTextResourcesCodeFile(textResources),
					Type = FileOutputType.Text
				};
			}

			return output;
		}
示例#4
0
		public override Dictionary<string, FileOutput> Package(
			BuildContext buildContext,
			string projectId,
			Dictionary<string, ParseTree.Executable[]> finalCode,
			List<string> filesToCopyOver,
			ICollection<ParseTree.StructDefinition> structDefinitions,
			string inputFolder,
			SpriteSheetBuilder spriteSheet)
		{
			Dictionary<string, FileOutput> output = new Dictionary<string, FileOutput>();
			string package = projectId.ToLowerInvariant();

			Dictionary<string, string> replacements = new Dictionary<string, string>() {
				{ "PROJECT_TITLE", projectId },
				{ "PROJECT_ID", projectId },
				{ "PACKAGE", package },
				{ "CURRENT_YEAR", DateTime.Now.Year.ToString() },
				{ "COPYRIGHT", "©" },
			};

			foreach (string awtFile in new string[] { 
				"AwtTranslationHelper",
			})
			{
				output["src/" + package + "/" + awtFile + ".java"] = new FileOutput()
				{
					Type = FileOutputType.Text,
					TextContent = Constants.DoReplacements(
						Util.ReadFileInternally("Translator/Java/AwtProject/" + awtFile + ".txt"),
						replacements)
				};
			}

			foreach (string basicFile in new string[] { 
				"AsyncMessageQueue",
				"TranslationHelper",
				"Start",
				"GameWindow",
				"RenderEngine",
				"Image",
				"JsonParser"
			})
			{
				output["src/" + package + "/" + basicFile + ".java"] = new FileOutput()
				{
					Type = FileOutputType.Text,
					TextContent = Constants.DoReplacements(
						Util.ReadFileInternally("Translator/Java/Project/" + basicFile + ".txt"),
						replacements)
				};
			}

			foreach (string basicFile in new string[] { 
				"AwtTranslationHelper",
			})
			{
				output["src/" + package + "/" + basicFile + ".java"] = new FileOutput()
				{
					Type = FileOutputType.Text,
					TextContent = Constants.DoReplacements(
						Util.ReadFileInternally("Translator/Java/AwtProject/" + basicFile + ".txt"),
						replacements)
				};
			}

			string[] items = finalCode.Keys.OrderBy<string, string>(s => s.ToLowerInvariant()).ToArray();

			List<string> crayonWrapper = new List<string>();
			crayonWrapper.Add(string.Join("\n",
				"package %%%PACKAGE%%%;",
				"",
				"import java.util.ArrayList;",
				"import java.util.HashMap;",
				"import java.util.Stack;",
				"",
				"final class CrayonWrapper {",
				"    private CrayonWrapper() {}",
				""));

			this.Translator.CurrentIndention++;
			foreach (string finalCodeKey in items)
			{
				this.Translator.Translate(crayonWrapper, finalCode[finalCodeKey]);
			}
			this.Translator.CurrentIndention--;

			crayonWrapper.Add(string.Join("\n",
				"}",
				""));

			output["src/" + package + "/CrayonWrapper.java"] = new FileOutput()
			{
				Type = FileOutputType.Text,
				TextContent = Constants.DoReplacements(string.Join("", crayonWrapper), replacements)
			};

			string crayonHeader = string.Join(this.Translator.NL, new string[] {
					"package " + package + ";",
					"",
					"import java.util.ArrayList;",
					"import java.util.HashMap;",
					"import java.util.Stack;",
					"",
					""
				});


			string nl = this.Translator.NL;

			foreach (StructDefinition structDefinition in structDefinitions)
			{
				string structName = structDefinition.Name.Value;
				string filename = structName + ".java";

				List<string> codeContents = new List<string>();

				codeContents.Add("class " + structName + " {" + nl);
				codeContents.Add("    public " + structName + "(");
				List<string> types = new List<string>();
				for (int i = 0; i < structDefinition.FieldsByIndex.Length; ++i)
				{
					string type;
					Annotation typeAnnotation = structDefinition.Types[i];
					if (typeAnnotation == null)
					{
						throw new Exception("Are there any of these left?");
					}
					else
					{
						type = this.GetTypeStringFromAnnotation(typeAnnotation.FirstToken, typeAnnotation.GetSingleArgAsString(null), false, false);
					}
					types.Add(type);

					if (i > 0) codeContents.Add(", ");
					codeContents.Add(type);
					codeContents.Add(" v_" + structDefinition.FieldsByIndex[i]);
				}
				codeContents.Add(") {" + nl);

				for (int i = 0; i < structDefinition.FieldsByIndex.Length; ++i)
				{
					codeContents.Add("        this." + structDefinition.FieldsByIndex[i] + " = v_" + structDefinition.FieldsByIndex[i] + ";" + nl);
				}

				codeContents.Add("    }" + nl + nl);
				for (int i = 0; i < structDefinition.FieldsByIndex.Length; ++i)
				{
					codeContents.Add("    public ");
					codeContents.Add(types[i]);
					codeContents.Add(" " + structDefinition.FieldsByIndex[i] + ";" + nl);
				}

				codeContents.Add("}" + nl);

				string fileContents = string.Join("", codeContents);
				string header = "package " + package + ";" + nl + nl;

				bool useList = fileContents.Contains("ArrayList<");
				bool useHashMap = fileContents.Contains("HashMap<");
				bool useStack = fileContents.Contains("Stack<");
				if (useList || useHashMap || useStack)
				{
					if (useList) header += "import java.util.ArrayList;" + nl;
					if (useHashMap) header += "import java.util.HashMap;" + nl;
					if (useStack) header += "import java.util.Stack;" + nl;
					header += nl;
				}
				fileContents = header + fileContents;

				output["src/" + package + "/" + filename] = new FileOutput()
				{
					Type = FileOutputType.Text,
					TextContent = fileContents
				};
			}

			output["data/ByteCode.txt"] = new FileOutput()
			{
				Type = FileOutputType.Text,
				TextContent = this.Context.ByteCodeString
			};

			foreach (string file in filesToCopyOver)
			{
				System.Drawing.Bitmap bmpHack = null;
				if (file.ToLowerInvariant().EndsWith(".png"))
				{
					bmpHack = HackUtil.ReEncodePngImageForJava(System.IO.Path.Combine(inputFolder, file));
				}

				if (bmpHack != null)
				{
					output["resources/" + file] = new FileOutput()
					{
						Type = FileOutputType.Image,
						Bitmap = bmpHack
					};
				}
				else
				{
					output["resources/" + file] = new FileOutput()
					{
						Type = FileOutputType.Copy,
						RelativeInputPath = file
					};
				}
			}

			output["build.xml"] = new FileOutput()
			{
				Type = FileOutputType.Text,
				TextContent = Constants.DoReplacements(
					Util.ReadFileInternally("Translator/Java/Project/BuildXml.txt"),
					replacements)
			};

			return output;
		}
示例#5
0
		public override Dictionary<string, FileOutput> Package(
			BuildContext buildContext,
			string projectId,
			Dictionary<string, Executable[]> finalCode,
			List<string> filesToCopyOver,
			ICollection<StructDefinition> structDefinitions,
			string inputFolder,
			SpriteSheetBuilder spriteSheet)
		{
			string guid = Guid.NewGuid().ToString();
			string guid2 = Guid.NewGuid().ToString();

			Dictionary<string, string> replacements = new Dictionary<string, string>() {
				{ "PROJECT_GUID", guid },
				{ "ASSEMBLY_GUID", guid2 },
				{ "PROJECT_TITLE", projectId },
				{ "PROJECT_ID", projectId },
				{ "CURRENT_YEAR", DateTime.Now.Year.ToString() },
				{ "COPYRIGHT", "©" },
				{ "EXTRA_DLLS", "" },
			};
			this.ApplyPlatformSpecificReplacements(replacements);

			HashSet<string> systemLibraries = new HashSet<string>(new string[] {
				"System",
				"System.Core",
				"System.Drawing",
				"System.Xml",
				"System.Xml.Linq",
				"Microsoft.CSharp"
			});

			this.AddPlatformSpecificSystemLibraries(systemLibraries);
			List<string> systemLibrariesStringBuilder = new List<string>();
			foreach (string library in systemLibraries.OrderBy<string, string>(s => s.ToLowerInvariant()))
			{
				systemLibrariesStringBuilder.Add("    <Reference Include=\"" + library + "\" />");
			}
			replacements["SYSTEM_LIBRARIES"] = string.Join("\r\n", systemLibrariesStringBuilder);

			Dictionary<string, FileOutput> output = new Dictionary<string, FileOutput>();
			List<string> compileTargets = new List<string>();

			// Get embedded resource list
			List<string> embeddedResources = this.GetEmbeddedResources(projectId, output, filesToCopyOver);

			// Code files that are templated
			Dictionary<string, string> directFileCopies = new Dictionary<string, string>()
			{
				{ "SolutionFile.txt", projectId + ".sln" },
				{ "ProjectFile.txt", projectId + ".csproj" },
				{ "ProgramCs.txt", "Program.cs" },
				{ "AssemblyInfo.txt", "Properties/AssemblyInfo.cs" },
				{ "JsonParser.txt", "JsonParser.cs" },
				{ "TranslationHelper.txt", "TranslationHelper.cs" },
				{ "GamepadTranslationHelper.txt", "GamepadTranslationHelper.cs" },
				{ "ResourceReader.txt", "ResourceReader.cs" },
				{ "AsyncMessageQueue.txt", "AsyncMessageQueue.cs" },
			};

			// Create a list of compiled C# files
			foreach (string finalFilePath in directFileCopies.Values.Where<string>(f => f.EndsWith(".cs")))
			{
				compileTargets.Add(finalFilePath.Replace('/', '\\'));
			}

			string crayonHeader = string.Join(this.Translator.NL, new string[] {
					"using System;",
					"using System.Collections.Generic;",
					"using System.Linq;",
					"using OpenTK.Graphics.OpenGL;",
					"",
					"namespace " + projectId,
					"{",
					""
				});

			string crayonWrapperHeader = string.Join(this.Translator.NL, new string[] {
					crayonHeader + "\tinternal partial class CrayonWrapper",
					"\t{",
					""
				});

			string crayonFooter = "}" + this.Translator.NL;
			string crayonWrapperFooter = "\t}" + this.Translator.NL + crayonFooter;

			// Add files for specific C# platform
			this.PlatformSpecificFiles(projectId, compileTargets, output, replacements);

			string nl = this.Translator.NL;

			foreach (StructDefinition structDefinition in structDefinitions)
			{
				string structName = structDefinition.Name.Value;
				string filename = structName + ".cs";
				compileTargets.Add(filename);
				List<string> codeContents = new List<string>();
				codeContents.Add(crayonHeader);
				codeContents.Add("\tpublic class " + structName + nl);
				codeContents.Add("\t{" + nl);
				codeContents.Add("\t\tpublic " + structName + "(");
				List<string> types = new List<string>();
				for (int i = 0; i < structDefinition.FieldsByIndex.Length; ++i)
				{
					string type;
					Annotation typeAnnotation = structDefinition.Types[i];
					if (typeAnnotation == null)
					{
						type = "object";
					}
					else
					{
						type = this.GetTypeStringFromAnnotation(typeAnnotation.FirstToken, typeAnnotation.GetSingleArgAsString(null));
					}
					types.Add(type);

					if (i > 0) codeContents.Add(", ");
					codeContents.Add(type);
					codeContents.Add(" v_" + structDefinition.FieldsByIndex[i]);
				}
				codeContents.Add(")" + nl);

				codeContents.Add("\t\t{" + nl);

				for (int i = 0; i < structDefinition.FieldsByIndex.Length; ++i)
				{
					codeContents.Add("\t\t\tthis." + structDefinition.FieldsByIndex[i] + " = v_" + structDefinition.FieldsByIndex[i] + ";" + nl);
				}

				codeContents.Add("\t\t}" + nl + nl);
				for (int i = 0; i < structDefinition.FieldsByIndex.Length; ++i)
				{
					codeContents.Add("\t\tpublic ");
					codeContents.Add(types[i]);
					codeContents.Add(" " + structDefinition.FieldsByIndex[i] + ";" + nl);
				}

				codeContents.Add("\t}" + nl);

				codeContents.Add(crayonFooter);
				output[projectId + "/" + filename] = new FileOutput()
				{
					Type = FileOutputType.Text,
					TextContent = string.Join("", codeContents)
				};
			}

			foreach (string codefile in finalCode.Keys)
			{
				List<string> codeContents = new List<string>();

				codeContents.Add(crayonWrapperHeader);
				this.Translator.CurrentIndention = 2;

				this.Translator.Translate(codeContents, finalCode[codefile]);

				codeContents.Add(crayonWrapperFooter);

				string filename = codefile + ".cs";
				compileTargets.Add(filename);
				output[projectId + "/" + filename] = new FileOutput()
				{
					Type = FileOutputType.Text,
					TextContent = string.Join("", codeContents)
				};
			}

			// Create the actual compile targets in the .csproj file
			List<string> compileTargetCode = new List<string>();
			foreach (string compileTarget in compileTargets)
			{
				compileTargetCode.Add("    <Compile Include=\"" + compileTarget.Replace('/', '\\') + "\" />\r\n");
			}
			compileTargetCode.Add("    <EmbeddedResource Include=\"ByteCode.txt\" />\r\n");
			foreach (string embeddedResource in embeddedResources)
			{
				compileTargetCode.Add("    <EmbeddedResource Include=\"" + embeddedResource.Replace('/', '\\') + "\" />\r\n");
			}

			foreach (string spriteSheetImage in spriteSheet.FinalPaths)
			{
				// TODO: need a better system of putting things in predefined destinations, rather than hacking it between states
				// in this fashion.
				string path = spriteSheetImage.Substring("%PROJECT_ID%".Length + 1).Replace('/', '\\');
				compileTargetCode.Add("    <EmbeddedResource Include=\"" + path + "\" />\r\n");
			}

			replacements["COMPILE_TARGETS"] = string.Join("", compileTargetCode);

			// Copy templated files over with proper replacements
			foreach (string templateFile in directFileCopies.Keys)
			{
				string finalFilePath = directFileCopies[templateFile];
				string outputFilePath = finalFilePath.EndsWith(".sln") ? finalFilePath : (projectId + "/" + finalFilePath);
				output[outputFilePath] = new FileOutput()
				{
					Type = FileOutputType.Text,
					TextContent = Constants.DoReplacements(
						Util.ReadFileInternally("Translator/CSharp/Project/" + templateFile),
						replacements)
				};
			}

			output[projectId + "/ByteCode.txt"] = new FileOutput()
			{
				Type = FileOutputType.Text,
				TextContent = this.Context.ByteCodeString
			};

			return output;
		}
示例#6
0
		private List<string> GetEmbeddedResources(string projectId, Dictionary<string, FileOutput> output, List<string> filesToCopyOver)
		{
			List<string> embeddedResources = new List<string>();
			foreach (string file in filesToCopyOver)
			{
				string filename = "Files/" + file;
				embeddedResources.Add(filename);
				output[projectId + "/" + filename] = new FileOutput()
				{
					Type = FileOutputType.Copy,
					RelativeInputPath = file
				};
			}
			return embeddedResources;
		}
 // Cleanup
 internal void Flush()
 {
     if (spkOut != null) { spkOut.flush(); spkOut = null; }
     if (spkOutRaw != null) { spkOutRaw.flush(); spkOutRaw = null; }
     if (spkOutSalpa != null) { spkOutSalpa.flush(); spkOutSalpa = null; }
     if (rawOut != null) { rawOut.flush(); rawOut = null; }
     if (salpaOut != null) { salpaOut.flush(); salpaOut = null; }
     if (spkFiltOut != null) { spkFiltOut.flush(); spkFiltOut = null; }
     if (lfpOut != null) { lfpOut.flush(); lfpOut = null; };
     if (stimOut != null) { stimOut.flush(); stimOut = null; }
     if (auxAnalogOut != null) { auxAnalogOut.flush(); auxAnalogOut = null; };
     if (auxDigitalOut != null) { auxDigitalOut.flush(); auxDigitalOut = null; }
 }
        // For full sampled streams
        internal void Setup(string dataType, Task dataTask)
        {
            //Create the nessesary file writers
            switch (dataType)
            {
                case "raw":
                    // Check if we need to create this stream
                    if (recordRaw)
                    {
                        if (numElectrodes == 64 && Properties.Settings.Default.ChannelMapping == "invitro")
                            rawOut = new FileOutputRemapped(fid, numElectrodes,
                                dataTask.Timing.SampleClockRate, 1, dataTask,
                                "." + dataType, Properties.Settings.Default.PreAmpGain);
                        else
                            rawOut = new FileOutput(fid, numElectrodes,
                                dataTask.Timing.SampleClockRate, 1, dataTask,
                                "." + dataType, Properties.Settings.Default.PreAmpGain);
                    }
                    break;
                case "salpa":
                    // Check if we need to create this stream
                    if (recordSALPA)
                    {
                        if (numElectrodes == 64 && Properties.Settings.Default.ChannelMapping == "invitro")
                            salpaOut = new FileOutputRemapped(fid, numElectrodes,
                                dataTask.Timing.SampleClockRate, 1, dataTask,
                                "." + dataType, Properties.Settings.Default.PreAmpGain);
                        else
                            salpaOut = new FileOutput(fid, numElectrodes,
                                dataTask.Timing.SampleClockRate, 1, dataTask,
                                "." + dataType, Properties.Settings.Default.PreAmpGain);
                    }
                    break;
                case "spkflt":
                    // Check if we need to create this stream
                    if (recordSpikeFilt)
                    {
                        if (numElectrodes == 64 && Properties.Settings.Default.ChannelMapping == "invitro")
                            spkFiltOut = new FileOutputRemapped(fid, numElectrodes,
                                dataTask.Timing.SampleClockRate, 1, dataTask,
                                "." + dataType, Properties.Settings.Default.PreAmpGain);
                        else
                            spkFiltOut = new FileOutput(fid, numElectrodes,
                                dataTask.Timing.SampleClockRate, 1, dataTask,
                                "." + dataType, Properties.Settings.Default.PreAmpGain);
                    }
                    break;
                case "stim":
                    // Check if we need to create this stream
                    if (recordStim)
                    {
                        stimOut = new StimFileOutput(fid, dataTask.Timing.SampleClockRate,
                            "." + dataType);
                    }
                    break;

                case "aux":
                    // Check if we need to create this stream
                    if (recordAuxAnalog)
                    {
                        auxAnalogOut = new FileOutput(fid, dataTask.AIChannels.Count,
                            dataTask.Timing.SampleClockRate, 0, dataTask,
                            "." + dataType, 1);
                    }
                    break;

                case "dig":
                    // Check if we need to create this stream
                    if (recordAuxDig)
                    {
                        auxDigitalOut = new DigFileOutput(fid,dataTask.Timing.SampleClockRate,
                            "." + dataType);
                    }
                    break;

                default:
                    Console.WriteLine("Unknown data type specified during RecordingSetup.Setup()");
                    break;
            }
        }
        // For down-sampled, raw-type streams or streams that are potentially sub-tasks of other tasks
        internal void Setup(string dataType, Task dataTask, double extraInt)
        {
            //Create the nessesary file writers
            switch (dataType)
            {
                case "lfp":
                    // Check if we need to create this stream
                    if (recordLFP)
                    {
                        if (Properties.Settings.Default.SeparateLFPBoard)
                            lfpOut = new FileOutput(fid, numElectrodes, extraInt, 1, dataTask,
                                         "." + dataType, Properties.Settings.Default.PreAmpGain);
                        else
                        {
                            if (numElectrodes == 64 && Properties.Settings.Default.ChannelMapping == "invitro")
                                lfpOut = new FileOutputRemapped(fid, numElectrodes, extraInt, 1, dataTask,
                                    "." + dataType, Properties.Settings.Default.PreAmpGain);
                            else
                                lfpOut = new FileOutput(fid, numElectrodes, extraInt, 1, dataTask,
                                    "." + dataType, Properties.Settings.Default.PreAmpGain);
                        }
                    }
                    break;
                case "eeg":
                    // Check if we need to create this stream
                    if (recordEEG)
                    {
                        if (numElectrodes == 64 && Properties.Settings.Default.ChannelMapping == "invitro")
                            eegOut = new FileOutputRemapped(fid, numElectrodes, extraInt, 1, dataTask,
                                "." + dataType, Properties.Settings.Default.PreAmpGain);
                        else
                            eegOut = new FileOutput(fid, numElectrodes, extraInt, 1, dataTask,
                                    "." + dataType, Properties.Settings.Default.PreAmpGain);
                    }
                    break;
                case "aux":
                    // Check if we need to create this stream
                    if (recordAuxAnalog)
                    {
                        auxAnalogOut = new FileOutput(fid, (int)extraInt,
                            dataTask.Timing.SampleClockRate, 0, dataTask,
                            "." + dataType, 1);
                    }
                    break;
                default:
                    Console.WriteLine("Unknown data type specified during RecordingSetup.Setup()");
                    break;

            }
        }