private Campaign CreateCampaign() { // Determine a title var title = m_mod.Title; var shortTitle = title.ToSafeAssetName(true); // Determine an asset path int i = 2; var assetPath = AssetPath.Combine("campaigns", shortTitle + ".campaign"); while (File.Exists(Path.Combine(m_mod.Path, "assets/" + assetPath))) { assetPath = AssetPath.Combine("campaigns", shortTitle + i + ".campaign"); ++i; } // Save the file out var fullPath = Path.Combine(m_mod.Path, "assets/" + assetPath); var newCampaign = new Campaign(assetPath); newCampaign.Title = title; newCampaign.Save(fullPath); // Load the new campaign Assets.Reload(assetPath); return(Campaign.Get(assetPath)); }
public string GetAtlasPath(string atlasChain, int index) { var path = AssetPath.Combine( "Atlases" + atlasesPostfix, atlasChain + '.' + index.ToString("000") + GetPlatformTextureExtension()); return(path); }
public static string InvalidateFontsAction() { if (AppDomain.CurrentDomain.FriendlyName.Contains("Orange")) { return("Run this command from Tangerine!"); } foreach (var configPath in EnumerateFontConfigs(AssetPath.Combine(The.Workspace.AssetsDirectory, "Fonts/"))) { Console.WriteLine($"Processing {configPath}.."); try { var tftPath = Path.ChangeExtension(configPath, "tft"); if ( File.Exists(tftPath) && new System.IO.FileInfo(configPath).LastWriteTime <= new System.IO.FileInfo(tftPath).LastWriteTime ) { Console.WriteLine($"{tftPath} is up to date."); continue; } FontGenerator.UpdateCharSetsAndGenerateFont( new Uri(The.Workspace.AssetsDirectory + "\\").MakeRelativeUri(new Uri(configPath)).OriginalString, The.Workspace.AssetsDirectory ); } catch (Exception e) { Console.WriteLine($"Failed to generate font using {configPath} config"); Console.WriteLine(e); } } return(null); }
public static Bitmap OpenAtlasItemBitmapAndRescaleIfNeeded(TargetPlatform platform, AtlasItem item) { var srcTexturePath = AssetPath.Combine(The.Workspace.AssetsDirectory, Path.ChangeExtension(item.Path, item.SourceExtension)); Bitmap bitmap; using (var stream = File.OpenRead(srcTexturePath)) { bitmap = new Bitmap(stream); } if (item.BitmapInfo == null) { if (ShouldDownscale(platform, bitmap, item.CookingRules)) { var newBitmap = DownscaleTexture(platform, bitmap, srcTexturePath, item.CookingRules); bitmap.Dispose(); bitmap = newBitmap; } // Ensure that no image exceeded maxAtlasSize limit DownscaleTextureToFitAtlas(ref bitmap, srcTexturePath); } else if (bitmap.Width != item.BitmapInfo.Width || bitmap.Height != item.BitmapInfo.Height) { var newBitmap = bitmap.Rescale(item.BitmapInfo.Width, item.BitmapInfo.Height); bitmap.Dispose(); bitmap = newBitmap; } return(bitmap); }
public static string GetPromptImagePath(this GamepadJoystick axis, GamepadType type) { if (type == GamepadType.Unknown) { type = GamepadType.Xbox360; } string buttonName; switch (axis) { case GamepadJoystick.Left: { buttonName = "left_stick"; break; } case GamepadJoystick.Right: { buttonName = "right_stick"; break; } default: { buttonName = axis.ToString().ToLowerUnderscored(); break; } } return(AssetPath.Combine( "gui/prompts/" + type.ToString().ToLowerUnderscored(), buttonName + ".png" )); }
private void Preprocess(StringBuilder output, IFileStore store, string directory, string path, int fileNumber) { int lineNumber = 0; output.AppendLine("#line " + lineNumber + " " + fileNumber); string fullPath = AssetPath.Combine(directory, path); using (var stream = store.OpenFile(fullPath)) { var reader = new StreamReader(stream, Encoding.UTF8); string line; while ((line = reader.ReadLine()) != null) { if (line.StartsWith("#include")) { var includePath = line.Substring("#include".Length).Trim(); if (includePath.StartsWith("\"") && includePath.EndsWith("\"")) { includePath = includePath.Substring(1, includePath.Length - 2); } Preprocess(output, store, directory, includePath, fileNumber + 1); output.AppendLine("#line " + (lineNumber + 1) + " " + fileNumber); } else { output.AppendLine(line); } lineNumber++; } } }
internal static bool TryGetSettings(out ApexSettings settings) { if (_instance != null) { settings = _instance; return(true); } var apexRoot = AssetPath.GetApexRoot(false); var dataFolder = AssetPath.GetApexDataFolder(false); var relativeDataFolder = AssetPath.GetApexDataFolder(true); string settingsPath = AssetPath.Combine(relativeDataFolder, "ApexSettings.asset"); AssetPath.EnsurePath(relativeDataFolder); _instance = AssetDatabase.LoadAssetAtPath(settingsPath, typeof(ApexSettings)) as ApexSettings; bool settingsFound = (_instance != null); if (!settingsFound) { _instance = ScriptableObject.CreateInstance <ApexSettings>(); AssetDatabase.CreateAsset(_instance, settingsPath); AssetDatabase.SaveAssets(); } _instance.rootFolder = apexRoot; _instance.dataFolder = dataFolder; _instance.relativeDataFolder = relativeDataFolder; settings = _instance; return(settingsFound); }
private void DeleteCampaign(Campaign campaign, Mod mod) { var dialog = DialogBox.CreateQueryBox( Game.Screen, Game.Language.Translate("menus.delete_mod_prompt.title"), Game.Language.Translate("menus.delete_mod_prompt.info", campaign.Title), new string[] { Game.Language.Translate("menus.yes"), Game.Language.Translate("menus.no"), }, true ); dialog.OnClosed += delegate(object sender2, DialogBoxClosedEventArgs e) { switch (e.Result) { case 0: { // YES // Delete the campaign var assetPath = campaign.Path; var fullPath = Path.Combine(mod.Path, "assets/" + assetPath); File.Delete(fullPath); // Delete the levels and their thumbnails for (int i = 0; i < campaign.Levels.Count; ++i) { var levelPath = campaign.Levels[i]; var fullLevelPath = Path.Combine(mod.Path, "assets/" + levelPath); if (File.Exists(fullLevelPath)) { File.Delete(fullLevelPath); } var thumbnailPath = AssetPath.ChangeExtension(levelPath, "png"); var fullThumbnailPath = AssetPath.Combine(mod.Path, "assets/" + thumbnailPath); if (File.Exists(fullThumbnailPath)) { File.Delete(fullThumbnailPath); } } // Unload the campaign Assets.Reload(assetPath); var sources = Assets.GetSources(assetPath); if (sources.Count == 0 || (sources.Count == 1 && sources.First() == m_mod.Assets)) { Assets.Unload(assetPath); } m_campaigns.Refresh(); break; } } }; ShowDialog(dialog); }
protected string GetCompilerSpecific(string path) { if (string.IsNullOrEmpty(path)) { return(null); } //We only look for the specific response file in the folder. var responseFilePath = AssetPath.Combine(path, ResponseFileName); if (File.Exists(responseFilePath)) { return(responseFilePath); } return(null); }
private bool ChangeStorageFolder(string proposedFolder) { if (string.Equals(proposedFolder, _storagePath, StringComparison.OrdinalIgnoreCase) || !AssetPath.IsProjectPath(proposedFolder)) { return(false); } proposedFolder = AssetPath.ProjectRelativePath(proposedFolder); bool apexified = proposedFolder.EndsWith("Resources/" + AIManager.StorageFolder); if (!proposedFolder.EndsWith("Resources") && !apexified) { EditorUtility.DisplayDialog("Invalid Storage Folder", "The storage folder selected must be a Resources folder. This can however be anywhere inside the Assets folder.", "Ok"); return(false); } if (!apexified) { proposedFolder = AssetPath.Combine(proposedFolder, AIManager.StorageFolder); } AssetPath.EnsurePath(proposedFolder); //Move files from current storage location to new location. var fullStoragePath = AssetPath.GetFullPath(_storagePath); if (Directory.Exists(fullStoragePath)) { foreach (var asset in Directory.GetFiles(fullStoragePath, "*.asset", SearchOption.TopDirectoryOnly)) { var fileName = Path.GetFileName(asset); var msg = AssetDatabase.MoveAsset(AssetPath.ProjectRelativePath(asset), AssetPath.Combine(proposedFolder, fileName)); if (!string.IsNullOrEmpty(msg)) { EditorUtility.DisplayDialog("Error Moving Assets", msg, "Ok"); return(false); } } AssetDatabase.DeleteAsset(_storagePath); } _storagePath = proposedFolder; return(true); }
internal void Save(string newName) { if (_ai == null || _ai.rootSelector == null) { return; } // new name is not null or empty when using 'Save As' if (!string.IsNullOrEmpty(newName)) { this.name = StoredAIs.EnsureValidName(newName, _aiStorage); // If we are saving under a new name (as opposed to saving a new AI), we need to save copy of the current AI with new Ids. if (_aiStorage != null) { _aiStorage = null; _ai.RegenerateIds(); } } bool saveNew = (_aiStorage == null); if (saveNew) { _aiStorage = AIStorage.Create(_ai.id.ToString(), this.name); StoredAIs.AIs.Add(_aiStorage); AssetPath.EnsurePath(AIGeneralSettings.instance.storagePath); var assetPath = AssetPath.Combine(AIGeneralSettings.instance.storagePath, this.name + ".asset"); AssetDatabase.CreateAsset(_aiStorage, assetPath); } _aiStorage.version = _aiVersion.version; _aiStorage.configuration = SerializationMaster.Serialize(_ai); _aiStorage.editorConfiguration = GuiSerializer.Serialize(this.canvas); EditorUtility.SetDirty(_aiStorage); AssetDatabase.SaveAssets(); this.isDirty = false; _undoRedo.SetSavePoint(); if (saveNew && UserSettings.instance.autoGenerateNameMap) { AINameMapGenerator.WriteNameMapFile(); } }
private void CreateCampaign() { string suggestedTitle = m_mod.Title; var count = m_campaigns.Count; if (count > 0) { suggestedTitle = suggestedTitle + " Act " + (count + 1); } var textEntry = TextEntryDialogBox.Create(Game.Language.Translate("menus.name_campaign_prompt.title"), suggestedTitle, "", Game.Screen.Width - 300.0f, new string[] { Game.Language.Translate("menus.ok"), Game.Language.Translate("menus.cancel") }); textEntry.OnClosed += delegate(object sender2, DialogBoxClosedEventArgs e2) { if (e2.Result == 0) { // Determine a title var title = (textEntry.EnteredText.Trim().Length > 0) ? textEntry.EnteredText.Trim() : suggestedTitle; var shortTitle = title.ToSafeAssetName(true); // Determine an asset path int i = 2; var assetPath = AssetPath.Combine("campaigns", shortTitle + ".campaign"); while (File.Exists(Path.Combine(m_mod.Path, "assets/" + assetPath))) { assetPath = AssetPath.Combine("campaigns", shortTitle + i + ".campaign"); ++i; } // Save the file out var fullPath = Path.Combine(m_mod.Path, "assets/" + assetPath); var newCampaign = new Campaign(assetPath); newCampaign.Title = title; newCampaign.Save(fullPath); // Load the new campaign Assets.Reload(assetPath); OpenCampaign(Campaign.Get(assetPath), m_mod); } }; ShowDialog(textEntry); }
public static string InvalidateFontsAction() { foreach (var configPath in EnumerateFontConfigs(AssetPath.Combine(The.Workspace.AssetsDirectory, "Fonts/"))) { Console.WriteLine($"Processing {configPath}.."); try { var tftPath = Path.ChangeExtension(configPath, "tft"); FontGenerator.UpdateCharSetsAndGenerateFont( new Uri(The.Workspace.AssetsDirectory + "\\").MakeRelativeUri(new Uri(configPath)).OriginalString, The.Workspace.AssetsDirectory ); } catch (Exception e) { Console.WriteLine($"Failed to generate font using {configPath} config"); Console.WriteLine(e); } } return(null); }
protected string GetDefaultResponseFiles() { var rootResponseFilePath = AssetPath.Combine(ProjectPath, k_AssetsFolder, ResponseFileName); if (File.Exists(rootResponseFilePath)) { return(rootResponseFilePath); } foreach (var obsoleteResponseFileName in ObsoleteResponseFileNames) { var obsoleteResponseFilePath = AssetPath.Combine(ProjectPath, k_AssetsFolder, obsoleteResponseFileName); if (File.Exists(obsoleteResponseFilePath)) { return(obsoleteResponseFilePath); } } return(null); }
internal static void WriteNameMapFile() { var targetFolder = AIGeneralSettings.instance.nameMapPath; if (string.IsNullOrEmpty(targetFolder)) { targetFolder = AssetPath.GetApexRoot(true); AIGeneralSettings.instance.nameMapPath = targetFolder; AIGeneralSettings.instance.SaveChanges(); } targetFolder = AssetPath.GetFullPath(targetFolder); if (!Directory.Exists(targetFolder)) { Debug.LogWarning("Unable to create name map, please setup a target folder under settings."); return; } var filePath = AssetPath.Combine(targetFolder, AIGeneralSettings.NameMapFileName); var b = new StringBuilder(); var aiList = StoredAIs.AIs; var count = aiList.count; for (int i = 0; i < count; i++) { var name = correctName(aiList[i].name); if (name != null) { b.AppendFormat(Template.ItemTemplate, name, aiList[i].aiId); b.AppendLine(); } } using (var writer = new StreamWriter(filePath)) { writer.WriteLine(Template.FileTemplate, b); } AssetDatabase.Refresh(); }
public List <string> Get(string folderToLookForResponseFilesIn) { if (!string.IsNullOrEmpty(folderToLookForResponseFilesIn) && !Path.IsPathRooted(folderToLookForResponseFilesIn)) { folderToLookForResponseFilesIn = AssetPath.Combine(ProjectPath, folderToLookForResponseFilesIn); } var result = new List <string>(); var folderResponseFile = GetCompilerSpecific(folderToLookForResponseFilesIn); if (!string.IsNullOrEmpty(folderResponseFile)) { AddIfNotNull(result, folderResponseFile); } else { AddIfNotNull(result, GetDefaultResponseFiles()); } return(result); }
internal static void WriteContextFiles(string nameSpace) { if (string.IsNullOrEmpty(nameSpace)) { nameSpace = "MyNamespace"; } var filePath = AssetPath.Combine(Application.dataPath, "BasicContext.cs"); using (var writer = new StreamWriter(filePath)) { writer.Write(Template.ContextTemplate, nameSpace); } filePath = AssetPath.Combine(Application.dataPath, "BasicContextProvider.cs"); using (var writer = new StreamWriter(filePath)) { writer.Write(Template.ProviderTemplate, nameSpace); } AssetDatabase.Refresh(); }
internal bool Delete() { if (_aiStorage == null) { return(true); } var path = AssetPath.Combine(AIGeneralSettings.instance.storagePath, string.Concat(_aiStorage.name, ".asset")); if (!AssetDatabase.DeleteAsset(path)) { Debug.LogWarning(this.ToString() + " could not be deleted, path checked: " + path); return(false); } if (UserSettings.instance.autoGenerateNameMap) { AINameMapGenerator.WriteNameMapFile(); } return(true); }
public override CompilerMessage[] GetCompilerMessages() { if (!Poll()) { Debug.LogWarning("Compile process is not finished yet. This should not happen."); } if (process == null) { return(new CompilerMessage[0]); } var outputFile = AssetPath.Combine(tempOutputDirectory, assembly.Filename); DumpStreamOutputToLog(outputFile); return(CreateOutputParser().Parse( GetStreamContainingCompilerMessages(), CompilationHadFailure(), assembly.Filename ).ToArray()); }
protected override void OnSelectClicked() { var current = CoalescedPropertyValue().GetDataflow(); current.Poll(); var value = current.Value; var dlg = new FileDialog { Mode = FileDialogMode.SelectFolder, InitialDirectory = current.GotValue && value.IsDefined && !string.IsNullOrEmpty(value.Value) && TryGetClosestAvailableDirectory( AssetPath.Combine(Project.Current.AssetsDirectory, value.Value), out var dir) ? dir : Directory.Exists(LastOpenedDirectory) ? LastOpenedDirectory : Project.Current.AssetsDirectory }; if (dlg.RunModal()) { SetProperty(dlg.FileName); LastOpenedDirectory = Path.GetDirectoryName(dlg.FileName); } } }
public static Texture GetLocalised(string path, Language language, bool filter) { // Try the current language and it's fallbacks bool triedEnglish = false; while (language != null) { var specificPath = AssetPath.Combine( AssetPath.GetDirectoryName(path), AssetPath.GetFileNameWithoutExtension(path) + "_" + language.Code + ".png" ); if (Assets.Assets.Exists <Texture>(specificPath)) { return(Texture.Get(specificPath, filter)); } if (language.Code == "en") { triedEnglish = true; } language = language.Fallback; } if (!triedEnglish) { // Try english var englishPath = AssetPath.Combine( AssetPath.GetDirectoryName(path), AssetPath.GetFileNameWithoutExtension(path) + "_en.png" ); if (Assets.Assets.Exists <Texture>(englishPath)) { return(Texture.Get(englishPath, filter)); } } // Try unlocalised return(Texture.Get(path, filter)); }
private bool ChangeNameMapFolder(string proposedFolder) { if (string.Equals(proposedFolder, _nameMapPath, StringComparison.OrdinalIgnoreCase) || !AssetPath.IsProjectPath(proposedFolder)) { return(false); } proposedFolder = AssetPath.ProjectRelativePath(proposedFolder); AssetPath.EnsurePath(proposedFolder); //Move map from current location to new location. if (!string.IsNullOrEmpty(_nameMapPath)) { var existingFile = AssetPath.Combine(AssetPath.GetFullPath(_nameMapPath), NameMapFileName); if (File.Exists(existingFile)) { var oldFilePath = AssetPath.Combine(_nameMapPath, NameMapFileName); var newFilePath = AssetPath.Combine(proposedFolder, NameMapFileName); var msg = AssetDatabase.MoveAsset(oldFilePath, newFilePath); if (!string.IsNullOrEmpty(msg)) { EditorUtility.DisplayDialog("Error Moving Asset", msg, "Ok"); return(false); } else { AssetDatabase.Refresh(); } } } _nameMapPath = proposedFolder; return(true); }
protected virtual void OnSelectClicked() { var current = CoalescedPropertyValue().GetDataflow(); current.Poll(); var value = current.Value; var path = ValueToStringConverter(value.Value); var dlg = new FileDialog { AllowedFileTypes = allowedFileTypes, Mode = FileDialogMode.Open, InitialDirectory = current.GotValue && value.IsDefined && !string.IsNullOrEmpty(path) && TryGetClosestAvailableDirectory( AssetPath.Combine(Project.Current.AssetsDirectory, path), out var dir) ? dir : Directory.Exists(LastOpenedDirectory) ? LastOpenedDirectory : Project.Current.AssetsDirectory }; if (dlg.RunModal()) { SetFilePath(dlg.FileName); LastOpenedDirectory = Path.GetDirectoryName(dlg.FileName); } } }
private static CookingRules GetAssociatedCookingRules(CookingRulesCollection crc, string path, bool createIfNotExists = false) { Action <string, CookingRules> ignoreRules = (p, r) => { r = r.InheritClone(); r.Ignore = true; crc[NormalizePath(p)] = r; }; path = AssetPath.CorrectSlashes(path); string key = NormalizePath(path); CookingRules cr = null; if (File.GetAttributes(path) == FileAttributes.Directory) { // Directory var crPath = AssetPath.Combine(path, Orange.CookingRulesBuilder.CookingRulesFilename); if (crc.ContainsKey(key)) { cr = crc[key]; if (cr.SourceFilename != crPath) { if (createIfNotExists) { cr = cr.InheritClone(); crc[key] = cr; ignoreRules(crPath, cr); } else { return(null); } } } else { throw new Lime.Exception("CookingRule record for directory should already be present in collection"); } cr.SourceFilename = crPath; } else { bool isPerDirectory = Path.GetFileName(path) == CookingRulesBuilder.CookingRulesFilename; bool isPerFile = path.EndsWith(".txt") && File.Exists(path.Remove(path.Length - 4)); string filename = isPerFile ? path.Remove(path.Length - 4) : path; if (isPerDirectory || isPerFile) { // Cooking Rules File itself if (crc.ContainsKey(key)) { cr = crc[key].Parent; } else { throw new Lime.Exception("CookingRule record for cooking rules file itself should already be present in collection"); } } else { // Regular File var crPath = path + ".txt"; var crKey = NormalizePath(crPath); if (crc.ContainsKey(crKey)) { cr = crc[crKey].Parent; } else if (!createIfNotExists) { return(null); } else if (crc.ContainsKey(NormalizePath(path))) { cr = crc[NormalizePath(path)].InheritClone(); cr.SourceFilename = crPath; ignoreRules(crPath, cr); crc[key] = cr; } else { throw new Lime.Exception("CookingRule record for any regular file should already be present in collection"); } } } return(cr); }
private void BuildAtlasChain(string atlasChain) { for (var i = 0; i < AssetCooker.MaxAtlasChainLength; i++) { var atlasPath = AssetCooker.GetAtlasPath(atlasChain, i); if (AssetCooker.OutputBundle.FileExists(atlasPath)) { AssetCooker.DeleteFileFromBundle(atlasPath); } else { break; } } var pluginItems = new Dictionary <string, List <TextureTools.AtlasItem> >(); var items = new Dictionary <AtlasOptimization, List <TextureTools.AtlasItem> >(); items[AtlasOptimization.Memory] = new List <TextureTools.AtlasItem>(); items[AtlasOptimization.DrawCalls] = new List <TextureTools.AtlasItem>(); foreach (var fileInfo in AssetBundle.Current.EnumerateFileInfos(null, textureExtension)) { var cookingRules = AssetCooker.CookingRulesMap[fileInfo.Path]; if (cookingRules.TextureAtlas == atlasChain) { var item = new TextureTools.AtlasItem { Path = Path.ChangeExtension(fileInfo.Path, atlasPartExtension), CookingRules = cookingRules, SourceExtension = Path.GetExtension(fileInfo.Path) }; var bitmapInfo = TextureTools.BitmapInfo.FromFile(AssetCooker.InputBundle, fileInfo.Path); if (bitmapInfo == null) { using (var bitmap = TextureTools.OpenAtlasItemBitmapAndRescaleIfNeeded(AssetCooker.Platform, item)) { item.BitmapInfo = TextureTools.BitmapInfo.FromBitmap(bitmap); } } else { var srcTexturePath = AssetPath.Combine(The.Workspace.AssetsDirectory, Path.ChangeExtension(item.Path, item.SourceExtension)); if (TextureTools.ShouldDownscale(AssetCooker.Platform, bitmapInfo, item.CookingRules)) { TextureTools.DownscaleTextureInfo(AssetCooker.Platform, bitmapInfo, srcTexturePath, item.CookingRules); } // Ensure that no image exceeded maxAtlasSize limit TextureTools.DownscaleTextureToFitAtlas(bitmapInfo, srcTexturePath); item.BitmapInfo = bitmapInfo; } var k = cookingRules.AtlasPacker; if (!string.IsNullOrEmpty(k) && k != "Default") { List <TextureTools.AtlasItem> l; if (!pluginItems.TryGetValue(k, out l)) { pluginItems.Add(k, l = new List <TextureTools.AtlasItem>()); } l.Add(item); } else { items[cookingRules.AtlasOptimization].Add(item); } } } var initialAtlasId = 0; foreach (var kv in items) { if (kv.Value.Any()) { if (AssetCooker.Platform == TargetPlatform.iOS) { Predicate <PVRFormat> isRequireSquare = (format) => { return (format == PVRFormat.PVRTC2 || format == PVRFormat.PVRTC4 || format == PVRFormat.PVRTC4_Forced); }; var square = kv.Value.Where(item => isRequireSquare(item.CookingRules.PVRFormat)).ToList(); var nonSquare = kv.Value.Where(item => !isRequireSquare(item.CookingRules.PVRFormat)).ToList(); initialAtlasId = PackItemsToAtlas(atlasChain, square, kv.Key, initialAtlasId, true); initialAtlasId = PackItemsToAtlas(atlasChain, nonSquare, kv.Key, initialAtlasId, false); } else { initialAtlasId = PackItemsToAtlas(atlasChain, kv.Value, kv.Key, initialAtlasId, false); } } } var packers = PluginLoader.CurrentPlugin.AtlasPackers.ToDictionary(i => i.Metadata.Id, i => i.Value); foreach (var kv in pluginItems) { if (!packers.ContainsKey(kv.Key)) { throw new InvalidOperationException($"Packer {kv.Key} not found"); } initialAtlasId = packers[kv.Key](atlasChain, kv.Value, initialAtlasId); } }
// pass target as null to build cooking rules disregarding targets public static Dictionary <string, CookingRules> Build(IFileEnumerator fileEnumerator, Target target) { var shouldRescanEnumerator = false; var pathStack = new Stack <string>(); var rulesStack = new Stack <CookingRules>(); var map = new Dictionary <string, CookingRules>(); pathStack.Push(""); var rootRules = new CookingRules(); rootRules.DeduceEffectiveRules(target); rulesStack.Push(rootRules); using (new DirectoryChanger(fileEnumerator.Directory)) { foreach (var fileInfo in fileEnumerator.Enumerate()) { var path = fileInfo.Path; while (!path.StartsWith(pathStack.Peek())) { rulesStack.Pop(); pathStack.Pop(); } if (Path.GetFileName(path) == CookingRulesFilename) { var dirName = Lime.AssetPath.GetDirectoryName(path); pathStack.Push(dirName == string.Empty ? "" : dirName + "/"); var rules = ParseCookingRules(rulesStack.Peek(), path, target); rules.SourceFilename = AssetPath.Combine(fileEnumerator.Directory, path); rulesStack.Push(rules); // Add 'ignore' cooking rules for this #CookingRules.txt itself var ignoreRules = rules.InheritClone(); ignoreRules.Ignore = true; map[path] = ignoreRules; var directoryName = pathStack.Peek(); if (!string.IsNullOrEmpty(directoryName)) { directoryName = directoryName.Remove(directoryName.Length - 1); // it is possible for map to not contain this directoryName since not every IFileEnumerator enumerates directories if (map.ContainsKey(directoryName)) { map[directoryName] = rules; } } } else { if (Path.GetExtension(path) == ".txt") { var filename = path.Remove(path.Length - 4); if (File.Exists(filename) || Directory.Exists(filename)) { continue; } } var rulesFile = path + ".txt"; var rules = rulesStack.Peek(); if (File.Exists(rulesFile)) { rules = ParseCookingRules(rulesStack.Peek(), rulesFile, target); rules.SourceFilename = AssetPath.Combine(fileEnumerator.Directory, rulesFile); // Add 'ignore' cooking rules for this cooking rules text file var ignoreRules = rules.InheritClone(); ignoreRules.Ignore = true; map[rulesFile] = ignoreRules; } if (rules.CommonRules.LastChangeTime > fileInfo.LastWriteTime) { try { File.SetLastWriteTime(path, rules.CommonRules.LastChangeTime); } catch (UnauthorizedAccessException) { // In case this is a folder } shouldRescanEnumerator = true; } map[path] = rules; } } } if (shouldRescanEnumerator) { fileEnumerator.Rescan(); } return(map); }
public void Action() { var textures = new Dictionary <string, DateTime>(StringComparer.OrdinalIgnoreCase); foreach (var fileInfo in AssetCooker.InputBundle.EnumerateFileInfos(null, textureExtension)) { textures[fileInfo.Path] = fileInfo.LastWriteTime; } var atlasChainsToRebuild = new HashSet <string>(); // Figure out atlas chains to rebuild foreach (var atlasPartPath in AssetCooker.OutputBundle.EnumerateFiles().ToList()) { if (!atlasPartPath.EndsWith(atlasPartExtension, StringComparison.OrdinalIgnoreCase)) { continue; } // If atlas part has been outdated we should rebuild full atlas chain var srcTexturePath = Path.ChangeExtension(atlasPartPath, textureExtension); var bundleSHA1 = AssetCooker.OutputBundle.GetCookingRulesSHA1(atlasPartPath); if (bundleSHA1 == null) { throw new InvalidOperationException("CookingRules SHA1 for atlas part shouldn't be null"); } if ( !textures.ContainsKey(srcTexturePath) || AssetCooker.OutputBundle.GetFileLastWriteTime(atlasPartPath) != textures[srcTexturePath] || (!AssetCooker.CookingRulesMap[srcTexturePath].SHA1.SequenceEqual(bundleSHA1)) ) { srcTexturePath = AssetPath.Combine(The.Workspace.AssetsDirectory, srcTexturePath); var part = InternalPersistence.Instance.ReadObjectFromBundle <TextureAtlasElement.Params>(AssetCooker.OutputBundle, atlasPartPath); var atlasChain = Path.GetFileNameWithoutExtension(part.AtlasPath); atlasChainsToRebuild.Add(atlasChain); if (!textures.ContainsKey(srcTexturePath)) { AssetCooker.DeleteFileFromBundle(atlasPartPath); } else { srcTexturePath = Path.ChangeExtension(atlasPartPath, textureExtension); if (AssetCooker.CookingRulesMap[srcTexturePath].TextureAtlas != null) { var rules = AssetCooker.CookingRulesMap[srcTexturePath]; atlasChainsToRebuild.Add(rules.TextureAtlas); } else { AssetCooker.DeleteFileFromBundle(atlasPartPath); } } } } // Find which new textures must be added to the atlas chain foreach (var t in textures) { var atlasPartPath = Path.ChangeExtension(t.Key, atlasPartExtension); var cookingRules = AssetCooker.CookingRulesMap[t.Key]; var atlasNeedRebuld = cookingRules.TextureAtlas != null && !AssetCooker.OutputBundle.FileExists(atlasPartPath); if (atlasNeedRebuld) { atlasChainsToRebuild.Add(cookingRules.TextureAtlas); } else { UserInterface.Instance.IncreaseProgressBar(); } } foreach (var atlasChain in atlasChainsToRebuild) { AssetCooker.CheckCookCancelation(); BuildAtlasChain(atlasChain); } }
static string GenerateResponseFileEdited( ScriptAssembly assembly, EditorScriptCompilationOptions options, string tempBuildDirectory) { bool buildingForEditor = (options & EditorScriptCompilationOptions.BuildingForEditor) == EditorScriptCompilationOptions.BuildingForEditor; bool flag = (options & EditorScriptCompilationOptions.BuildingDevelopmentBuild) == EditorScriptCompilationOptions.BuildingDevelopmentBuild; List <string> arguments = new List <string>() { "-target:library", "-nowarn:0169", "-out:" + PrepareFileName(AssetPath.Combine(tempBuildDirectory, assembly.Filename)) }; // added arguments.Add("-define:__UNITY_PROCESSID__" + Process.GetCurrentProcess().Id); if (assembly.CompilerOptions.AllowUnsafeCode) { arguments.Add("-unsafe"); } arguments.Add("-debug:portable"); if (!flag && (!buildingForEditor || !EditorPrefs.GetBool("AllowAttachedDebuggingOfEditor", true))) { arguments.Add("-optimize+"); } else { arguments.Add("-optimize-"); } FillCompilerOptionsEdited(arguments, buildingForEditor, assembly.BuildTarget); foreach (ScriptAssembly assemblyReference in assembly.ScriptAssemblyReferences) { arguments.Add("-reference:" + ScriptCompilerBase.PrepareFileName(AssetPath.Combine(assembly.OutputDirectory, assemblyReference.Filename))); } foreach (string reference in assembly.References) { arguments.Add("-reference:" + ScriptCompilerBase.PrepareFileName(reference)); } foreach (string str in ((IEnumerable <string>)assembly.Defines).Distinct <string>()) { arguments.Add("-define:" + str); } foreach (string file in assembly.Files) { string str = Paths.UnifyDirectorySeparator(ScriptCompilerBase.PrepareFileName(file)); arguments.Add(str); } HashSet <string> source = new HashSet <string>((IEnumerable <string>)(assembly.Language?.CreateResponseFileProvider()?.Get(assembly.OriginPath) ?? new List <string>())); string path = source.SingleOrDefault <string>((Func <string, bool>)(x => ((IEnumerable <string>)CompilerSpecificResponseFiles.MicrosoftCSharpCompilerObsolete).Contains <string>(AssetPath.GetFileName(x)))); if (!string.IsNullOrEmpty(path)) { UnityEngine.Debug.LogWarning((object)("Using obsolete custom response file '" + AssetPath.GetFileName(path) + "'. Please use 'csc.rsp' instead.")); } // Assembly-CSharp has null OriginPath if (assembly.OriginPath?.StartsWith("Assets", StringComparison.Ordinal) ?? true) { // excludes unity packages var rspPath = "Assets/assets-csc.rsp"; if (File.Exists(rspPath)) { source.Add(rspPath); } } foreach (string responseFileName in source) { ScriptCompilerBase.AddResponseFileToArguments(arguments, responseFileName, assembly.CompilerOptions.ApiCompatibilityLevel); } return(CommandLineFormatter.GenerateResponseFile((IEnumerable <string>)arguments)); }
internal static string GenerateResponseFile(ScriptAssembly assembly, string tempBuildDirectory) { var assemblyOutputPath = PrepareFileName(AssetPath.Combine(tempBuildDirectory, assembly.Filename)); var arguments = new List <string> { "/target:library", "/nowarn:0169", "/out:" + assemblyOutputPath }; if (assembly.CompilerOptions.AllowUnsafeCode) { arguments.Add("/unsafe"); } if (assembly.CompilerOptions.UseDeterministicCompilation) { arguments.Add("/deterministic"); } arguments.Add("/debug:portable"); if (assembly.CompilerOptions.CodeOptimization == CodeOptimization.Release) { arguments.Add("/optimize+"); } else { arguments.Add("/optimize-"); } FillCompilerOptions(arguments, assembly.BuildTarget); string[] scriptAssemblyReferences = new string[assembly.ScriptAssemblyReferences.Length]; for (var index = 0; index < assembly.ScriptAssemblyReferences.Length; index++) { var reference = assembly.ScriptAssemblyReferences[index]; scriptAssemblyReferences[index] = "/reference:" + PrepareFileName(AssetPath.Combine(assembly.OutputDirectory, reference.Filename)); } Array.Sort(scriptAssemblyReferences, StringComparer.Ordinal); arguments.AddRange(scriptAssemblyReferences); Array.Sort(assembly.References, StringComparer.Ordinal); foreach (var reference in assembly.References) { arguments.Add("/reference:" + PrepareFileName(reference)); } var defines = assembly.Defines.Distinct().ToArray(); Array.Sort(defines, StringComparer.Ordinal); foreach (var define in defines) { arguments.Add("/define:" + define); } Array.Sort(assembly.Files, StringComparer.Ordinal); foreach (var source in assembly.Files) { var f = PrepareFileName(source); f = Paths.UnifyDirectorySeparator(f); arguments.Add(f); } var responseFileProvider = assembly.Language?.CreateResponseFileProvider(); var responseFilesList = responseFileProvider?.Get(assembly.OriginPath) ?? new List <string>(); HashSet <string> responseFiles = new HashSet <string>(responseFilesList); string obsoleteResponseFile = responseFiles.SingleOrDefault( x => CompilerSpecificResponseFiles.MicrosoftCSharpCompilerObsolete.Contains(AssetPath.GetFileName(x))); if (!string.IsNullOrEmpty(obsoleteResponseFile)) { Debug.LogWarning($"Using obsolete custom response file '{AssetPath.GetFileName(obsoleteResponseFile)}'. Please use '{CompilerSpecificResponseFiles.MicrosoftCSharpCompiler}' instead."); } foreach (var file in responseFiles) { AddResponseFileToArguments(arguments, file, assembly.CompilerOptions.ApiCompatibilityLevel); } var responseFile = CommandLineFormatter.GenerateResponseFile(arguments); return(responseFile); }
private static string GetPromptImagePath(this GamepadButton button, GamepadType type) { if (type == GamepadType.Unknown || type == GamepadType.XboxOne) { type = GamepadType.Xbox360; } else if (type == GamepadType.PS4) { type = GamepadType.PS3; } string buttonName; switch (button) { case GamepadButton.LeftStickUp: case GamepadButton.LeftStickDown: case GamepadButton.LeftStickLeft: case GamepadButton.LeftStickRight: { buttonName = "left_stick"; break; } case GamepadButton.RightStickUp: case GamepadButton.RightStickDown: case GamepadButton.RightStickLeft: case GamepadButton.RightStickRight: { buttonName = "right_stick"; break; } case GamepadButton.A: { switch (type) { case GamepadType.PS3: case GamepadType.PS4: { buttonName = "cross"; break; } default: { buttonName = "a"; break; } } break; } case GamepadButton.B: { switch (type) { case GamepadType.PS3: case GamepadType.PS4: { buttonName = "circle"; break; } default: { buttonName = "b"; break; } } break; } case GamepadButton.X: { switch (type) { case GamepadType.PS3: case GamepadType.PS4: { buttonName = "square"; break; } default: { buttonName = "x"; break; } } break; } case GamepadButton.Y: { switch (type) { case GamepadType.PS3: case GamepadType.PS4: { buttonName = "triangle"; break; } default: { buttonName = "y"; break; } } break; } case GamepadButton.Back: { switch (type) { case GamepadType.PS3: { buttonName = "select"; break; } case GamepadType.PS4: { buttonName = "share"; break; } case GamepadType.XboxOne: { buttonName = "view"; break; } default: { buttonName = "back"; break; } } break; } case GamepadButton.Start: { switch (type) { case GamepadType.PS4: { buttonName = "options"; break; } case GamepadType.XboxOne: { buttonName = "menu"; break; } default: { buttonName = "start"; break; } } break; } default: { buttonName = button.ToString().ToLowerUnderscored(); break; } } var path = AssetPath.Combine( "gui/prompts/" + type.ToString().ToLowerUnderscored(), buttonName + ".png" ); if (Assets.Assets.Exists <Texture>(path)) { return(path); } return(null); }