Exemplo n.º 1
31
        /// <summary>
        /// Determines whether this directory contains the specified path.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns><c>true</c> if this directory contains the specified path; otherwise, <c>false</c>.</returns>
        public bool Contains(UPath path)
        {
            if (path == null) throw new ArgumentNullException("path");
            if (FullPath == null) return false;
            if (path.FullPath == null) return false;

            return path.FullPath.StartsWith(FullPath, StringComparison.OrdinalIgnoreCase) && path.FullPath.Length > FullPath.Length && path.FullPath[FullPath.Length] == DirectorySeparatorChar;
        }
Exemplo n.º 2
0
 public void CheckReferenceDirectoryConstructorProvideAbsolutePathWithUnixPaths()
 {
     var path = new UPath(_unixCurDir, "..\\..");
     var info = new DirectoryInfo(_curDir);
     var expected = Unixify(info.Parent.Parent.FullName).Replace('/', Path.DirectorySeparatorChar);
     Assert.AreEqual(expected, path.ToString());
 }
 public void GetPath(Vector3 target)
 {
     myPath = null;
     pathing.RequestPath(myTransform.position, target, gameObject, gridI);
     curPoint = 0;
     pathComplete = false;
 }
Exemplo n.º 4
0
 public void ReproduceUnixRelativePathNotOnTheSameDrive()
 {
     var unixPath =
         @"/usr/local/teamcity-agent/work/6c86e2555ed64afc/Lx.Tools/Lx.Tools.Projects/Lx.Tools.Projects.Tests/bin/Debug";
     var winPath =
         @"C:\usr\local\teamcity-agent\work\6c86e2555ed64afc\Lx.Tools\Lx.Tools.Projects\Lx.Tools.Projects.Tests\bin\Debug\..\..\Lx.Tools.Projects.Tests.csproj";
     var path1 = new UPath(unixPath);
     var path2 = new UPath(winPath);
     var res = path1.MakeRelativeUPath(path2);
 }
Exemplo n.º 5
0
 // The Vector3 based implementation
 public UPath FindPath(Vector3 startLoc, Vector3 endLoc)
 {
     Vector3 loc1 = gridScript.DetermineNearestPoint(startLoc, endLoc, 0);
     Vector3 loc2 = gridScript.DetermineNearestPoint(endLoc, startLoc, 0);
     int pointLoc1 = DetermineLoc(loc1);
     int pointLoc2 = DetermineLoc(loc2);
     UPath mp = new UPath();
     mp = FindNormalPath(pointLoc1, pointLoc2);
     myPath = mp;
     return mp;
 }
Exemplo n.º 6
0
 UPath BackTrack(int startLoc, int endLoc, int[] lGridLookup, GridPoint[] lGrid)
 {
     int pathSize = 1;
     int loc = endLoc;
     while(loc != startLoc){
         loc = lGrid[lGridLookup[loc]].parent;
         pathSize++;
     }
     UPath mp = new UPath();
     mp.list = new int[pathSize];
     loc = endLoc;
     for(int x = pathSize-1; x >= 0; x--){
         mp.list[x] = loc;
         loc = lGrid[lGridLookup[loc]].parent;
     }
     return mp;
 }
Exemplo n.º 7
0
 // The Interior Implementation
 public void FindMTPath(object x)
 {
     if(mGrid == null){
         int l = gridScript.grids[gridI].grid.Length;
         mGrid = new GridPoint[l];
         for(int z = 0; z < mGrid.Length; z++){
             mGrid[z] = new GridPoint(gridScript.grids[gridI].grid[z]);
         }
     }
     else if(mGrid.Length == 0){
         int l = gridScript.grids[gridI].grid.Length;
         mGrid = new GridPoint[l];
         for(int z = 0; z < mGrid.Length; z++){
             mGrid[z] = new GridPoint(gridScript.grids[gridI].grid[z]);
         }
     }
     if(generate){
         UPath mp = new UPath();
         mp = FindPath(end, start);
         myPath = mp;
         generate = false;
     }
 }
Exemplo n.º 8
0
 public void TestRelativePath2()
 {
     var path1 = new UPath("..\\mydir\\file.cs");
     var path2 = new UPath("../mydir/");
     Assert.AreEqual("file.cs", path2.MakeRelativeUPath(path1).ToString());
 }
Exemplo n.º 9
0
 /// <summary>
 /// Implementation for <see cref="GetFileLength"/>, <paramref name="path"/> is guaranteed to be absolute and validated through <see cref="ValidatePath"/>.
 /// Gets the size, in bytes, of a file.
 /// </summary>
 /// <param name="path">The path of a file.</param>
 /// <returns>The size, in bytes, of the file</returns>
 protected abstract long GetFileLengthImpl(UPath path);
Exemplo n.º 10
0
 public void TestAbsoluteToAbsolutePathWithADifferentDirectory()
 {
     var path1 = new UPath(new FileInfo("../../UPath.cs").FullName);
     var path2 = new UPath(new DirectoryInfo("../../Properties").FullName);
     Assert.AreEqual(".." + Path.DirectorySeparatorChar + "UPath.cs", path2.MakeRelativeUPath(path1).ToString());
 }
Exemplo n.º 11
0
        // ----------------------------------------------
        // File API
        // ----------------------------------------------

        /// <inheritdoc />
        public void CopyFile(UPath srcPath, UPath destPath, bool overwrite)
        {
            AssertNotDisposed();
            CopyFileImpl(ValidatePath(srcPath, nameof(srcPath)), ValidatePath(destPath, nameof(destPath)), overwrite);
        }
Exemplo n.º 12
0
 /// <summary>
 /// Implementation for <see cref="ReplaceFile"/>, <paramref name="srcPath"/>, <paramref name="destPath"/> and <paramref name="destBackupPath"/>
 /// are guaranteed to be absolute and validated through <see cref="ValidatePath"/>.
 /// Replaces the contents of a specified file with the contents of another file, deleting the original file, and creating a backup of the replaced file and optionally ignores merge errors.
 /// </summary>
 /// <param name="srcPath">The path of a file that replaces the file specified by <paramref name="destPath"/>.</param>
 /// <param name="destPath">The path of the file being replaced.</param>
 /// <param name="destBackupPath">The path of the backup file (maybe null, in that case, it doesn't create any backup)</param>
 /// <param name="ignoreMetadataErrors"><c>true</c> to ignore merge errors (such as attributes and access control lists (ACLs)) from the replaced file to the replacement file; otherwise, <c>false</c>.</param>
 protected abstract void ReplaceFileImpl(UPath srcPath, UPath destPath, UPath destBackupPath, bool ignoreMetadataErrors);
Exemplo n.º 13
0
        public static (long, long) Build(Stream input, IList <IArchiveFileInfo> files, UPath rootDirectory)
        {
            // Parse files into file tree
            var rootNode = RomFsDirectoryNode.Parse(files, rootDirectory);

            // Create MetaData Tree
            var metaData = new MetaData
            {
                DirMetaOffset = rootNode.Directories.Count <= 0 ? UnusedEntry_ : 0x18
            };

            metaData.Dirs.Add(new MetaData.DirEntry
            {
                MetaOffset          = 0,
                ParentOffset        = 0,
                NextSiblingOffset   = UnusedEntry_,
                FirstChildOffset    = rootNode.Directories.Count <= 0 ? UnusedEntry_ : 0x18,
                FirstFileOffset     = 0,
                NextDirInSameBucket = UnusedEntry_,
                Hash = CalculatePathHash(0, Encoding.Unicode.GetBytes(string.Empty)),
                Name = string.Empty
            });

            PopulateMetaData(metaData, rootNode, metaData.Dirs[0]);

            // Creating directory hash buckets
            metaData.DirHashTable = Enumerable.Repeat(0xFFFFFFFF, GetHashTableEntryCount(metaData.Dirs.Count)).ToArray();
            PopulateDirHashTable(metaData.Dirs, metaData.DirHashTable);

            // Creating file hash buckets
            metaData.FileHashTable = Enumerable.Repeat(0xFFFFFFFF, GetHashTableEntryCount(metaData.Files.Count)).ToArray();
            PopulateFileHashTable(metaData.Files, metaData.FileHashTable);

            // Write RomFs
            var romFsSizes = WriteRomFs(input, metaData);

            return(romFsSizes);
        }
Exemplo n.º 14
0
 /// <summary>
 /// Implementation for <see cref="MoveDirectory"/>, <paramref name="srcPath"/> and <paramref name="destPath"/>
 /// are guaranteed to be absolute, not equal and different from root `/`, and validated through <see cref="ValidatePath"/>.
 /// Moves a directory and its contents to a new location.
 /// </summary>
 /// <param name="srcPath">The path of the directory to move.</param>
 /// <param name="destPath">The path to the new location for <paramref name="srcPath"/></param>
 protected abstract void MoveDirectoryImpl(UPath srcPath, UPath destPath);
Exemplo n.º 15
0
 public UPath GetDossierDataPath(Dossier dossier)
 {
     return(UPath.Combine(this.BaseDossierPath, $"{dossier.Title}.pdf"));
 }
Exemplo n.º 16
0
 protected override UPath ConvertPathFromDelegate(UPath path) => path;
Exemplo n.º 17
0
        private static async void Startup(UFile initialSessionPath)
        {
            try
            {
                InitializeLanguageSettings();
                var serviceProvider = InitializeServiceProvider();

                try
                {
                    PackageSessionPublicHelper.FindAndSetMSBuildVersion();
                }
                catch (Exception e)
                {
                    var message = "Could not find a compatible version of MSBuild.\r\n\r\n" +
                                  "Check that you have a valid installation with the required workloads, or go to [www.visualstudio.com/downloads](https://www.visualstudio.com/downloads) to install a new one.\r\n\r\n" +
                                  e;
                    await serviceProvider.Get <IEditorDialogService>().MessageBox(message, Core.Presentation.Services.MessageBoxButton.OK, Core.Presentation.Services.MessageBoxImage.Error);

                    app.Shutdown();
                    return;
                }

                // We use a MRU that contains the older version projects to display in the editor
                var mru = new MostRecentlyUsedFileCollection(InternalSettings.LoadProfileCopy, InternalSettings.MostRecentlyUsedSessions, InternalSettings.WriteFile);
                mru.LoadFromSettings();
                var editor = new GameStudioViewModel(serviceProvider, mru);
                AssetsPlugin.RegisterPlugin(typeof(XenkoDefaultAssetsPlugin));
                AssetsPlugin.RegisterPlugin(typeof(XenkoEditorPlugin));

                // Attempt to load the startup session, if available
                if (!UPath.IsNullOrEmpty(initialSessionPath))
                {
                    var sessionLoaded = await editor.OpenInitialSession(initialSessionPath);

                    if (sessionLoaded == true)
                    {
                        var mainWindow = new GameStudioWindow(editor);
                        Application.Current.MainWindow = mainWindow;
                        WindowManager.ShowMainWindow(mainWindow);
                        return;
                    }
                }

                // No session successfully loaded, open the new/open project window
                bool?completed;
                // The user might cancel after chosing a template to instantiate, in this case we'll reopen the window
                var startupWindow = new ProjectSelectionWindow
                {
                    WindowStartupLocation = WindowStartupLocation.CenterScreen,
                    ShowInTaskbar         = true,
                };
                var viewModel = new NewOrOpenSessionTemplateCollectionViewModel(serviceProvider, startupWindow);
                startupWindow.Templates = viewModel;
                startupWindow.ShowDialog();

                // The user selected a template to instantiate
                if (startupWindow.NewSessionParameters != null)
                {
                    // Clean existing entry in the MRU data
                    var directory = startupWindow.NewSessionParameters.OutputDirectory;
                    var name      = startupWindow.NewSessionParameters.OutputName;
                    var mruData   = new MRUAdditionalDataCollection(InternalSettings.LoadProfileCopy, GameStudioInternalSettings.MostRecentlyUsedSessionsData, InternalSettings.WriteFile);
                    mruData.RemoveFile(UFile.Combine(UDirectory.Combine(directory, name), new UFile(name + SessionViewModel.SolutionExtension)));

                    completed = await editor.NewSession(startupWindow.NewSessionParameters);
                }
                // The user selected a path to open
                else if (startupWindow.ExistingSessionPath != null)
                {
                    completed = await editor.OpenSession(startupWindow.ExistingSessionPath);
                }
                // The user cancelled from the new/open project window, so exit the application
                else
                {
                    completed = true;
                }

                if (completed != true)
                {
                    var windowsClosed = new List <Task>();
                    foreach (var window in Application.Current.Windows.Cast <Window>().Where(x => x.IsLoaded))
                    {
                        var tcs = new TaskCompletionSource <int>();
                        window.Unloaded += (s, e) => tcs.SetResult(0);
                        windowsClosed.Add(tcs.Task);
                    }

                    await Task.WhenAll(windowsClosed);

                    // When a project has been partially loaded, it might already have initialized some plugin that could conflict with
                    // the next attempt to start something. Better start the application again.
                    var commandLine = string.Join(" ", Environment.GetCommandLineArgs().Skip(1).Select(x => $"\"{x}\""));
                    var process     = new Process {
                        StartInfo = new ProcessStartInfo(typeof(Program).Assembly.Location, commandLine)
                    };
                    process.Start();
                    app.Shutdown();
                    return;
                }

                if (editor.Session != null)
                {
                    // If a session was correctly loaded, show the main window
                    var mainWindow = new GameStudioWindow(editor);
                    Application.Current.MainWindow = mainWindow;
                    WindowManager.ShowMainWindow(mainWindow);
                }
                else
                {
                    // Otherwise, exit.
                    app.Shutdown();
                }
            }
            catch (Exception)
            {
                app.Shutdown();
            }
        }
Exemplo n.º 18
0
        public static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            EditorPath.EditorTitle = XenkoGameStudio.EditorName;

            if (IntPtr.Size == 4)
            {
                MessageBox.Show("Xenko GameStudio requires a 64bit OS to run.", "Xenko", MessageBoxButton.OK, MessageBoxImage.Error);
                Environment.Exit(1);
            }

            PrivacyPolicyHelper.RestartApplication = RestartApplication;
            PrivacyPolicyHelper.EnsurePrivacyPolicyXenko30();

            // We use MRU of the current version only when we're trying to reload last session.
            var mru = new MostRecentlyUsedFileCollection(InternalSettings.LoadProfileCopy, InternalSettings.MostRecentlyUsedSessions, InternalSettings.WriteFile);

            mru.LoadFromSettings();

            EditorSettings.Initialize();
            Thread.CurrentThread.Name = "Main thread";

            // Install Metrics for the editor
            using (XenkoGameStudio.MetricsClient = new MetricsClient(CommonApps.XenkoEditorAppId))
            {
                try
                {
                    // Environment.GetCommandLineArgs correctly process arguments regarding the presence of '\' and '"'
                    var args = Environment.GetCommandLineArgs().Skip(1).ToList();
                    var startupSessionPath = XenkoEditorSettings.StartupSession.GetValue();
                    var lastSessionPath    = EditorSettings.ReloadLastSession.GetValue() ? mru.MostRecentlyUsedFiles.FirstOrDefault() : null;
                    var initialSessionPath = !UPath.IsNullOrEmpty(startupSessionPath) ? startupSessionPath : lastSessionPath?.FilePath;

                    // Handle arguments
                    for (var i = 0; i < args.Count; i++)
                    {
                        if (args[i] == "/LauncherWindowHandle")
                        {
                            windowHandle = new IntPtr(long.Parse(args[++i]));
                        }
                        else if (args[i] == "/NewProject")
                        {
                            initialSessionPath = null;
                        }
                        else if (args[i] == "/DebugEditorGraphics")
                        {
                            EmbeddedGame.DebugMode = true;
                        }
                        else if (args[i] == "/RenderDoc")
                        {
                            // TODO: RenderDoc is not working here (when not in debug)
                            GameStudioPreviewService.DisablePreview = true;
                            renderDocManager = new RenderDocManager();
                        }
                        else if (args[i] == "/Reattach")
                        {
                            var debuggerProcessId = int.Parse(args[++i]);

                            if (!System.Diagnostics.Debugger.IsAttached)
                            {
                                using (var debugger = VisualStudioDebugger.GetByProcess(debuggerProcessId))
                                {
                                    debugger?.Attach();
                                }
                            }
                        }
                        else if (args[i] == "/RecordEffects")
                        {
                            GameStudioBuilderService.GlobalEffectLogPath = args[++i];
                        }
                        else
                        {
                            initialSessionPath = args[i];
                        }
                    }
                    RuntimeHelpers.RunModuleConstructor(typeof(Asset).Module.ModuleHandle);

                    //listen to logger for crash report
                    GlobalLogger.GlobalMessageLogged += GlobalLoggerOnGlobalMessageLogged;

                    mainDispatcher = Dispatcher.CurrentDispatcher;
                    mainDispatcher.InvokeAsync(() => Startup(initialSessionPath));

                    using (new WindowManager(mainDispatcher))
                    {
                        app = new App {
                            ShutdownMode = ShutdownMode.OnExplicitShutdown
                        };
                        app.Activated += (sender, eventArgs) =>
                        {
                            XenkoGameStudio.MetricsClient?.SetActiveState(true);
                        };
                        app.Deactivated += (sender, eventArgs) =>
                        {
                            XenkoGameStudio.MetricsClient?.SetActiveState(false);
                        };

                        app.InitializeComponent();
                        app.Run();
                    }

                    renderDocManager?.Shutdown();
                }
                catch (Exception e)
                {
                    HandleException(e, 0);
                }
            }
        }
Exemplo n.º 19
0
        protected override void Compile(AssetCompilerContext context, string urlInStorage, UFile assetAbsolutePath, SpriteFontAsset asset, AssetCompilerResult result)
        {
            var colorSpace = context.GetColorSpace();

            if (asset.IsDynamic)
            {
                UFile fontPathOnDisk;

                if (!string.IsNullOrEmpty(asset.Source))
                {
                    var assetDirectory = assetAbsolutePath.GetParent();
                    fontPathOnDisk = UPath.Combine(assetDirectory, asset.Source);
                    if (!File.Exists(fontPathOnDisk))
                    {
                        result.Error("The font source '{0}' does not exist on the PC.", asset.FontName);
                        return;
                    }
                    // set the source filename as font name instead of the font family.
                    asset.FontName = fontPathOnDisk.GetFileName();
                }
                else
                {
                    fontPathOnDisk = GetFontPath(asset, result);
                    if (fontPathOnDisk == null)
                    {
                        result.Error("The font named '{0}' could not be located on the PC.", asset.FontName);
                        return;
                    }
                }
                var fontImportLocation = FontHelper.GetFontPath(asset.FontName, asset.Style);

                result.BuildSteps = new AssetBuildStep(AssetItem)
                {
                    new ImportStreamCommand {
                        SourcePath = fontPathOnDisk, Location = fontImportLocation
                    },
                    new DynamicFontCommand(urlInStorage, asset)
                };
            }
            else
            {
                // copy the asset and transform the source and character set file path to absolute paths
                var assetClone     = (SpriteFontAsset)AssetCloner.Clone(asset);
                var assetDirectory = assetAbsolutePath.GetParent();
                assetClone.Source       = !string.IsNullOrEmpty(asset.Source) ? UPath.Combine(assetDirectory, asset.Source): null;
                assetClone.CharacterSet = !string.IsNullOrEmpty(asset.CharacterSet) ? UPath.Combine(assetDirectory, asset.CharacterSet): null;

                result.BuildSteps = new AssetBuildStep(AssetItem)
                {
                    new StaticFontCommand(urlInStorage, assetClone, colorSpace)
                };
            }
        }
        protected override void Compile(AssetCompilerContext context, AssetItem assetItem, string targetUrlInStorage, AssetCompilerResult result)
        {
            var asset             = (SpriteSheetAsset)assetItem.Asset;
            var gameSettingsAsset = context.GetGameSettingsAsset();
            var renderingSettings = gameSettingsAsset.Get <RenderingSettings>(context.Platform);

            result.BuildSteps = new ListBuildStep();

            // create the registry containing the sprite assets texture index association
            var imageToTextureUrl = new Dictionary <SpriteInfo, string>();

            var colorSpace = context.GetColorSpace();

            // create and add import texture commands
            if (asset.Sprites != null && !asset.Packing.Enabled)
            {
                // sort sprites by referenced texture.
                var spriteByTextures = asset.Sprites.GroupBy(x => x.Source).ToArray();
                for (int i = 0; i < spriteByTextures.Length; i++)
                {
                    // skip the texture if the file is not valid.
                    var textureFile = spriteByTextures[i].Key;
                    if (!TextureFileIsValid(textureFile))
                    {
                        continue;
                    }

                    var textureUrl = SpriteSheetAsset.BuildTextureUrl(targetUrlInStorage, i);

                    var spriteAssetArray = spriteByTextures[i].ToArray();
                    foreach (var spriteAsset in spriteAssetArray)
                    {
                        imageToTextureUrl[spriteAsset] = textureUrl;
                    }

                    // create an texture asset.
                    var textureAsset = new TextureAsset
                    {
                        Id               = AssetId.Empty, // CAUTION: It is important to use an empty GUID here, as we don't want the command to be rebuilt (by default, a new asset is creating a new guid)
                        Alpha            = asset.Alpha,
                        Format           = asset.Format,
                        GenerateMipmaps  = asset.GenerateMipmaps,
                        PremultiplyAlpha = asset.PremultiplyAlpha,
                        ColorKeyColor    = asset.ColorKeyColor,
                        ColorKeyEnabled  = asset.ColorKeyEnabled,
                        ColorSpace       = asset.ColorSpace,
                        Hint             = TextureHint.Color
                    };

                    // Get absolute path of asset source on disk
                    var assetDirectory = assetItem.FullPath.GetParent();
                    var assetSource    = UPath.Combine(assetDirectory, spriteAssetArray[0].Source);

                    // add the texture build command.
                    result.BuildSteps.Add(new AssetBuildStep(new AssetItem(textureUrl, textureAsset))
                    {
                        new TextureAssetCompiler.TextureConvertCommand(
                            textureUrl,
                            new TextureConvertParameters(assetSource, textureAsset, context.Platform, context.GetGraphicsPlatform(assetItem.Package), renderingSettings.DefaultGraphicsProfile, gameSettingsAsset.Get <TextureSettings>().TextureQuality, colorSpace))
                    });
                }
            }

            if (!result.HasErrors)
            {
                var parameters = new SpriteSheetParameters(asset, imageToTextureUrl, context.Platform, context.GetGraphicsPlatform(assetItem.Package), renderingSettings.DefaultGraphicsProfile, gameSettingsAsset.Get <TextureSettings>().TextureQuality, colorSpace);
                result.BuildSteps.Add(new AssetBuildStep(assetItem)
                {
                    new SpriteSheetCommand(targetUrlInStorage, parameters)
                });
            }
        }
Exemplo n.º 21
0
 void RegisterItem(UFile targetFilePath)
 {
     generatedItems.Add((targetFilePath.ToWindowsPath(), UPath.Combine("stride", targetFilePath.MakeRelative(outputPath)).ToWindowsPath()));
 }
Exemplo n.º 22
0
 public void TestRelativePath5()
 {
     var path1 = new UPath("..\\dir1\\dir2\\dir3\\file.cs");
     var path2 = new UPath("../dir1/dir2");
     Assert.AreEqual("dir3" + Path.DirectorySeparatorChar + "file.cs", path2.MakeRelativeUPath(path1).ToString());
 }
Exemplo n.º 23
0
        public override ContentResult TryProcessContent(ContentObject file, ContentProcessingStage stage)
        {
            var contentType = file.ContentType;

            // This plugin is only working on scss files
            if (contentType != ScssType)
            {
                return(ContentResult.None);
            }

            if (file.Content == null)
            {
                file.Content = file.SourceFile.ReadAllText();
            }

            var content = file.Content;

            var options = new ScssOptions();

            options.InputFile = (string)file.Path;

            var includePaths = new List <DirectoryEntry>();

            foreach (var pathObj in Plugin.Includes)
            {
                var path = pathObj as string;
                if (path != null && UPath.TryParse(path, out var validPath) && Site.MetaFileSystem.DirectoryExists(validPath))
                {
                    includePaths.Add(new DirectoryEntry(Site.MetaFileSystem, validPath));
                }
                else
                {
                    Site.Error($"Invalid folder path `{pathObj}` found in site.scss.includes.");
                }
            }

            var tempIncludePaths = new List <DirectoryEntry>();

            var extensions = new string[] { ".scss", ".sass", ".css" };

            var includedFiles = new List <FileEntry>();

            options.TryImport = (ref string file, string parentpath, out string scss, out string map) =>
            {
                scss = null;
                map  = null;

                // From: https://sass-lang.com/documentation/at-rules/import#load-paths
                // Imports will always be resolved relative to the current file first, though.
                // Load paths will only be used if no relative file exists that matches the import.
                // This ensures that you can’t accidentally mess up your relative imports when you add a new library.
                tempIncludePaths.Clear();
                UPath filePath      = (UPath)file;
                var   directoryName = ((UPath)parentpath).GetDirectory();
                if (!directoryName.IsNull && directoryName.IsAbsolute)
                {
                    DirectoryEntry localDirEntry = null;
                    if (Site.FileSystem.DirectoryExists(directoryName))
                    {
                        localDirEntry = new DirectoryEntry(Site.FileSystem, directoryName);
                        if (!tempIncludePaths.Contains(localDirEntry))
                        {
                            tempIncludePaths.Add(localDirEntry);
                        }
                    }

                    if (Site.MetaFileSystem.DirectoryExists(directoryName))
                    {
                        localDirEntry = new DirectoryEntry(Site.MetaFileSystem, directoryName);
                        if (!tempIncludePaths.Contains(localDirEntry))
                        {
                            tempIncludePaths.Add(localDirEntry);
                        }
                    }
                }

                tempIncludePaths.AddRange(includePaths);

                // From libsass, order for ambiguous import:
                // (1) filename as given
                // (2) underscore + given
                // (3) underscore + given + extension
                // (4) given + extension
                // (5) given + _index.scss
                // (6) given + _index.sass
                var ufile          = (UPath)file;
                var relativeFolder = ufile.GetDirectory();
                var filename       = ufile.GetName();

                bool Resolve(FileEntry entry, out string scss, out string file)
                {
                    scss = null;
                    file = null;
                    if (entry.Exists)
                    {
                        scss = entry.ReadAllText();
                        file = (string)entry.Path;
                        includedFiles.Add(entry);
                        return(true);
                    }

                    return(false);
                }

                foreach (var dirEntry in tempIncludePaths)
                {
                    var rootFolder = dirEntry.Path / relativeFolder;

                    // (1) filename as given
                    if (Resolve(new FileEntry(dirEntry.FileSystem, rootFolder / filename), out scss, out file))
                    {
                        return(true);
                    }

                    // (2) underscore + given
                    if (Resolve(new FileEntry(dirEntry.FileSystem, rootFolder / $"_{filename}"), out scss, out file))
                    {
                        return(true);
                    }

                    // (3) underscore + given + extension
                    foreach (var extension in extensions)
                    {
                        if (Resolve(new FileEntry(dirEntry.FileSystem, rootFolder / $"_{filename}{extension}"), out scss, out file))
                        {
                            return(true);
                        }
                    }

                    // (4) given + extension
                    foreach (var extension in extensions)
                    {
                        if (Resolve(new FileEntry(dirEntry.FileSystem, rootFolder / $"{filename}{extension}"), out scss, out file))
                        {
                            return(true);
                        }
                    }

                    // (5) given + _index.scss
                    if (Resolve(new FileEntry(dirEntry.FileSystem, rootFolder / $"{filename}" / "_index.scss"), out scss, out file))
                    {
                        return(true);
                    }

                    // (6) given + _index.sass
                    if (Resolve(new FileEntry(dirEntry.FileSystem, rootFolder / $"{filename}" / "_index.sass"), out scss, out file))
                    {
                        return(true);
                    }
                }

                return(false);
            };

            var result = SharpScss.Scss.ConvertToCss(content, options);

            file.Content = result.Css;
            file.ChangeContentType(ContentType.Css);

            foreach (var includeFile in includedFiles)
            {
                file.Dependencies.Add(new FileContentDependency(includeFile));
            }

            return(ContentResult.Continue);
        }
Exemplo n.º 24
0
 public void TestRelativeToAbsolutePath()
 {
     var path1 = new UPath("../file.cs");
     var path2 = new UPath(_winCurDir);
     Assert.AreEqual("../file.cs".Replace('/', Path.DirectorySeparatorChar),
         path2.MakeRelativeUPath(path1).ToString());
 }
Exemplo n.º 25
0
        /// <inheritdoc />
        protected override IFileSystemWatcher WatchImpl(UPath path)
        {
            var delegateWatcher = base.WatchImpl(path);

            return(new Watcher(this, path, delegateWatcher));
        }
Exemplo n.º 26
0
        /// <summary>
        /// Raise the <see cref="IFileSystemWatcher.Renamed"/> event on watchers.
        /// </summary>
        /// <param name="newPath">Absolute path to the new file or directory.</param>
        /// <param name="oldPath">Absolute path to the old file or directory.</param>
        public void RaiseRenamed(UPath newPath, UPath oldPath)
        {
            var args = new FileRenamedEventArgs(FileSystem, WatcherChangeTypes.Renamed, newPath, oldPath);

            Dispatch(args, (w, a) => w.RaiseRenamed(a));
        }
Exemplo n.º 27
0
 public Watcher(SubFileSystem fileSystem, UPath path, IFileSystemWatcher watcher)
     : base(fileSystem, path, watcher)
 {
     this._fileSystem = fileSystem;
 }
Exemplo n.º 28
0
 /// <summary>
 /// Implementation for <see cref="DeleteDirectory"/>, <paramref name="path"/> is guaranteed to be absolute and different from root path `/` and validated through <see cref="ValidatePath"/>.
 /// Deletes the specified directory and, if indicated, any subdirectories and files in the directory.
 /// </summary>
 /// <param name="path">The path of the directory to remove.</param>
 /// <param name="isRecursive"><c>true</c> to remove directories, subdirectories, and files in path; otherwise, <c>false</c>.</param>
 protected abstract void DeleteDirectoryImpl(UPath path, bool isRecursive);
Exemplo n.º 29
0
        /// <inheritdoc />
        protected override UPath ConvertPathToDelegate(UPath path)
        {
            var safePath = path.ToRelative();

            return(this.SubPath / safePath);
        }
Exemplo n.º 30
0
 /// <summary>
 /// Implementation for <see cref="CopyFile"/>, <paramref name="srcPath"/> and <paramref name="destPath"/>
 /// are guaranteed to be absolute and validated through <see cref="ValidatePath"/>.
 /// Copies an existing file to a new file. Overwriting a file of the same name is allowed.
 /// </summary>
 /// <param name="srcPath">The path of the file to copy.</param>
 /// <param name="destPath">The path of the destination file. This cannot be a directory.</param>
 /// <param name="overwrite"><c>true</c> if the destination file can be overwritten; otherwise, <c>false</c>.</param>
 protected abstract void CopyFileImpl(UPath srcPath, UPath destPath, bool overwrite);
Exemplo n.º 31
0
        /// <summary>
        /// Raise the <see cref="IFileSystemWatcher.Opened"/> event on watchers.
        /// </summary>
        /// <param name="path">Absolute path to the opened file.</param>
        public void RaiseOpened(UPath path)
        {
            var args = new FileOpenedEventArgs(path);

            Dispatch(args, (w, a) => w.RaiseOpened(a));
        }
Exemplo n.º 32
0
 /// <inheritdoc />
 public long GetFileLength(UPath path)
 {
     AssertNotDisposed();
     return(GetFileLengthImpl(ValidatePath(path)));
 }
Exemplo n.º 33
0
        public async Task Load(IFileSystem fileSystem, UPath filePath, LoadContext loadContext)
        {
            var fileStream = await fileSystem.OpenFileAsync(filePath);

            Images = new IKanvasImage[] { new KanvasImage(EncodingDefinition, _jtex.Load(fileStream)) };
        }
Exemplo n.º 34
0
 /// <summary>
 /// Implementation for <see cref="FileExists"/>, <paramref name="path"/> is guaranteed to be absolute and validated through <see cref="ValidatePath"/>.
 /// Determines whether the specified file exists.
 /// </summary>
 /// <param name="path">The path.</param>
 /// <returns><c>true</c> if the caller has the required permissions and path contains the name of an existing file;
 /// otherwise, <c>false</c>. This method also returns false if path is null, an invalid path, or a zero-length string.
 /// If the caller does not have sufficient permissions to read the specified file,
 /// no exception is thrown and the method returns false regardless of the existence of path.</returns>
 protected abstract bool FileExistsImpl(UPath path);
Exemplo n.º 35
0
 public static UPath NormalizePath(this UPath path) => AsNormalizePath(path.FullName);
Exemplo n.º 36
0
 public void TestAbsoluteWithDifferentDrives()
 {
     var path1 = new UPath(@"D:\FileNotExists.cs");
     var path2 = new UPath(@"C:\NotExisting");
     var res = path2.MakeRelativeUPath(path1).ToString();
 }
Exemplo n.º 37
0
 public void TestAbsoluteToAbsolutePath()
 {
     var path1 = new UPath(new FileInfo("../../UPath.cs").FullName);
     var path2 = new UPath(new DirectoryInfo("../../").FullName);
     Assert.AreEqual("UPath.cs", path2.MakeRelativeUPath(path1).ToString());
 }
Exemplo n.º 38
0
 public void TestRelativePath4()
 {
     var path1 = new UPath("..\\dir1\\dir2\\dir3\\file.cs");
     var path2 = new UPath("../dir1/dir2/dir3");
     Assert.AreEqual("file.cs", path2.MakeRelativeUPath(path1).ToString());
 }
Exemplo n.º 39
0
 public void TestRelativeToRelativePathNotResolvable()
 {
     var path1 = new UPath("FileNotExists.cs");
     var path2 = new UPath("../NotExisting");
     var res = path2.MakeRelativeUPath(path1).ToString();
 }
Exemplo n.º 40
0
 public void TestRelativePathInCurrentDir()
 {
     var path1 = new UPath("mydir\\dir2\\file.cs");
     var path2 = new UPath("mydir");
     Assert.AreEqual("dir2/file.cs".Replace('/', Path.DirectorySeparatorChar),
         path2.MakeRelativeUPath(path1).ToString());
 }
Exemplo n.º 41
0
 public void CheckReferenceDirectoryConstructorProvideAbsolutePath()
 {
     var path = new UPath(_curDir, "..\\..");
     var info = new DirectoryInfo(_curDir);
     Assert.AreEqual(info.Parent.Parent.FullName, path.ToString());
 }
Exemplo n.º 42
0
 public void TestRelativeToCurrentPath()
 {
     var path1 = new UPath("../file.cs");
     var path2 = new UPath(".");
     Assert.AreEqual(".." + Path.DirectorySeparatorChar + "file.cs", path2.MakeRelativeUPath(path1).ToString());
 }
Exemplo n.º 43
0
 public static int CountDirectories(IList <ArchiveFileInfo> files, UPath rootDirectory)
 {
     return(files.Select(x => x.FilePath.GetSubDirectory(rootDirectory.ToAbsolute()).GetDirectory())
            .Distinct()
            .Count());
 }
Exemplo n.º 44
0
 public void TestWinVsUnixRoots()
 {
     var path1 = new UPath(_winCurDir.Replace('\\', '/') + "/root.cs");
     var path2 = new UPath(_winCurDir.Replace('/', '\\'));
     Assert.AreEqual("root.cs", path2.MakeRelativeUPath(path1).ToString());
 }
Exemplo n.º 45
0
        protected override void Prepare(AssetCompilerContext context, AssetItem assetItem, string targetUrlInStorage, AssetCompilerResult result)
        {
            var asset             = (AnimationAsset)assetItem.Asset;
            var assetAbsolutePath = assetItem.FullPath;
            // Get absolute path of asset source on disk
            var assetDirectory = assetAbsolutePath.GetParent();
            var assetSource    = GetAbsolutePath(assetItem, asset.Source);
            var extension      = assetSource.GetFileExtension();
            var buildStep      = new AssetBuildStep(assetItem);

            // Find skeleton asset, if any
            AssetItem skeleton = null;

            if (asset.Skeleton != null)
            {
                skeleton = assetItem.Package.FindAssetFromProxyObject(asset.Skeleton);
            }

            var sourceBuildCommand = ImportModelCommand.Create(extension);

            if (sourceBuildCommand == null)
            {
                result.Error($"No importer found for model extension '{extension}. The model '{assetSource}' can't be imported.");
                return;
            }

            sourceBuildCommand.Mode                   = ImportModelCommand.ExportMode.Animation;
            sourceBuildCommand.SourcePath             = assetSource;
            sourceBuildCommand.Location               = targetUrlInStorage;
            sourceBuildCommand.AnimationRepeatMode    = asset.RepeatMode;
            sourceBuildCommand.AnimationRootMotion    = asset.RootMotion;
            sourceBuildCommand.ImportCustomAttributes = asset.ImportCustomAttributes;
            if (asset.ClipDuration.Enabled)
            {
                sourceBuildCommand.StartFrame = asset.ClipDuration.StartAnimationTime;
                sourceBuildCommand.EndFrame   = asset.ClipDuration.EndAnimationTime;
            }
            else
            {
                sourceBuildCommand.StartFrame = TimeSpan.Zero;
                sourceBuildCommand.EndFrame   = AnimationAsset.LongestTimeSpan;
            }
            sourceBuildCommand.ScaleImport   = asset.ScaleImport;
            sourceBuildCommand.PivotPosition = asset.PivotPosition;

            if (skeleton != null)
            {
                sourceBuildCommand.SkeletonUrl = skeleton.Location;
                // Note: skeleton override values
                sourceBuildCommand.ScaleImport   = ((SkeletonAsset)skeleton.Asset).ScaleImport;
                sourceBuildCommand.PivotPosition = ((SkeletonAsset)skeleton.Asset).PivotPosition;
            }

            if (asset.Type.Type == AnimationAssetTypeEnum.AnimationClip)
            {
                // Import the main animation
                buildStep.Add(sourceBuildCommand);
            }
            else if (asset.Type.Type == AnimationAssetTypeEnum.DifferenceClip)
            {
                var diffAnimationAsset = ((DifferenceAnimationAssetType)asset.Type);
                var referenceClip      = diffAnimationAsset.BaseSource;
                var rebaseMode         = diffAnimationAsset.Mode;

                var baseUrlInStorage   = targetUrlInStorage + RefClipSuffix;
                var sourceUrlInStorage = targetUrlInStorage + SrcClipSuffix;

                var baseAssetSource = UPath.Combine(assetDirectory, referenceClip);
                var baseExtension   = baseAssetSource.GetFileExtension();

                sourceBuildCommand.Location = sourceUrlInStorage;

                var baseBuildCommand = ImportModelCommand.Create(extension);
                if (baseBuildCommand == null)
                {
                    result.Error($"No importer found for model extension '{baseExtension}. The model '{baseAssetSource}' can't be imported.");
                    return;
                }

                baseBuildCommand.FailOnEmptyAnimation = false;
                baseBuildCommand.Mode                = ImportModelCommand.ExportMode.Animation;
                baseBuildCommand.SourcePath          = baseAssetSource;
                baseBuildCommand.Location            = baseUrlInStorage;
                baseBuildCommand.AnimationRepeatMode = asset.RepeatMode;
                baseBuildCommand.AnimationRootMotion = asset.RootMotion;

                if (diffAnimationAsset.ClipDuration.Enabled)
                {
                    baseBuildCommand.StartFrame = diffAnimationAsset.ClipDuration.StartAnimationTimeBox;
                    baseBuildCommand.EndFrame   = diffAnimationAsset.ClipDuration.EndAnimationTimeBox;
                }
                else
                {
                    baseBuildCommand.StartFrame = TimeSpan.Zero;
                    baseBuildCommand.EndFrame   = AnimationAsset.LongestTimeSpan;
                }

                baseBuildCommand.ScaleImport   = asset.ScaleImport;
                baseBuildCommand.PivotPosition = asset.PivotPosition;

                if (skeleton != null)
                {
                    baseBuildCommand.SkeletonUrl = skeleton.Location;
                    // Note: skeleton override values
                    baseBuildCommand.ScaleImport   = ((SkeletonAsset)skeleton.Asset).ScaleImport;
                    baseBuildCommand.PivotPosition = ((SkeletonAsset)skeleton.Asset).PivotPosition;
                }

                // Import base and main animation
                var sourceStep = new CommandBuildStep(sourceBuildCommand);
                buildStep.Add(sourceStep);
                var baseStep = new CommandBuildStep(baseBuildCommand);
                buildStep.Add(baseStep);

                IEnumerable <ObjectUrl> InputFilesGetter()
                {
                    yield return(new ObjectUrl(UrlType.File, GetAbsolutePath(assetItem, diffAnimationAsset.BaseSource)));
                }

                var diffCommand = new AdditiveAnimationCommand(targetUrlInStorage, new AdditiveAnimationParameters(baseUrlInStorage, sourceUrlInStorage, rebaseMode), assetItem.Package)
                {
                    InputFilesGetter = InputFilesGetter
                };

                var diffStep = new CommandBuildStep(diffCommand);

                BuildStep.LinkBuildSteps(sourceStep, diffStep);
                BuildStep.LinkBuildSteps(baseStep, diffStep);

                // Generate the diff of those two animations
                buildStep.Add(diffStep);
            }
            else
            {
                throw new NotImplementedException("This type of animation asset is not supported yet!");
            }

            result.BuildSteps = buildStep;
        }
Exemplo n.º 46
0
        protected virtual bool IsValidName(string value, out string error)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            if (value.Length > 240)
            {
                error = Tr._p("Message", "The name is too long.");
                return(false);
            }

            if (value.Contains(UPath.DirectorySeparatorChar) || value.Contains(UPath.DirectorySeparatorCharAlt) || !UPath.IsValid(value))
            {
                error = Tr._p("Message", "The name contains invalid characters.");
                return(false);
            }

            if (string.IsNullOrEmpty(value))
            {
                error = Tr._p("Message", "The name is empty.");
                return(false);
            }

            error = null;

            return(true);
        }
Exemplo n.º 47
0
        /// <summary>
        /// Raise the <see cref="IFileSystemWatcher.Deleted"/> event on watchers.
        /// </summary>
        /// <param name="path">Absolute path to the changed file or directory.</param>
        public void RaiseDeleted(UPath path)
        {
            var args = new FileChangedEventArgs(FileSystem, WatcherChangeTypes.Deleted, path);

            Dispatch(args, (w, a) => w.RaiseDeleted(a));
        }
Exemplo n.º 48
0
 public void TestAbsoluteToAbsolutePath2()
 {
     var path1 = new UPath(new FileInfo("../../Properties/AssemblyInfo.cs").FullName);
     var path2 = new UPath(new DirectoryInfo("../../").FullName);
     Assert.AreEqual("Properties" + Path.DirectorySeparatorChar + "AssemblyInfo.cs",
         path2.MakeRelativeUPath(path1).ToString());
 }
Exemplo n.º 49
0
        public override bool Upgrade(PackageSession session, ILogger log, Package dependentPackage, PackageDependency dependency, Package dependencyPackage, IList <PackageLoadingAssetFile> assetFiles)
        {
            // Paradox 1.1 projects didn't have their dependency properly updated (they might have been marked as 1.0).
            // We know they are 1.1 only because there is a .props file.
            // This check shouldn't be necessary from 1.2.
            var packagePath   = dependentPackage.FullPath;
            var propsFilePath = UPath.Combine(packagePath.GetParent(), (UFile)(packagePath.GetFileName() + ".props"));

            if (!File.Exists(propsFilePath) && dependency.Version.MinVersion < new PackageVersion("1.1.0-beta"))
            {
                log.Error("Can't upgrade old projects from {0} 1.0 to 1.1", dependency.Name);
                return(false);
            }

            // Nothing to do for now, most of the work is already done by individual asset upgraders
            // We can later add logic here for package-wide upgrades (i.e. GameSettingsAsset)
            if (dependency.Version.MinVersion < new PackageVersion("1.2.0-beta"))
            {
                // UIImageGroups and SpriteGroups asset have been merged into a single SpriteSheet => rename the assets and modify the tag
                var uiImageGroups = assetFiles.Where(f => f.FilePath.GetFileExtension() == ".pdxuiimage");
                var spritesGroups = assetFiles.Where(f => f.FilePath.GetFileExtension() == ".pdxsprite");
                RenameAndChangeTag(assetFiles, uiImageGroups, "!UIImageGroup");
                RenameAndChangeTag(assetFiles, spritesGroups, "!SpriteGroup");
            }

            if (dependency.Version.MinVersion < new PackageVersion("1.3.0-alpha01"))
            {
                // Create GameSettingsAsset
                GameSettingsAsset.UpgraderVersion130.Upgrade(session, log, dependentPackage, dependency, dependencyPackage, assetFiles);
            }

            if (dependency.Version.MinVersion < new PackageVersion("1.3.0-alpha02"))
            {
                // Delete EffectLogAsset
                foreach (var assetFile in assetFiles)
                {
                    if (assetFile.FilePath.GetFileName() == EffectLogAsset.DefaultFile)
                    {
                        assetFile.Deleted = true;
                    }
                }
            }

            if (dependency.Version.MinVersion < new PackageVersion("1.4.0-beta"))
            {
                // Update file extensions with Xenko prefix
                var legacyAssets = from assetFile in assetFiles
                                   where !assetFile.Deleted
                                   let extension = assetFile.FilePath.GetFileExtension()
                                                   where extension.StartsWith(".pdx")
                                                   select new { AssetFile = assetFile, NewExtension = ".xk" + extension.Substring(4) };

                foreach (var legacyAsset in legacyAssets.ToArray())
                {
                    // Load asset data, so the renamed file will have it's AssetContent set
                    if (legacyAsset.AssetFile.AssetContent == null)
                    {
                        legacyAsset.AssetFile.AssetContent = File.ReadAllBytes(legacyAsset.AssetFile.FilePath);
                    }

                    // Change legacy namespaces and default effect names in all shader source files
                    // TODO: Use syntax analysis? What about shaders referenced in other assets?
                    if (legacyAsset.NewExtension == ".xksl" || legacyAsset.NewExtension == ".xkfx" || legacyAsset.NewExtension == ".xkeffectlog")
                    {
                        var sourceText    = System.Text.Encoding.UTF8.GetString(legacyAsset.AssetFile.AssetContent);
                        var newSourceText = sourceText.Replace("Paradox", "Xenko");

                        if (newSourceText != sourceText)
                        {
                            legacyAsset.AssetFile.AssetContent = System.Text.Encoding.UTF8.GetBytes(newSourceText);
                        }
                    }

                    // Create asset copy with new extension
                    ChangeFileExtension(assetFiles, legacyAsset.AssetFile, legacyAsset.NewExtension);
                }

                // Force loading of user settings with old extension
                var userSettings = dependentPackage.UserSettings;

                // Change package extension
                dependentPackage.FullPath = new UFile(dependentPackage.FullPath.GetFullPathWithoutExtension(), Package.PackageFileExtension);

                // Make sure all assets are upgraded
                RunAssetUpgradersUntilVersion(log, dependentPackage, XenkoConfig.PackageName, assetFiles, PackageVersion.Parse("1.4.0-beta"));
            }

            if (dependency.Version.MinVersion < new PackageVersion("1.5.0-alpha01"))
            {
                RunAssetUpgradersUntilVersion(log, dependentPackage, XenkoConfig.PackageName, assetFiles, PackageVersion.Parse("1.5.0-alpha01"));
            }

            if (dependency.Version.MinVersion < new PackageVersion("1.5.0-alpha02"))
            {
                // Ideally, this should be part of asset upgrader but we can't upgrade multiple assets at once yet

                var modelAssets = assetFiles.Where(f => f.FilePath.GetFileExtension() == ".xkm3d").Select(x => x.AsYamlAsset()).ToArray();
                var animAssets  = assetFiles.Where(f => f.FilePath.GetFileExtension() == ".xkanim").Select(x => x.AsYamlAsset()).ToArray();
                var sceneAssets = assetFiles.Where(f => f.FilePath.GetFileExtension() == ".xkscene").Select(x => x.AsYamlAsset()).ToArray();

                // Select models with at least two nodes
                var modelAssetsWithSekeleton = modelAssets
                                               .Where(model => ((IEnumerable)model.DynamicRootNode.Nodes).Cast <object>().Count() > 1).ToArray();

                var animToModelMapping = new Dictionary <PackageLoadingAssetFile.YamlAsset, PackageLoadingAssetFile.YamlAsset>();

                // Find associations in scene
                foreach (var sceneAsset in sceneAssets)
                {
                    var hierarchy = sceneAsset.DynamicRootNode.Hierarchy;
                    foreach (dynamic entity in hierarchy.Entities)
                    {
                        var components         = entity.Entity.Components;
                        var animationComponent = components["AnimationComponent.Key"];
                        var model = components["ModelComponent.Key"]?.Model;
                        if (animationComponent != null && model != null)
                        {
                            var modelReference = DynamicYamlExtensions.ConvertTo <AssetReference <Asset> >(model);
                            var modelAsset     = modelAssetsWithSekeleton.FirstOrDefault(x => x.Asset.AssetPath == modelReference.Location);

                            foreach (var animation in animationComponent.Animations)
                            {
                                var animationReference = DynamicYamlExtensions.ConvertTo <AssetReference <Asset> >(animation.Value);
                                var animationAsset     = animAssets.FirstOrDefault(x => x.Asset.AssetPath == animationReference.Location);

                                if (modelAsset != null && animationAsset != null)
                                {
                                    animToModelMapping[animationAsset] = modelAsset;
                                }
                            }
                        }
                    }
                }

                // Find associations when sharing same source file
                foreach (var animationAsset in animAssets)
                {
                    // Comparing absolute path of assets
                    var modelAsset = modelAssetsWithSekeleton.FirstOrDefault(
                        x => UPath.Combine(animationAsset.Asset.AssetPath.GetParent(), new UFile((string)animationAsset.DynamicRootNode.Source))
                        == UPath.Combine(x.Asset.AssetPath.GetParent(), new UFile((string)x.DynamicRootNode.Source)));
                    if (modelAsset != null)
                    {
                        animToModelMapping[animationAsset] = modelAsset;
                    }
                }

                var modelToSkeletonMapping = new Dictionary <PackageLoadingAssetFile.YamlAsset, PackageLoadingAssetFile.YamlAsset>();

                // For each model asset, create skeleton assets
                foreach (var modelAsset in modelAssetsWithSekeleton)
                {
                    var skeletonAsset = new PackageLoadingAssetFile(modelAsset.Asset.FilePath.GetFullPathWithoutExtension() + " Skeleton.xkskel", modelAsset.Asset.SourceFolder)
                    {
                        AssetContent = System.Text.Encoding.UTF8.GetBytes("!Skeleton\r\nId: " + Guid.NewGuid())
                    };

                    using (var skeletonAssetYaml = skeletonAsset.AsYamlAsset())
                    {
                        // Set source
                        skeletonAssetYaml.DynamicRootNode.Source     = modelAsset.DynamicRootNode.Source;
                        skeletonAssetYaml.DynamicRootNode.SourceHash = modelAsset.DynamicRootNode.SourceHash;

                        // To be on the safe side, mark everything as preserved
                        var nodes = modelAsset.DynamicRootNode.Nodes;
                        foreach (var node in nodes)
                        {
                            node.Preserve = true;
                        }

                        skeletonAssetYaml.DynamicRootNode.Nodes       = nodes;
                        skeletonAssetYaml.DynamicRootNode.ScaleImport = modelAsset.DynamicRootNode.ScaleImport;

                        // Update model to point to this skeleton
                        modelAsset.DynamicRootNode.Skeleton = new AssetReference <Asset>(Guid.Parse((string)skeletonAssetYaml.DynamicRootNode.Id), skeletonAsset.AssetPath.MakeRelative(modelAsset.Asset.AssetPath.GetParent()));
                        modelToSkeletonMapping.Add(modelAsset, skeletonAssetYaml);
                    }

                    assetFiles.Add(skeletonAsset);
                }

                // Update animation to point to skeleton, and set preview default model
                foreach (var animToModelEntry in animToModelMapping)
                {
                    var animationAsset = animToModelEntry.Key;
                    var modelAsset     = animToModelEntry.Value;

                    var skeletonAsset = modelToSkeletonMapping[modelAsset];
                    animationAsset.DynamicRootNode.Skeleton     = new AssetReference <Asset>(Guid.Parse((string)skeletonAsset.DynamicRootNode.Id), skeletonAsset.Asset.AssetPath.MakeRelative(animationAsset.Asset.AssetPath.GetParent()));
                    animationAsset.DynamicRootNode.PreviewModel = new AssetReference <Asset>(Guid.Parse((string)modelAsset.DynamicRootNode.Id), modelAsset.Asset.AssetPath.MakeRelative(animationAsset.Asset.AssetPath.GetParent()));
                }

                // Remove Nodes from models
                foreach (var modelAsset in modelAssets)
                {
                    modelAsset.DynamicRootNode.Nodes = DynamicYamlEmpty.Default;
                    modelAsset.DynamicRootNode["~Base"].Asset.Nodes = DynamicYamlEmpty.Default;
                }

                // Save back
                foreach (var modelAsset in modelAssets)
                {
                    modelAsset.Dispose();
                }
                foreach (var animAsset in animAssets)
                {
                    animAsset.Dispose();
                }
            }

            return(true);
        }
Exemplo n.º 50
0
        public async Task Load(IFileSystem fileSystem, UPath filePath, LoadContext loadContext)
        {
            var fileStream = await fileSystem.OpenFileAsync(filePath);

            Files = _b123.Load(fileStream);
        }
Exemplo n.º 51
0
 // Add Path list values to the beginning of the current list
 public void Shift(UPath oPath)
 {
     int[] oList = new int[list.Length];
     for(int x = 0; x < list.Length; x++){
         oList[x] = list[x];
     }
     list = new int[list.Length + oPath.list.Length];
     int y = 0;
     for(int x = 0; x < oPath.list.Length; x++){
         list[y] = oPath.list[x];
         y++;
     }
     for(int x = 0; x < oList.Length; x++){
         list[y] = oList[x];
         y++;
     }
 }