public void initDefault() { // Dispose if not null if (_package != null) { _package.Dispose(); _package = null; } if (_part != null) { _part.Dispose(); _part = null; } if (_editor != null) { _editor.Dispose(); _editor = null; } if (_renderer != null) { _renderer.Dispose(); _renderer = null; } if (_engine != null) { _engine.Dispose(); _engine = null; } _engine = Engine.Create(MyScript.Certificate.MyCertificate.Bytes); var confDirs = new string[1]; confDirs[0] = "conf"; _engine.Configuration.SetStringArray("configuration-manager.search-path", confDirs); var localFolder = _path; var tempFolder = _tmp_path; _engine.Configuration.SetString("content-package.temp-folder", tempFolder); _engine.Configuration.SetString("lang", _lang); _dpiX = 300; _dpiY = 300; _renderer = _engine.CreateRenderer(_dpiX, _dpiY, null); _package = _engine.CreatePackage("text.iink"); _part = _package.CreatePart("Text"); _editor = _engine.CreateEditor(_renderer); _editor.Theme = ".text { font-size: 7.8;line-height: 1.0; }"; _editor.SetViewSize(30000, 30000); var fmp = new FontMetricsProvider(_dpiX, _dpiY); _editor.SetFontMetricsProvider(fmp); _editor.Part = _part; _editor.Configuration.SetBoolean("text.guides.enable", false); _engine.Configuration.SetBoolean("text.guides.enable", false); initListener(); }
public static IEnumerable <ContentPart> GetPages([NotNull] this ContentPackage source) { var count = source.PartCount; for (var index = 0; index < count; index++) { yield return(source.GetPart(index)); } }
public ContentPackage ImportAnimation(Components.Scene scene, string filename, SceneNode root, string fileNodeRoot) { this.scene = scene; ContentPackage pk = new ContentPackage(Path.GetFileNameWithoutExtension(filename)); var anim = ParseFile(filename, root); pk.Add(anim); return(pk); }
protected override void Initialize() { // TODO: Add your initialization logic here ContentPackage.LoadAll(ContentPackage.Folder); settings = new GameSettings(configPath); base.Initialize(); }
public static string GetWorkshopItemContentPackagePath(ContentPackage contentPackage) { string fileName = contentPackage.Name + ".xml"; string invalidChars = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()); foreach (char c in invalidChars) { fileName = fileName.Replace(c.ToString(), ""); } return(Path.Combine("Data", "ContentPackages", fileName)); }
public int CreateContentPackage(ContentPackage ObjContentPackage) { try { db.ContentPackages.Add(ObjContentPackage); return(db.SaveChanges()); } catch (Exception e) { return((int)EnumCore.Result.action_false); } }
public async Task <int> CreateContentPackageAsync(ContentPackage ObjContentPackage) { try { db.ContentPackages.Add(ObjContentPackage); return(await db.SaveChangesAsync()); } catch (Exception e) { return((int)EnumCore.Result.action_false); } }
public override void Load(ContentPackage package) { LoadShader(package); diffuseColorParam = GL.GetUniformLocation(ShaderProgram, DefaultDiffuseColorParamLocation); lightDirectionParam = GL.GetUniformLocation(ShaderProgram, DefaultLightDirectionParamLocation); specularColorParam = GL.GetUniformLocation(ShaderProgram, DefaultSpecularColorParamLocation); specularityParam = GL.GetUniformLocation(ShaderProgram, DefaultSpecularityParamLocation); shininessParam = GL.GetUniformLocation(ShaderProgram, DefaultShininessParamLocation); cameraPositionParam = GL.GetUniformLocation(ShaderProgram, DefaultCameraPositionParamLocation); ambientColorParam = GL.GetUniformLocation(ShaderProgram, DefaultAmbientColorParamLocation); ambientStrengthParam = GL.GetUniformLocation(ShaderProgram, DefaultAmbientStrengthParamLocation); }
ContentPackage ImportContent() { ContentPackage content = null; using (OpenFileDialog d = new OpenFileDialog()) { if (d.ShowDialog() == DialogResult.OK) { SceneTests.InitializeScene(); content = ContentImporter.Import(SceneManager.Scene, d.FileName); } } return(content); }
/// <summary> /// Creates a new folder, copies the specified files there and creates a metadata file with install instructions. /// </summary> public static void CreateWorkshopItemStaging(List <ContentFile> contentFiles, out Workshop.Editor itemEditor, out ContentPackage contentPackage) { var stagingFolder = new DirectoryInfo(WorkshopItemStagingFolder); if (stagingFolder.Exists) { SaveUtil.ClearFolder(stagingFolder.FullName); } else { stagingFolder.Create(); } Directory.CreateDirectory(Path.Combine(WorkshopItemStagingFolder, "Submarines")); Directory.CreateDirectory(Path.Combine(WorkshopItemStagingFolder, "Mods")); Directory.CreateDirectory(Path.Combine(WorkshopItemStagingFolder, "Mods", "ModName")); itemEditor = instance.client.Workshop.CreateItem(Workshop.ItemType.Community); itemEditor.Visibility = Workshop.Editor.VisibilityType.Public; itemEditor.WorkshopUploadAppId = AppID; itemEditor.Folder = stagingFolder.FullName; string previewImagePath = Path.GetFullPath(Path.Combine(itemEditor.Folder, PreviewImageName)); File.Copy("Content/DefaultWorkshopPreviewImage.png", previewImagePath); //copy content files to the staging folder List <string> copiedFilePaths = new List <string>(); foreach (ContentFile file in contentFiles) { string relativePath = UpdaterUtil.GetRelativePath(Path.GetFullPath(file.Path), Environment.CurrentDirectory); string destinationPath = Path.Combine(stagingFolder.FullName, relativePath); //make sure the directory exists Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)); File.Copy(file.Path, destinationPath); copiedFilePaths.Add(destinationPath); } System.Diagnostics.Debug.Assert(copiedFilePaths.Count == contentFiles.Count); //create a new content package and include the copied files in it contentPackage = ContentPackage.CreatePackage("ContentPackage", Path.Combine(itemEditor.Folder, MetadataFileName), false); for (int i = 0; i < copiedFilePaths.Count; i++) { contentPackage.AddFile(copiedFilePaths[i], contentFiles[i].Type); } contentPackage.Save(Path.Combine(stagingFolder.FullName, MetadataFileName)); }
/// <summary> /// Is the item compatible with this version of Barotrauma. Returns null if compatibility couldn't be determined (item not installed) /// </summary> public static bool?CheckWorkshopItemCompatibility(Workshop.Item item) { if (!item.Installed) { return(null); } string metaDataPath = Path.Combine(item.Directory.FullName, MetadataFileName); if (!File.Exists(metaDataPath)) { throw new FileNotFoundException("Metadata file for the Workshop item \"" + item.Title + "\" not found. The file may be corrupted."); } ContentPackage contentPackage = new ContentPackage(metaDataPath); return(contentPackage.IsCompatible()); }
public static async Task <IBook> ToPlatformAsync([NotNull] this ContentPackage source) { var result = new Book { Name = source.GetValue(ParamBookName, DefaultName), Pages = source.GetParts().Select(part => part.ToPlatform()) }; var configuration = InteractiveInkServices.EngineService.Engine.Configuration; var identifier = configuration.GetString(ConfigurationKeys.Language); result.Language = InteractiveInkServices.LanguageService.Languages.Single(x => x.Tag == identifier); if (!(await source.GetTargetFileAsync() is { } file)) { return(result); } result.Name = source.GetValue(ParamBookName, file.DisplayName); result.TargetFile = file; result.TargetFileProperties = await file.GetBasicPropertiesAsync(); return(result); }
/// <summary>Gets the complete cookie string for the given data package as well as the HTTP status.</summary> public static void Handle(ContentPackage package) { // Foreach header in "set-cookie": List <string> setCookie = package.responseHeaders.GetAll("set-cookie"); if (setCookie == null) { return; } // Get the url: Location url = package.location; for (int i = 0; i < setCookie.Count; i++) { // Load the cookie now: Cookie cookie = new Cookie(setCookie[i]); // Try adding it, with a safety check: cookie.SafeSet(url); } }
private int SaveVideoPackage(long[] model, MediaContent Video) { try { int dl = cms_db.DeleteContentPackage(Video.MediaContentId, (int)EnumCore.ObjTypeId.video); foreach (int _val in model) { ContentPackage tmp = new ContentPackage(); tmp.ContentId = Video.MediaContentId; tmp.ContentName = Video.Filename; tmp.ContentType = (int)EnumCore.ObjTypeId.video; tmp.PackageId = _val; tmp.PackageName = cms_db.GetPackageName(_val); cms_db.CreateContentPackage(tmp); } return((int)EnumCore.Result.action_true); } catch (Exception e) { cms_db.AddToExceptionLog("SaveVideoPackage", "MediaManage", e.ToString(), long.Parse(User.Identity.GetUserId())); return((int)EnumCore.Result.action_false); } }
private bool LaunchClick(GUIButton button, object obj) { if (!TrySaveSettings()) { return(false); } var executables = ContentPackage.GetFilesOfType(settings.SelectedContentPackages, ContentType.Executable); if (!executables.Any()) { ShowError("Error", "The game executable isn't configured in the selected content package."); return(false); } string exePath = Path.Combine(Directory.GetCurrentDirectory(), executables.First()); if (!File.Exists(exePath)) { ShowError("Error", "Couldn't find the executable \"" + exePath + "\"!"); return(false); } try { Process.Start(new ProcessStartInfo(exePath)); } catch (Exception exception) { ShowError("Error while opening executable \"" + exePath + "\"", exception.Message); return(false); } Exit(); return(true); }
public DecalPrefab(XElement element, ContentFile file) { Name = element.Name.ToString(); FilePath = file.Path; ContentPackage = file.ContentPackage; Sprites = new List <Sprite>(); foreach (XElement subElement in element.Elements()) { if (subElement.Name.ToString().Equals("sprite", StringComparison.OrdinalIgnoreCase)) { Sprites.Add(new Sprite(subElement)); } } Color = new Color(element.GetAttributeVector4("color", Vector4.One)); LifeTime = element.GetAttributeFloat("lifetime", 10.0f); FadeOutTime = Math.Min(LifeTime, element.GetAttributeFloat("fadeouttime", 1.0f)); FadeInTime = Math.Min(LifeTime - FadeOutTime, element.GetAttributeFloat("fadeintime", 0.0f)); }
public static bool CheckWorkshopItemUpToDate(Workshop.Item item) { if (!item.Installed) { return(false); } string metaDataPath = Path.Combine(item.Directory.FullName, MetadataFileName); if (!File.Exists(metaDataPath)) { DebugConsole.ThrowError("Metadata file for the Workshop item \"" + item.Title + "\" not found. The file may be corrupted."); return(false); } ContentPackage steamPackage = new ContentPackage(metaDataPath); ContentPackage myPackage = ContentPackage.List.Find(cp => cp.Name == steamPackage.Name); if (myPackage?.InstallTime == null) { return(false); } return(item.Modified <= myPackage.InstallTime.Value); }
public static bool CheckWorkshopItemEnabled(Workshop.Item item, bool checkContentFiles = true) { if (!item.Installed) { return(false); } string metaDataPath = Path.Combine(item.Directory.FullName, MetadataFileName); if (!File.Exists(metaDataPath)) { DebugConsole.ThrowError("Metadata file for the Workshop item \"" + item.Title + "\" not found. The file may be corrupted."); return(false); } ContentPackage contentPackage = new ContentPackage(metaDataPath); //make sure the contentpackage file is present if (!File.Exists(GetWorkshopItemContentPackagePath(contentPackage)) && !ContentPackage.List.Any(cp => cp.Name == contentPackage.Name)) { return(false); } if (checkContentFiles) { foreach (ContentFile contentFile in contentPackage.Files) { if (!File.Exists(contentFile.Path)) { return(false); } } } return(true); }
private int SaveContentItemPackage(long[] model, ContentItem ContentObj) { try { int dl = cms_db.DeleteContentPackage(ContentObj.ContentItemId, (int)EnumCore.ObjTypeId.tin_tuc); foreach (int _val in model) { ContentPackage tmp = new ContentPackage(); tmp.ContentId = ContentObj.ContentItemId; tmp.ContentName = ContentObj.ContentTitle; tmp.ContentType = (int)EnumCore.ObjTypeId.tin_tuc; tmp.PackageId = _val; tmp.PackageName = cms_db.GetPackageName(_val); cms_db.CreateContentPackage(tmp); } return((int)EnumCore.Result.action_true); } catch (Exception e) { cms_db.AddToExceptionLog("SaveContentItemPackage", "ContentItem", e.ToString(), long.Parse(User.Identity.GetUserId())); return((int)EnumCore.Result.action_false); } }
protected void CreateSelector(ContentPackage package) { SolidColorSpecularMaterial materialGray = new SolidColorSpecularMaterial(new Vector3(.5f, .5f, 1f), SelectorMaterialName); materialGray.Load(package); RenderScene.AddMaterial(materialGray); materialGray.LightDirection = new Vector3(1f, -1f, 0f); materialGray.Shininess = 3f; materialGray.Specularity = .5f; MeshGroup selectorMesh = package.LoadMeshGroup(SelectorMeshSource); Model selectorModel = new Model() { Name = SelectorModelName, Material = materialGray, MeshGroup = selectorMesh }; RenderScene.AddModel(selectorModel); selector = new RenderNode() { Model = selectorModel, Transform = Matrix4.Identity }; RenderScene.AddRenderNode(selector); }
private int SaveMarginPackage(long[] model, Margin Margin) { try { int dl = cms_db.DeleteContentPackage(Margin.MarginId, (int)EnumCore.ObjTypeId.margin); foreach (int _val in model) { ContentPackage tmp = new ContentPackage(); tmp.ContentId = Margin.MarginId; tmp.ContentName = "Margin"; tmp.ContentType = (int)EnumCore.ObjTypeId.margin; tmp.PackageId = _val; tmp.PackageName = cms_db.GetPackageName(_val); cms_db.CreateContentPackage(tmp); } return((int)EnumCore.Result.action_true); } catch (Exception e) { cms_db.AddToExceptionLog("SaveTickerPackage", "MarginManagerController", e.ToString(), long.Parse(User.Identity.GetUserId())); return((int)EnumCore.Result.action_false); } }
protected void CreatePieceMaterials(ContentPackage package) { SolidColorSpecularMaterial materialWhite = new SolidColorSpecularMaterial(Vector3.One, MaterialWhiteName); SolidColorSpecularMaterial materialBlack = new SolidColorSpecularMaterial(new Vector3(.5f, .5f, .5f), MaterialBlackName); SolidColorSpecularMaterial materialSelected = new SolidColorSpecularMaterial(Color.CornflowerBlue, SelectedMaterialName); materialWhite.Load(package); materialBlack.Load(package); materialSelected.Load(package); RenderScene.AddMaterial(materialWhite); RenderScene.AddMaterial(materialBlack); RenderScene.AddMaterial(materialSelected); // Set material parameters materialWhite.LightDirection = new Vector3(1f, -1f, 0f); materialBlack.LightDirection = new Vector3(1f, -1f, 0f); materialSelected.LightDirection = new Vector3(1f, -1f, 0f); materialWhite.Shininess = 3f; materialBlack.Shininess = 3f; materialSelected.Shininess = 3f; materialWhite.Specularity = .5f; materialBlack.Specularity = .5f; materialSelected.Specularity = .5f; }
public WebRequestHandler(ContentPackage contentPackage, SocketPackage socketPackage) { this.contentPackage = contentPackage; this.socketPackage = socketPackage; }
/// <summary> /// Enables a workshop item by moving it to the game folder. /// </summary> public static bool EnableWorkShopItem(Workshop.Item item, bool allowFileOverwrite, out string errorMsg) { if (!item.Installed) { errorMsg = TextManager.GetWithVariable("WorkshopErrorInstallRequiredToEnable", "[itemname]", item.Title); DebugConsole.NewMessage(errorMsg, Microsoft.Xna.Framework.Color.Red); return(false); } string metaDataFilePath = Path.Combine(item.Directory.FullName, MetadataFileName); ContentPackage contentPackage = new ContentPackage(metaDataFilePath); string newContentPackagePath = GetWorkshopItemContentPackagePath(contentPackage); if (!contentPackage.IsCompatible()) { errorMsg = TextManager.GetWithVariables(contentPackage.GameVersion <= new Version(0, 0, 0, 0) ? "IncompatibleContentPackageUnknownVersion" : "IncompatibleContentPackage", new string[3] { "[packagename]", "[packageversion]", "[gameversion]" }, new string[3] { contentPackage.Name, contentPackage.GameVersion.ToString(), GameMain.Version.ToString() }); return(false); } if (contentPackage.CorePackage && !contentPackage.ContainsRequiredCorePackageFiles(out List <ContentType> missingContentTypes)) { errorMsg = TextManager.GetWithVariables("ContentPackageMissingCoreFiles", new string[2] { "[packagename]", "[missingfiletypes]" }, new string[2] { contentPackage.Name, string.Join(", ", missingContentTypes) }, new bool[2] { false, true }); return(false); } var allPackageFiles = Directory.GetFiles(item.Directory.FullName, "*", SearchOption.AllDirectories); List <string> nonContentFiles = new List <string>(); foreach (string file in allPackageFiles) { if (file == metaDataFilePath) { continue; } string relativePath = UpdaterUtil.GetRelativePath(file, item.Directory.FullName); string fullPath = Path.GetFullPath(relativePath); if (contentPackage.Files.Any(f => { string fp = Path.GetFullPath(f.Path); return(fp == fullPath); })) { continue; } if (ContentPackage.IsModFilePathAllowed(relativePath)) { nonContentFiles.Add(relativePath); } } if (!allowFileOverwrite) { if (File.Exists(newContentPackagePath) && !CheckFileEquality(newContentPackagePath, metaDataFilePath)) { errorMsg = TextManager.GetWithVariables("WorkshopErrorOverwriteOnEnable", new string[2] { "[itemname]", "[filename]" }, new string[2] { item.Title, newContentPackagePath }); DebugConsole.NewMessage(errorMsg, Microsoft.Xna.Framework.Color.Red); return(false); } foreach (ContentFile contentFile in contentPackage.Files) { string sourceFile = Path.Combine(item.Directory.FullName, contentFile.Path); if (File.Exists(sourceFile) && File.Exists(contentFile.Path) && !CheckFileEquality(sourceFile, contentFile.Path)) { errorMsg = TextManager.GetWithVariables("WorkshopErrorOverwriteOnEnable", new string[2] { "[itemname]", "[filename]" }, new string[2] { item.Title, contentFile.Path }); DebugConsole.NewMessage(errorMsg, Microsoft.Xna.Framework.Color.Red); return(false); } } } try { foreach (ContentFile contentFile in contentPackage.Files) { string sourceFile = Path.Combine(item.Directory.FullName, contentFile.Path); //path not allowed -> the content file must be a reference to an external file (such as some vanilla file outside the Mods folder) if (!ContentPackage.IsModFilePathAllowed(contentFile)) { //the content package is trying to copy a file to a prohibited path, which is not allowed if (File.Exists(sourceFile)) { errorMsg = TextManager.GetWithVariable("WorkshopErrorIllegalPathOnEnable", "[filename]", contentFile.Path); return(false); } //not trying to copy anything, so this is a reference to an external file //if the external file doesn't exist, we cannot enable the package else if (!File.Exists(contentFile.Path)) { errorMsg = TextManager.GetWithVariable("WorkshopErrorEnableFailed", "[itemname]", item.Title) + " " + TextManager.GetWithVariable("WorkshopFileNotFound", "[path]", "\"" + contentFile.Path + "\""); return(false); } continue; } else if (!File.Exists(sourceFile)) { if (File.Exists(contentFile.Path)) { //the file is already present in the game folder, all good continue; } else { //file not present in either the mod or the game folder -> cannot enable the package errorMsg = TextManager.GetWithVariable("WorkshopErrorEnableFailed", "[itemname]", item.Title) + " " + TextManager.GetWithVariable("WorkshopFileNotFound", "[path]", "\"" + contentFile.Path + "\""); return(false); } } //make sure the destination directory exists Directory.CreateDirectory(Path.GetDirectoryName(contentFile.Path)); File.Copy(sourceFile, contentFile.Path, overwrite: true); } foreach (string nonContentFile in nonContentFiles) { string sourceFile = Path.Combine(item.Directory.FullName, nonContentFile); if (!File.Exists(sourceFile)) { continue; } if (!ContentPackage.IsModFilePathAllowed(nonContentFile)) { DebugConsole.ThrowError(TextManager.GetWithVariable("WorkshopErrorIllegalPathOnEnable", "[filename]", nonContentFile)); continue; } Directory.CreateDirectory(Path.GetDirectoryName(nonContentFile)); File.Copy(sourceFile, nonContentFile, overwrite: true); } } catch (Exception e) { errorMsg = TextManager.GetWithVariable("WorkshopErrorEnableFailed", "[itemname]", item.Title) + " {" + e.Message + "}"; DebugConsole.NewMessage(errorMsg, Microsoft.Xna.Framework.Color.Red); return(false); } var newPackage = new ContentPackage(contentPackage.Path, newContentPackagePath) { SteamWorkshopUrl = item.Url, InstallTime = item.Modified > item.Created ? item.Modified : item.Created }; newPackage.Save(newContentPackagePath); ContentPackage.List.Add(newPackage); if (newPackage.CorePackage) { //if enabling a core package, disable all other core packages GameMain.Config.SelectedContentPackages.RemoveWhere(cp => cp.CorePackage); } GameMain.Config.SelectedContentPackages.Add(newPackage); GameMain.Config.SaveNewPlayerConfig(); if (newPackage.Files.Any(f => f.Type == ContentType.Submarine)) { Submarine.RefreshSavedSubs(); } errorMsg = ""; return(true); }
public override void Load(ContentPackage package) { LoadShader(package); }
public static void AppendTo(ContentPackage contentPackage) { contentPackage.AddContentProvider(ResourcesListUrl, new ContentPackageResourceListContentProvider(contentPackage)); }
public ContentPackageResourceListContentProvider(ContentPackage contentPackage) { this.contentPackage = contentPackage; }
/// <summary>Just like FileProtocol. Called when a request was made to the server. /// Respond to the package to handle the request /// (in the same way a FileProtocol would respond to it).</summary> public virtual void OnGetDataNow(ContentPackage package) { }
//todo: remove public static void AppendTo(ContentPackage contentPackage) { //throw new NotImplementedException(); }
private static void WriteStyles(TextWriter w, string stylesXml, ContentPackage pkg) { if (!string.IsNullOrEmpty(stylesXml)) { var Url = DNA.Utility.UrlUtility.CreateUrlHelper(); var stylesEl = XElement.Parse(stylesXml); if (stylesEl != null && stylesEl.HasElements) { foreach (var style in stylesEl.Elements()) { var src = style.StrAttr("src"); if (!string.IsNullOrEmpty(src)) { #region link element var linkElement = new XElement("link", new XAttribute("type", "text/css"), new XAttribute("rel", "stylesheet")); var formattedSrc = src; if (!src.StartsWith("http")) { if (src.StartsWith("~")) formattedSrc = Url.Content(src); else formattedSrc = Url.Content(pkg.ResolveUri(src)); } linkElement.Add(new XAttribute("href", formattedSrc)); w.Write(linkElement.OuterXml()); #endregion } else { w.Write("<style type=\"text/css\" >"); var csstext = string.IsNullOrEmpty(style.Value) ? style.InnerXml() : style.Value; if (!string.IsNullOrEmpty(csstext)) w.Write(csstext); w.Write("</style>"); } } } } }
/// <summary> /// Enables a workshop item by moving it to the game folder. /// </summary> public static bool EnableWorkShopItem(Workshop.Item item, bool allowFileOverwrite, out string errorMsg) { if (!item.Installed) { errorMsg = TextManager.Get("WorkshopErrorInstallRequiredToEnable").Replace("[itemname]", item.Title); DebugConsole.NewMessage(errorMsg, Microsoft.Xna.Framework.Color.Red); return(false); } string metaDataFilePath = Path.Combine(item.Directory.FullName, MetadataFileName); ContentPackage contentPackage = new ContentPackage(metaDataFilePath); string newContentPackagePath = GetWorkshopItemContentPackagePath(contentPackage); var allPackageFiles = Directory.GetFiles(item.Directory.FullName, "*", SearchOption.AllDirectories); List <string> nonContentFiles = new List <string>(); foreach (string file in allPackageFiles) { if (file == metaDataFilePath) { continue; } string relativePath = UpdaterUtil.GetRelativePath(file, item.Directory.FullName); string fullPath = Path.GetFullPath(relativePath); if (contentPackage.Files.Any(f => { string fp = Path.GetFullPath(f.Path); return(fp == fullPath); })) { continue; } if (ContentPackage.IsModFilePathAllowed(relativePath)) { nonContentFiles.Add(relativePath); } } if (!allowFileOverwrite) { if (File.Exists(newContentPackagePath)) { errorMsg = TextManager.Get("WorkshopErrorOverwriteOnEnable") .Replace("[itemname]", item.Title) .Replace("[filename]", newContentPackagePath); DebugConsole.NewMessage(errorMsg, Microsoft.Xna.Framework.Color.Red); return(false); } foreach (ContentFile contentFile in contentPackage.Files) { string sourceFile = Path.Combine(item.Directory.FullName, contentFile.Path); if (File.Exists(sourceFile) && File.Exists(contentFile.Path)) { errorMsg = TextManager.Get("WorkshopErrorOverwriteOnEnable") .Replace("[itemname]", item.Title) .Replace("[filename]", contentFile.Path); DebugConsole.NewMessage(errorMsg, Microsoft.Xna.Framework.Color.Red); return(false); } } } try { foreach (ContentFile contentFile in contentPackage.Files) { string sourceFile = Path.Combine(item.Directory.FullName, contentFile.Path); if (!File.Exists(sourceFile)) { continue; } if (!ContentPackage.IsModFilePathAllowed(contentFile)) { DebugConsole.ThrowError(TextManager.Get("WorkshopErrorIllegalPathOnEnable").Replace("[filename]", contentFile.Path)); continue; } //make sure the destination directory exists Directory.CreateDirectory(Path.GetDirectoryName(contentFile.Path)); File.Copy(sourceFile, contentFile.Path, overwrite: true); } foreach (string nonContentFile in nonContentFiles) { string sourceFile = Path.Combine(item.Directory.FullName, nonContentFile); if (!File.Exists(sourceFile)) { continue; } if (!ContentPackage.IsModFilePathAllowed(nonContentFile)) { DebugConsole.ThrowError(TextManager.Get("WorkshopErrorIllegalPathOnEnable").Replace("[filename]", nonContentFile)); continue; } Directory.CreateDirectory(Path.GetDirectoryName(nonContentFile)); File.Copy(sourceFile, nonContentFile, overwrite: true); } } catch (Exception e) { errorMsg = TextManager.Get("WorkshopErrorEnableFailed").Replace("[itemname]", item.Title) + " " + e.Message; DebugConsole.NewMessage(errorMsg, Microsoft.Xna.Framework.Color.Red); return(false); } var newPackage = new ContentPackage(contentPackage.Path, newContentPackagePath) { SteamWorkshopUrl = item.Url, InstallTime = item.Modified > item.Created ? item.Modified : item.Created }; newPackage.Save(newContentPackagePath); ContentPackage.List.Add(newPackage); if (newPackage.CorePackage) { //if enabling a core package, disable all other core packages GameMain.Config.SelectedContentPackages.RemoveWhere(cp => cp.CorePackage); } GameMain.Config.SelectedContentPackages.Add(newPackage); GameMain.Config.SaveNewPlayerConfig(); if (newPackage.Files.Any(f => f.Type == ContentType.Submarine)) { Submarine.RefreshSavedSubs(); } errorMsg = ""; return(true); }
/// <summary> /// Disables a workshop item by removing the files from the game folder. /// </summary> public static bool DisableWorkShopItem(Workshop.Item item, out string errorMsg) { if (!item.Installed) { errorMsg = "Cannot disable workshop item \"" + item.Title + "\" because it has not been installed."; DebugConsole.NewMessage(errorMsg, Microsoft.Xna.Framework.Color.Red); return(false); } ContentPackage contentPackage = new ContentPackage(Path.Combine(item.Directory.FullName, MetadataFileName)); string installedContentPackagePath = GetWorkshopItemContentPackagePath(contentPackage); var allPackageFiles = Directory.GetFiles(item.Directory.FullName, "*", SearchOption.AllDirectories); List <string> nonContentFiles = new List <string>(); foreach (string file in allPackageFiles) { if (file == MetadataFileName) { continue; } string relativePath = UpdaterUtil.GetRelativePath(file, item.Directory.FullName); string fullPath = Path.GetFullPath(relativePath); if (contentPackage.Files.Any(f => { string fp = Path.GetFullPath(f.Path); return(fp == fullPath); })) { continue; } if (ContentPackage.IsModFilePathAllowed(relativePath)) { nonContentFiles.Add(relativePath); } } if (File.Exists(installedContentPackagePath)) { File.Delete(installedContentPackagePath); } bool wasSub = contentPackage.Files.Any(f => f.Type == ContentType.Submarine); HashSet <string> directories = new HashSet <string>(); try { foreach (ContentFile contentFile in contentPackage.Files) { if (!ContentPackage.IsModFilePathAllowed(contentFile)) { //Workshop items are not allowed to add or modify files in the Content or Data folders; continue; } if (!File.Exists(contentFile.Path)) { continue; } File.Delete(contentFile.Path); directories.Add(Path.GetDirectoryName(contentFile.Path)); } foreach (string nonContentFile in nonContentFiles) { if (!ContentPackage.IsModFilePathAllowed(nonContentFile)) { //Workshop items are not allowed to add or modify files in the Content or Data folders; continue; } if (!File.Exists(nonContentFile)) { continue; } File.Delete(nonContentFile); directories.Add(Path.GetDirectoryName(nonContentFile)); } foreach (string directory in directories) { if (string.IsNullOrWhiteSpace(directory) || !Directory.Exists(directory)) { continue; } if (Directory.GetFiles(directory, "*", SearchOption.AllDirectories).Count() == 0) { Directory.Delete(directory, recursive: true); } } ContentPackage.List.RemoveAll(cp => System.IO.Path.GetFullPath(cp.Path) == System.IO.Path.GetFullPath(installedContentPackagePath)); GameMain.Config.SelectedContentPackages.RemoveWhere(cp => !ContentPackage.List.Contains(cp)); GameMain.Config.SaveNewPlayerConfig(); } catch (Exception e) { errorMsg = "Disabling the workshop item \"" + item.Title + "\" failed. " + e.Message; DebugConsole.NewMessage(errorMsg, Microsoft.Xna.Framework.Color.Red); return(false); } if (wasSub) { Submarine.RefreshSavedSubs(); } errorMsg = ""; return(true); }
protected void CreatePieceModels(ContentPackage package) { Material materialWhite = RenderScene.Materials[MaterialWhiteName]; Material materialBlack = RenderScene.Materials[MaterialBlackName]; MeshGroup mesh = package.LoadMeshGroup(Pawn.MeshSource); Model pawnWhite = new Model() { Name = Pawn.ModelWhite, Material = materialWhite, MeshGroup = mesh }; RenderScene.AddModel(pawnWhite); Model pawnBlack = new Model() { Name = Pawn.ModelBlack, Material = materialBlack, MeshGroup = mesh }; RenderScene.AddModel(pawnBlack); mesh = package.LoadMeshGroup(Knight.MeshSource); Model knightWhite = new Model() { Name = Knight.ModelWhite, Material = materialWhite, MeshGroup = mesh }; RenderScene.AddModel(knightWhite); Model knightBlack = new Model() { Name = Knight.ModelBlack, Material = materialBlack, MeshGroup = mesh }; RenderScene.AddModel(knightBlack); mesh = package.LoadMeshGroup(Bishop.MeshSource); Model bishopWhite = new Model() { Name = Bishop.ModelWhite, Material = materialWhite, MeshGroup = mesh }; RenderScene.AddModel(bishopWhite); Model bishopBlack = new Model() { Name = Bishop.ModelBlack, Material = materialBlack, MeshGroup = mesh }; RenderScene.AddModel(bishopBlack); mesh = package.LoadMeshGroup(Rook.MeshSource); Model rookWhite = new Model() { Name = Rook.ModelWhite, Material = materialWhite, MeshGroup = mesh }; RenderScene.AddModel(rookWhite); Model rookBlack = new Model() { Name = Rook.ModelBlack, Material = materialBlack, MeshGroup = mesh }; RenderScene.AddModel(rookBlack); mesh = package.LoadMeshGroup(Queen.MeshSource); Model queenWhite = new Model() { Name = Queen.ModelWhite, Material = materialWhite, MeshGroup = mesh }; RenderScene.AddModel(queenWhite); Model queenBlack = new Model() { Name = Queen.ModelBlack, Material = materialBlack, MeshGroup = mesh }; RenderScene.AddModel(queenBlack); mesh = package.LoadMeshGroup(King.MeshSource); Model kingWhite = new Model() { Name = King.ModelWhite, Material = materialWhite, MeshGroup = mesh }; RenderScene.AddModel(kingWhite); Model kingBlack = new Model() { Name = King.ModelBlack, Material = materialBlack, MeshGroup = mesh }; RenderScene.AddModel(kingBlack); }
private static void WriteScripts(TextWriter w, string scriptsXml, ContentPackage pkg) { if (!string.IsNullOrEmpty(scriptsXml)) { var Url = DNA.Utility.UrlUtility.CreateUrlHelper(); var scriptsEl = XElement.Parse(scriptsXml); if (scriptsEl != null && scriptsEl.HasElements) { foreach (var script in scriptsEl.Elements()) { var type = string.IsNullOrEmpty(script.StrAttr("type")) ? "text/javascript" : script.StrAttr("type"); var src = script.StrAttr("src"); if (!string.IsNullOrEmpty(src)) { //var scriptElement = new XElement("script", new XAttribute("type", type)); var formattedSrc = src; if (!src.StartsWith("http")) { if (src.StartsWith("~")) formattedSrc = Url.Content(src); else formattedSrc = Url.Content(pkg.ResolveUri(src)); } w.Write("<script type=\"" + type + "\" src=\"" + formattedSrc + "\"></script>"); } else { var scriptContent = string.IsNullOrEmpty(script.Value) ? script.InnerXml() : script.Value; w.Write("<script type=\"" + type + "\">"); w.Write(scriptContent); w.Write("</script>"); } } } } }
protected string GetPackageStr(ContentPackage contentPackage) { return("\"" + contentPackage.Name + "\" (hash " + contentPackage.MD5hash.ShortHash + ")"); }
/// <summary> /// Creates a copy of the specified workshop item in the staging folder and an editor that can be used to edit and update the item /// </summary> public static void CreateWorkshopItemStaging(Workshop.Item existingItem, out Workshop.Editor itemEditor, out ContentPackage contentPackage) { if (!existingItem.Installed) { itemEditor = null; contentPackage = null; DebugConsole.ThrowError("Cannot edit the workshop item \"" + existingItem.Title + "\" because it has not been installed."); return; } var stagingFolder = new DirectoryInfo(WorkshopItemStagingFolder); if (stagingFolder.Exists) { SaveUtil.ClearFolder(stagingFolder.FullName); } else { stagingFolder.Create(); } itemEditor = instance.client.Workshop.EditItem(existingItem.Id); itemEditor.Visibility = Workshop.Editor.VisibilityType.Public; itemEditor.Title = existingItem.Title; itemEditor.Tags = existingItem.Tags.ToList(); itemEditor.Description = existingItem.Description; itemEditor.WorkshopUploadAppId = AppID; itemEditor.Folder = stagingFolder.FullName; string previewImagePath = Path.GetFullPath(Path.Combine(itemEditor.Folder, PreviewImageName)); itemEditor.PreviewImage = previewImagePath; try { if (File.Exists(previewImagePath)) { File.Delete(previewImagePath); } Uri baseAddress = new Uri(existingItem.PreviewImageUrl); Uri directory = new Uri(baseAddress, "."); // "." == current dir, like MS-DOS string fileName = Path.GetFileName(baseAddress.LocalPath); IRestClient client = new RestClient(directory); var request = new RestRequest(fileName, Method.GET); var response = client.Execute(request); if (response.ResponseStatus == ResponseStatus.Completed) { File.WriteAllBytes(previewImagePath, response.RawBytes); } } catch (Exception e) { string errorMsg = "Failed to save workshop item preview image to \"" + previewImagePath + "\" when creating workshop item staging folder."; GameAnalyticsManager.AddErrorEventOnce("SteamManager.CreateWorkshopItemStaging:WriteAllBytesFailed" + previewImagePath, GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg + "\n" + e.Message); } ContentPackage tempContentPackage = new ContentPackage(Path.Combine(existingItem.Directory.FullName, MetadataFileName)); //item already installed, copy it from the game folder if (existingItem != null && CheckWorkshopItemEnabled(existingItem, checkContentFiles: false)) { string installedItemPath = GetWorkshopItemContentPackagePath(tempContentPackage); if (File.Exists(installedItemPath)) { tempContentPackage = new ContentPackage(installedItemPath); } } if (File.Exists(tempContentPackage.Path)) { string newContentPackagePath = Path.Combine(WorkshopItemStagingFolder, MetadataFileName); File.Copy(tempContentPackage.Path, newContentPackagePath, overwrite: true); contentPackage = new ContentPackage(newContentPackagePath); foreach (ContentFile contentFile in tempContentPackage.Files) { string sourceFile; if (contentFile.Type == ContentType.Submarine && File.Exists(contentFile.Path)) { sourceFile = contentFile.Path; } else { sourceFile = Path.Combine(existingItem.Directory.FullName, contentFile.Path); } if (!File.Exists(sourceFile)) { continue; } //make sure the destination directory exists string destinationPath = Path.Combine(WorkshopItemStagingFolder, contentFile.Path); Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)); File.Copy(sourceFile, destinationPath, overwrite: true); contentPackage.AddFile(contentFile.Path, contentFile.Type); } } else { contentPackage = ContentPackage.CreatePackage(existingItem.Title, Path.Combine(WorkshopItemStagingFolder, MetadataFileName), false); contentPackage.Save(contentPackage.Path); } }