public EffectCompileCommand(AssetCompilerContext context, UDirectory baseUrl, string effectName, CompilerParameters compilerParameters)
 {
     this.context = context;
     this.baseUrl = baseUrl;
     this.effectName = effectName;
     this.compilerParameters = compilerParameters;
 }
        public MaterialDescription Run(MaterialDescription material, UDirectory materialPath, PixelFormat outputFormat = PixelFormat.ETC1)
        {
            if (material == null) throw new ArgumentNullException("material");

            var assetManager = new AssetManager();
            var modifiedMaterial = material.Clone();
            var textureVisitor = new MaterialTextureVisitor(modifiedMaterial);
            var nodeReplacer = new MaterialNodeReplacer(modifiedMaterial);
            var textureNodes = textureVisitor.GetAllModelTextureValues();

            foreach (var textureNode in textureNodes)
            {
                var itemAsset = assetSession.FindAsset(textureNode.TextureReference.Id);
                if(itemAsset == null)
                    throw new InvalidOperationException("The referenced texture is not included in the project session.");

                var textureAsset = (TextureAsset)itemAsset.Asset;
                if (textureAsset.Format != TextureFormat.Compressed || textureAsset.Alpha == AlphaFormat.None)
                    continue; // the texture has no alpha so there is no need to divide the texture into two sub-textures

                var originalLocation = textureNode.TextureReference.Location;

                throw new NotImplementedException("TODO: Need to reimplement this with removed data layer.");
                using (var image = assetManager.Load<Image>(originalLocation))
                {
                    CreateAndSaveSeparateTextures(image, originalLocation, textureAsset.GenerateMipmaps, outputFormat);
                    assetManager.Unload(image); // matching unload to the previous asset manager load call
                }

                // make new tree
                var colorNode = new MaterialTextureNode(GenerateColorTextureURL(originalLocation), textureNode.TexcoordIndex, Vector2.One, Vector2.Zero);
                var alphaNode = new MaterialTextureNode(GenerateAlphaTextureURL(originalLocation), textureNode.TexcoordIndex, Vector2.One, Vector2.Zero);
                var substituteAlphaNode = new MaterialShaderClassNode { MixinReference = new AssetReference<EffectShaderAsset>(Guid.Empty, "ComputeColorSubstituteAlphaWithColor") };
                substituteAlphaNode.CompositionNodes.Add("color1", colorNode);
                substituteAlphaNode.CompositionNodes.Add("color2", alphaNode);

                // set the parameters of the children so that they match the original texture
                var children = new[] { colorNode, alphaNode };
                foreach (var childTexture in children)
                {
                    childTexture.Sampler.AddressModeU = textureNode.Sampler.AddressModeU;
                    childTexture.Sampler.AddressModeV = textureNode.Sampler.AddressModeV;
                    childTexture.Sampler.Filtering = textureNode.Sampler.Filtering;
                    childTexture.Offset = textureNode.Offset;
                    childTexture.Sampler.SamplerParameterKey = textureNode.Sampler.SamplerParameterKey;
                    childTexture.Scale = textureNode.Scale;
                    childTexture.TexcoordIndex = textureNode.TexcoordIndex;
                }

                // copy the parameter key on the color and let the one of the alpha null so that it is set automatically to available value later
                colorNode.Key = textureNode.Key;
                alphaNode.Key = null;

                // update all the material references to the new node
                nodeReplacer.Replace(textureNode, substituteAlphaNode);
            }
            
            return modifiedMaterial;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="PackageLoadingAssetFile" /> class.
        /// </summary>
        /// <param name="package">The package this asset will be part of.</param>
        /// <param name="filePath">The relative file path (from default asset folder).</param>
        /// <param name="sourceFolder">The source folder (optional, can be null).</param>
        /// <exception cref="System.ArgumentException">filePath must be relative</exception>
        public PackageLoadingAssetFile(Package package, UFile filePath, UDirectory sourceFolder)
        {
            if (filePath.IsAbsolute)
                throw new ArgumentException("filePath must be relative", filePath);

            SourceFolder = UPath.Combine(package.RootDirectory, sourceFolder ?? package.GetDefaultAssetFolder());
            FilePath = UPath.Combine(SourceFolder, filePath);
        }
Example #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PackageStore"/> class.
        /// </summary>
        /// <exception cref="System.InvalidOperationException">Unable to find a valid Xenko installation path</exception>
        private PackageStore(string installationPath = null, string defaultPackageName = "Xenko", string defaultPackageVersion = XenkoVersion.CurrentAsText)
        {
            // TODO: these are currently hardcoded to Xenko
            DefaultPackageName = defaultPackageName;
            DefaultPackageVersion = new PackageVersion(defaultPackageVersion);
            defaultPackageDirectory = DirectoryHelper.GetPackageDirectory(defaultPackageName);
   
            // 1. Try to use the specified installation path
            if (installationPath != null)
            {
                if (!DirectoryHelper.IsInstallationDirectory(installationPath))
                {
                    throw new ArgumentException("Invalid Xenko installation path [{0}]".ToFormat(installationPath), "installationPath");
                }

                globalInstallationPath = installationPath;
            }

            // 2. Try to resolve an installation path from the path of this assembly
            // We need to be able to use the package manager from an official Xenko install as well as from a developer folder
            if (globalInstallationPath == null)
            {
                globalInstallationPath = DirectoryHelper.GetInstallationDirectory(DefaultPackageName);
            }

            // If there is no root, this is an error
            if (globalInstallationPath == null)
            {
                throw new InvalidOperationException("Unable to find a valid Xenko installation or dev path");
            }

            // Preload default package
            var logger = new LoggerResult();
            var defaultPackageFile = DirectoryHelper.GetPackageFile(defaultPackageDirectory, DefaultPackageName);
            defaultPackage = Package.Load(logger, defaultPackageFile, GetDefaultPackageLoadParameters());
            if (defaultPackage == null)
            {
                throw new InvalidOperationException("Error while loading default package from [{0}]: {1}".ToFormat(defaultPackageFile, logger.ToText()));
            }
            defaultPackage.IsSystem = true;

            // A flag variable just to know if it is a bare bone development directory
            isDev = defaultPackageDirectory != null && DirectoryHelper.IsRootDevDirectory(defaultPackageDirectory);

            // Check if we are in a root directory with store/packages facilities
            if (NugetStore.IsStoreDirectory(globalInstallationPath))
            {
                packagesDirectory = UPath.Combine(globalInstallationPath, (UDirectory)NugetStore.DefaultGamePackagesDirectory);
                store = new NugetStore(globalInstallationPath);
            }
            else
            {
                // We should exit from here if NuGet is not configured.
                MessageBox.Show($"Unexpected installation. Cannot find a proper NuGet configuration for [{defaultPackageName}] in [{globalInstallationPath}]", "Installation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
            }
        }
 internal static void UpdateUPaths(Asset asset, UDirectory assetFolder, UPathType convertUPathTo)
 {
     switch (convertUPathTo)
     {
         case UPathType.Absolute:
             ConvertUPaths(asset, RelativeSourceHashesKey, AbsoluteSourceHashesKey, x => UPath.Combine(assetFolder, x));
             break;
         case UPathType.Relative:
             ConvertUPaths(asset, AbsoluteSourceHashesKey, RelativeSourceHashesKey, x => x.MakeRelative(assetFolder));
             break;
         default:
             throw new ArgumentOutOfRangeException(nameof(convertUPathTo), convertUPathTo, null);
     }
 }
 /// <summary>
 /// Sync output of current compilation to <paramref name="dir"/>
 /// </summary>
 /// <param name="dir"></param>
 /// <returns></returns>
 private bool SyncTo(string dir)
 {
     // Copy files over
     using (var sftp = new SftpClient(Machine, Port, Username, Password))
     {
         sftp.Connect();
         if (!sftp.IsConnected)
         {
             return false;
         }
         // Perform recursive copy of all the folders under `dir`. This is required
         // as the sftp client only synchronize directories at their level only, no
         // subdirectory.
         var dirs = new Queue<DirectoryInfo>();
         dirs.Enqueue(new DirectoryInfo(dir));
         var parentPath = new UDirectory(dir);
         while (dirs.Count != 0)
         {
             var currentDir = dirs.Dequeue();
             var currentPath = new UDirectory(currentDir.FullName);
             foreach (var subdir in currentDir.EnumerateDirectories())
             {
                 dirs.Enqueue(subdir);
             }
             // Get the destination path by adding to `Location` the relative path of `dir` to `currentDir`.
             var destination = UPath.Combine(new UDirectory(Location.ItemSpec), currentPath.MakeRelative(parentPath));
             Log.LogMessage("Synchronizing " + currentPath + " with " + destination.FullPath);
             // Try to create a remote directory. If it throws an exception, we will assume
             // for now that the directory already exists. See https://github.com/sshnet/SSH.NET/issues/25
             try
             {
                 sftp.CreateDirectory(destination.FullPath);
                 Log.LogMessage("Creating remote directory " + destination.FullPath);
             }
             catch (SshException)
             {
                 // Do nothing, as this is when the directory already exists
             }
             // Synchronize files.
             foreach (var file in sftp.SynchronizeDirectories(currentPath.FullPath, destination.FullPath, "*"))
             {
                 Log.LogMessage("Updating " + file.Name);
             }
         }
         return true;
     }
 }
Example #7
0
        private static void GenerateUnitTestProject(string outputDirectory, string templateFile, string name, string projectNamespace)
        {
            var projectTemplate = ProjectTemplate.Load(templateFile);

            // Force reference to Xenko.Assets (to have acess to SolutionPlatform)
            projectTemplate.Assemblies.Add(typeof(GraphicsProfile).Assembly.FullName);
            projectTemplate.Assemblies.Add(typeof(XenkoConfig).Assembly.FullName);

            var options = new Dictionary<string, object>();

            // When generating over an existing set of files, retrieve the existing IDs
            // for better incrementality
            Guid projectGuid, assetId;
            GetExistingGuid(outputDirectory, name + ".Windows.csproj", out projectGuid);
            GetExistingAssetId(outputDirectory, name + ".xkpkg", out assetId);

            var session = new PackageSession();
            var result = new LoggerResult();

            var templateGeneratorParameters = new SessionTemplateGeneratorParameters();
            templateGeneratorParameters.OutputDirectory = outputDirectory;
            templateGeneratorParameters.Session = session;
            templateGeneratorParameters.Name = name;
            templateGeneratorParameters.Logger = result;
            templateGeneratorParameters.Description = new TemplateDescription();
            templateGeneratorParameters.Id = assetId;

            if (!PackageUnitTestGenerator.Default.PrepareForRun(templateGeneratorParameters).Result)
            {
                Console.WriteLine(@"Error generating package: PackageUnitTestGenerator.PrepareForRun returned false");
                return;
            }
            if (!PackageUnitTestGenerator.Default.Run(templateGeneratorParameters))
            {
                Console.WriteLine(@"Error generating package: PackageUnitTestGenerator.Run returned false");
                return;
            }
            if (result.HasErrors)
            {
                Console.WriteLine($"Error generating package: {result.ToText()}");
                return;
            }

            var package = session.LocalPackages.Single();

            var previousCurrent = session.CurrentPackage;
            session.CurrentPackage = package;

            // Compute Xenko Sdk relative path
            // We are supposed to be in standard output binary folder, so Xenko root should be at ..\..
            var xenkoPath = UPath.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), new UDirectory(@"..\.."));
            var xenkoRelativePath = new UDirectory(xenkoPath)
                .MakeRelative(outputDirectory)
                .ToString()
                .Replace('/', '\\');
            xenkoRelativePath = xenkoRelativePath.TrimEnd('\\');

            options["Namespace"] = projectNamespace ?? name;
            options["Package"] = package;
            options["Platforms"] = new List<SolutionPlatform>(AssetRegistry.SupportedPlatforms);
            options["XenkoSdkRelativeDir"] = xenkoRelativePath;

            // Generate project template
            result = projectTemplate.Generate(outputDirectory, name, projectGuid, options);
            if (result.HasErrors)
            {
                Console.WriteLine("Error generating solution: {0}", result.ToText());
                return;
            }

            var sharedProfile = package.Profiles.FindSharedProfile();

            // Setup the assets folder
            Directory.CreateDirectory(UPath.Combine(outputDirectory, (UDirectory)"Assets/Shared"));

            // Add Windows test as Shared library
            var projectWindowsRef = new ProjectReference
            {
                Id = projectGuid,
                Location = UPath.Combine(outputDirectory, (UFile)(name + ".Windows.csproj")),
                Type = SiliconStudio.Assets.ProjectType.Library
            };
            sharedProfile.ProjectReferences.Add(projectWindowsRef);

            // Generate executable projects for each platform
            foreach (var platform in AssetRegistry.SupportedPlatforms)
            {
                var platformProfile = new PackageProfile(platform.Name) { Platform = platform.Type };
                platformProfile.AssetFolders.Add(new AssetFolder("Assets/"+ platform.Name));
                
                // Log progress
                var projectName = name + "." + platform.Type;

                // Create project reference
                var projectPlatformRef = new ProjectReference
                {
                    Id = projectGuid,
                    Location = UPath.Combine(outputDirectory, (UFile)(projectName + ".csproj")),
                    Type = SiliconStudio.Assets.ProjectType.Executable
                };

                platformProfile.ProjectReferences.Add(projectPlatformRef);

                // Add build configuration per platform
                platform.Properties.CopyTo(platformProfile.Properties, true);

                package.Profiles.Add(platformProfile);
            }

            session.CurrentPackage = previousCurrent;

            result = session.Save();
            if (result.HasErrors)
            {
                Console.WriteLine("Error saving package: {0}", result.ToText());
                return;
            }
        }
Example #8
0
 /// <summary>
 /// Makes this instance relative to the specified anchor directory.
 /// </summary>
 /// <param name="anchorDirectory">The anchor directory.</param>
 /// <returns>A relative path of this instance to the anchor directory.</returns>
 public new UFile MakeRelative(UDirectory anchorDirectory)
 {
     return((UFile)base.MakeRelative(anchorDirectory));
 }
Example #9
0
            /// <summary>
            /// Generate the build step corresponding to raw imports of the current package file.
            /// </summary>
            /// <param name="context">The compilation context</param>
            /// <param name="result">The compilation current result</param>
            private void GenerateRawImportBuildSteps(AssetCompilerContext context, AssetCompilerResult result)
            {
                if (context.Package.RootDirectory == null)
                    return;

                foreach (var profile in context.Package.Profiles)
                {
                    foreach (var sourceFolder in profile.AssetFolders)
                    {
                        var baseDirectory = Path.GetFullPath(context.Package.RootDirectory);
                        // Use sub directory
                        baseDirectory = Path.Combine(baseDirectory, sourceFolder.Path);

                        if (!Directory.Exists(baseDirectory))
                        {
                            continue;
                        }

                        var baseUDirectory = new UDirectory(baseDirectory);
                        var hashSet = new HashSet<string>();

                        // Imports explicit
                        foreach (var rawImport in sourceFolder.RawImports)
                        {
                            var sourceDirectory = baseUDirectory;
                            if (!string.IsNullOrEmpty(rawImport.SourceDirectory))
                                sourceDirectory = UPath.Combine(sourceDirectory, rawImport.SourceDirectory);

                            if (!Directory.Exists(sourceDirectory))
                            {
                                result.Error("Unable to find raw import directory [{0}]", sourceDirectory);
                                continue;
                            }

                            var files = Directory.EnumerateFiles(sourceDirectory, "*.*", SearchOption.AllDirectories).ToList();
                            var importRegexes = rawImport.Patterns.Select(x => new Regex(Selectors.PathSelector.TransformToRegex(x))).ToArray();
                            foreach (var file in files)
                            {
                                var pathToFileRelativeToProject = new UFile(file).MakeRelative(sourceDirectory);
                                var outputPath = pathToFileRelativeToProject;
                                if (!string.IsNullOrEmpty(rawImport.TargetLocation))
                                    outputPath = UPath.Combine(rawImport.TargetLocation, outputPath);

                                foreach (var importRegex in importRegexes)
                                {
                                    if (importRegex.Match(pathToFileRelativeToProject).Success && hashSet.Add(outputPath))
                                    {
                                        result.BuildSteps.Add(new ImportStreamCommand
                                        {
                                            SourcePath = file,
                                            Location = outputPath,
                                        });
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
Example #10
0
 /// <summary>
 /// Makes this instance relative to the specified anchor directory.
 /// </summary>
 /// <param name="anchorDirectory">The anchor directory.</param>
 /// <returns>A relative path of this instance to the anchor directory.</returns>
 public new UFile MakeRelative(UDirectory anchorDirectory)
 {
     return (UFile)base.MakeRelative(anchorDirectory);
 }
Example #11
0
        private static void FindCodeAssetsInProject(ICollection<PackageLoadingAssetFile> list, Package package)
        {
            if (package.IsSystem) return;

            var profile = package.Profiles.FindSharedProfile();
            if (profile == null) return;

            foreach (var libs in profile.ProjectReferences.Where(x => x.Type == ProjectType.Library))
            {
                var realFullPath = UPath.Combine(package.RootDirectory, libs.Location);
                string defaultNamespace;
                var codePaths = FindCodeAssetsInProject(realFullPath, out defaultNamespace);
                libs.RootNamespace = defaultNamespace;
                var dir = new UDirectory(realFullPath.GetFullDirectory());
                var parentDir = dir.GetParent();

                foreach (var codePath in codePaths)
                {
                    list.Add(new PackageLoadingAssetFile(codePath, parentDir, realFullPath));
                }
            }
        }
 public override void VisitObjectMember(object container, ObjectDescriptor containerDescriptor, IMemberDescriptor member, object value)
 {
     base.VisitObjectMember(container, containerDescriptor, member, value);
     var assetReference = value as AssetReference;
     var assetBase = value as AssetBase;
     var attachedReference = value != null ? AttachedReferenceManager.GetAttachedReference(value) : null;
     if (assetReference != null)
     {
         AddLink(assetReference,
             (guid, location) =>
             {
                 var newValue = AssetReference.New(member.Type, guid.HasValue ? guid.Value : assetReference.Id, location);
                 member.Set(container, newValue);
                 return newValue;
             });
     }
     else if (assetBase != null)
     {
         AddLink(assetBase,
             (guid, location) =>
             {
                 var newValue = new AssetBase(location, assetBase.Asset);
                 member.Set(container, newValue);
                 return newValue;
             });
     }
     else if (attachedReference != null)
     {
         AddLink(attachedReference,
             (guid, location) =>
             {
                 object newValue = guid.HasValue && guid.Value != Guid.Empty ? AttachedReferenceManager.CreateSerializableVersion(member.Type, guid.Value, location) : null;
                 member.Set(container, newValue);
                 return newValue;
             });
     }
     else if (value is UFile)
     {
         AddLink(value,
             (guid, location) =>
             {
                 var newValue = new UFile(location);
                 member.Set(container, newValue);
                 return newValue;
             });
     }
     else if (value is UDirectory)
     {
         AddLink(value,
             (guid, location) =>
             {
                 var newValue = new UDirectory(location);
                 member.Set(container, newValue);
                 return newValue;
             });
     }
 }
 public override void VisitCollectionItem(IEnumerable collection, CollectionDescriptor descriptor, int index, object item, ITypeDescriptor itemDescriptor)
 {
     base.VisitCollectionItem(collection, descriptor, index, item, itemDescriptor);
     var assetReference = item as AssetReference;
     var assetBase = item as AssetBase;
     var attachedReference = item != null ? AttachedReferenceManager.GetAttachedReference(item) : null;
     // TODO force support for IList in CollectionDescriptor
     if (assetReference != null)
     {
         var list = (IList)collection;
         AddLink(assetReference, (guid, location) => list[index] = AssetReference.New(descriptor.ElementType, guid.HasValue ? guid.Value : assetReference.Id, location));
     }
     else if (assetBase != null)
     {
         var list = (IList)collection;
         AddLink(assetBase, (guid, location) => list[index] = new AssetBase(location, assetBase.Asset));
     }
     else if (attachedReference != null)
     {
         var list = (IList)collection;
         AddLink(attachedReference, (guid, location) => list[index] = guid.HasValue && guid.Value != Guid.Empty ? AttachedReferenceManager.CreateSerializableVersion(descriptor.ElementType, guid.Value, location) : null);
     }
     else if (item is UFile)
     {
         var list = (IList)collection;
         AddLink(item, (guid, location) => list[index] = new UFile(location));
     }
     else if (item is UDirectory)
     {
         var list = (IList)collection;
         AddLink(item, (guid, location) => list[index] = new UDirectory(location));
     }
 }
Example #14
0
 public PackageLoadingAssetFile(UFile filePath, UDirectory sourceFolder, UFile projectFile)
 {
     FilePath = filePath;
     SourceFolder = sourceFolder;
     ProjectFile = projectFile;
 }
Example #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TemplateFolder"/> class.
 /// </summary>
 /// <param name="path">The path.</param>
 public TemplateFolder(UDirectory path)
 {
     Path = path;
     Files = new List<UFile>();
 }
 public static BuildStep FromRequest(AssetCompilerContext context, Package package, UDirectory urlRoot, EffectCompileRequest effectCompileRequest)
 {
     var compilerParameters = new CompilerParameters(effectCompileRequest.UsedParameters);
     compilerParameters.EffectParameters.Platform = context.GetGraphicsPlatform(package);
     compilerParameters.EffectParameters.Profile = context.GetGameSettingsAsset().Get<RenderingSettings>(context.Platform).DefaultGraphicsProfile;
     compilerParameters.EffectParameters.ApplyCompilationMode(context.GetCompilationMode());
     return new CommandBuildStep(new EffectCompileCommand(context, urlRoot, effectCompileRequest.EffectName, compilerParameters, package));
 }
Example #17
0
        private static void FindCodeAssetsInProject(ICollection<PackageLoadingAssetFile> list, Package package)
        {
            if (!package.IsSystem) //user code case
            {
                var profile = package.Profiles.FindSharedProfile();
                if (profile != null)
                {
                    foreach (var libs in profile.ProjectReferences.Where(x => x.Type == ProjectType.Library))
                    {
                        var realFullPath = UPath.Combine(package.RootDirectory, libs.Location);
                        var project = VSProjectHelper.LoadProject(realFullPath);
                        var dir = new UDirectory(realFullPath.GetFullDirectory());
                        var parentDir = dir.GetParent();

                        foreach (var projectItem in project.Items.Where(x => x.ItemType == "Compile" || x.ItemType == "None").
                            Select(x => new UFile(x.EvaluatedInclude)).
                            Where(x => AssetRegistry.IsProjectSourceCodeAssetFileExtension(x.GetFileExtension())))
                        {
                            var csPath = UPath.Combine(dir, projectItem);
                            list.Add(new PackageLoadingAssetFile(csPath, parentDir, realFullPath));
                        }

                        project.ProjectCollection.UnloadAllProjects();
                        project.ProjectCollection.Dispose();
                    }
                }
            }
        }
Example #18
0
 public static UFile Combine([NotNull] UDirectory leftPath, [NotNull] UFile rightPath)
 {
     return(UPath.Combine(leftPath, rightPath));
 }
Example #19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AssetFolder"/> class.
 /// </summary>
 /// <param name="path">The folder.</param>
 public AssetFolder(UDirectory path) : this()
 {
     if (path == null) throw new ArgumentNullException("path");
     this.path = path;
 }
Example #20
0
        public void TestMakeRelative()
        {
            UPath assetPath2 = null;
            UPath newAssetPath2 = null;
            var dir1 = new UDirectory("/a/b/c");

            var assetDir2 = new UDirectory("/a/b/c");
            newAssetPath2 = dir1.MakeRelative(assetDir2);
            Assert.AreEqual(".", newAssetPath2.FullPath);

            var assetDir3 = new UDirectory("/a/b");
            newAssetPath2 = dir1.MakeRelative(assetDir3);
            Assert.AreEqual("c", newAssetPath2.FullPath);

            var assetDir4 = new UDirectory("/a/b/c/d");
            newAssetPath2 = dir1.MakeRelative(assetDir4);
            Assert.AreEqual("..", newAssetPath2.FullPath);

            // Test direct relative
            assetPath2 = new UFile("/a/b/c/test.txt");
            newAssetPath2 = assetPath2.MakeRelative(dir1);
            Assert.AreEqual("test.txt", newAssetPath2.FullPath);

            // Test direct relative + subdir
            assetPath2 = new UFile("/a/b/c/test/test.txt");
            newAssetPath2 = assetPath2.MakeRelative(dir1);
            Assert.AreEqual("test/test.txt", newAssetPath2.FullPath);

            // Test relative 1
            assetPath2 = new UFile("/a/b/test.txt");
            newAssetPath2 = assetPath2.MakeRelative(dir1);
            Assert.AreEqual("../test.txt", newAssetPath2.FullPath);

            // Test relative 2
            assetPath2 = new UFile("/a/test.txt");
            newAssetPath2 = assetPath2.MakeRelative(dir1);
            Assert.AreEqual("../../test.txt", newAssetPath2.FullPath);

            // Test relative 3
            assetPath2 = new UFile("/test.txt");
            newAssetPath2 = assetPath2.MakeRelative(dir1);
            Assert.AreEqual("../../../test.txt", newAssetPath2.FullPath);

            // Test already relative
            assetPath2 = new UFile("../test.txt");
            newAssetPath2 = assetPath2.MakeRelative(dir1);
            Assert.AreEqual("../test.txt", newAssetPath2.FullPath);

            // Test only root path in common
            assetPath2 = new UFile("/e/f/g/test.txt");
            newAssetPath2 = assetPath2.MakeRelative(dir1);
            Assert.AreEqual("../../../e/f/g/test.txt", newAssetPath2.FullPath);

            // Test only root path in common with single file
            assetPath2 = new UFile("/test.txt");
            newAssetPath2 = assetPath2.MakeRelative(dir1);
            Assert.AreEqual("../../../test.txt", newAssetPath2.FullPath);
        }
Example #21
0
        public void TestMakeRelativeWithDrive()
        {
            UPath assetPath2 = null;
            UPath newAssetPath2 = null;
            var dir1 = new UDirectory("C:/a/b/c");

            // Test direct relative
            assetPath2 = new UFile("C:/a/b/c/test.txt");
            newAssetPath2 = assetPath2.MakeRelative(dir1);
            Assert.AreEqual("test.txt", newAssetPath2.FullPath);

            // Test direct relative + subdir
            assetPath2 = new UFile("C:/a/b/c/test/test.txt");
            newAssetPath2 = assetPath2.MakeRelative(dir1);
            Assert.AreEqual("test/test.txt", newAssetPath2.FullPath);

            // Test relative 1
            assetPath2 = new UFile("C:/a/b/test.txt");
            newAssetPath2 = assetPath2.MakeRelative(dir1);
            Assert.AreEqual("../test.txt", newAssetPath2.FullPath);

            // Test relative 2
            assetPath2 = new UFile("C:/a/test.txt");
            newAssetPath2 = assetPath2.MakeRelative(dir1);
            Assert.AreEqual("../../test.txt", newAssetPath2.FullPath);

            // Test relative 3
            assetPath2 = new UFile("C:/test.txt");
            newAssetPath2 = assetPath2.MakeRelative(dir1);
            Assert.AreEqual("../../../test.txt", newAssetPath2.FullPath);

            // Test already relative
            assetPath2 = new UFile("../test.txt");
            newAssetPath2 = assetPath2.MakeRelative(dir1);
            Assert.AreEqual("../test.txt", newAssetPath2.FullPath);

            // Test no path in common
            assetPath2 = new UFile("E:/e/f/g/test.txt");
            newAssetPath2 = assetPath2.MakeRelative(dir1);
            Assert.AreEqual("E:/e/f/g/test.txt", newAssetPath2.FullPath);

            // Test no root path single file
            assetPath2 = new UFile("E:/test.txt");
            newAssetPath2 = assetPath2.MakeRelative(dir1);
            Assert.AreEqual("E:/test.txt", newAssetPath2.FullPath);
        }
 public override void VisitDictionaryKeyValue(object dictionaryObj, DictionaryDescriptor descriptor, object key, ITypeDescriptor keyDescriptor, object value, ITypeDescriptor valueDescriptor)
 {
     base.VisitDictionaryKeyValue(dictionaryObj, descriptor, key, keyDescriptor, value, valueDescriptor);
     var assetReference = value as AssetReference;
     var assetBase = value as AssetBase;
     var attachedReference = value != null ? AttachedReferenceManager.GetAttachedReference(value) : null;
     if (assetReference != null)
     {
         AddLink(assetReference,
             (guid, location) =>
             {
                 var newValue = AssetReference.New(descriptor.ValueType, guid.HasValue ? guid.Value : assetReference.Id, location);
                 descriptor.SetValue(dictionaryObj, key, newValue);
                 return newValue;
             });
     }
     else if (assetBase != null)
     {
         AddLink(assetBase,
             (guid, location) =>
             {
                 var newValue = new AssetBase(location, assetBase.Asset);
                 descriptor.SetValue(dictionaryObj, key, newValue);
                 return newValue;
             });
     }
     else if (attachedReference != null)
     {
         AddLink(attachedReference,
             (guid, location) =>
             {
                 object newValue = guid.HasValue && guid.Value != Guid.Empty ? AttachedReferenceManager.CreateSerializableVersion(descriptor.ValueType, guid.Value, location) : null;
                 descriptor.SetValue(dictionaryObj, key, newValue);
                 return newValue;
             });
     }
     else if (value is UFile)
     {
         AddLink(value,
             (guid, location) =>
             {
                 var newValue = new UFile(location);
                 descriptor.SetValue(dictionaryObj, key, newValue);
                 return newValue;
             });
     }
     else if (value is UDirectory)
     {
         AddLink(value,
             (guid, location) =>
             {
                 var newValue = new UDirectory(location);
                 descriptor.SetValue(dictionaryObj, key, newValue);
                 return newValue;
             });
     }
 }
Example #23
0
        public void TestUPathGetParent()
        {
            // First directories
            var dir = new UDirectory("c:/");
            Assert.AreEqual("c:/", dir.GetParent().FullPath);

            dir = new UDirectory("c:/a");
            Assert.AreEqual("c:/", dir.GetParent().FullPath);

            dir = new UDirectory("c:/a/b");
            Assert.AreEqual("c:/a", dir.GetParent().FullPath);

            dir = new UDirectory("/");
            Assert.AreEqual("/", dir.GetParent().FullPath);

            dir = new UDirectory("/a");
            Assert.AreEqual("/", dir.GetParent().FullPath);

            dir = new UDirectory("/a/b");
            Assert.AreEqual("/a", dir.GetParent().FullPath);

            dir = new UDirectory("a");
            Assert.AreEqual("", dir.GetParent().FullPath);

            dir = new UDirectory("a/b");
            Assert.AreEqual("a", dir.GetParent().FullPath);

            // Now with files.
            var file = new UFile("c:/a.txt");
            Assert.AreEqual("c:/", file.GetParent().FullPath);

            file = new UFile("c:/a/b.txt");
            Assert.AreEqual("c:/a", file.GetParent().FullPath);

            file = new UFile("/a.txt");
            Assert.AreEqual("/", file.GetParent().FullPath);

            file = new UFile("/a/b.txt");
            Assert.AreEqual("/a", file.GetParent().FullPath);

            file = new UFile("a.txt");
            Assert.AreEqual("", file.GetParent().FullPath);

            file = new UFile("a/b.txt");
            Assert.AreEqual("a", file.GetParent().FullPath);
        }
Example #24
0
        public static List<string> FindCodeAssetsInProject(string projectFullPath, out string nameSpace)
        {
            var realFullPath = new UFile(projectFullPath);
            var project = VSProjectHelper.LoadProject(realFullPath);
            var dir = new UDirectory(realFullPath.GetFullDirectory());

            var nameSpaceProp = project.AllEvaluatedProperties.FirstOrDefault(x => x.Name == "RootNamespace");
            nameSpace = nameSpaceProp?.EvaluatedValue ?? string.Empty;

            var result = project.Items.Where(x => (x.ItemType == "Compile" || x.ItemType == "None") && string.IsNullOrEmpty(x.GetMetadataValue("AutoGen")))
                .Select(x => new UFile(x.EvaluatedInclude)).Where(x => AssetRegistry.IsProjectSourceCodeAssetFileExtension(x.GetFileExtension()))
                .Select(projectItem => UPath.Combine(dir, projectItem)).Select(csPath => (string)csPath).ToList();

            project.ProjectCollection.UnloadAllProjects();
            project.ProjectCollection.Dispose();

            return result;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="PackageLoadingAssetFile"/> class.
 /// </summary>
 /// <param name="filePath">The file path.</param>
 /// <param name="sourceFolder">The source folder.</param>
 public PackageLoadingAssetFile(UFile filePath, UDirectory sourceFolder)
 {
     FilePath = filePath;
     SourceFolder = sourceFolder;
 }
Example #26
0
 /// <summary>
 /// Combines the specified left uniform location and right location and return a new <see cref="UFile"/>
 /// </summary>
 /// <param name="leftPath">The left path.</param>
 /// <param name="rightPath">The right path.</param>
 /// <returns>The combination of both paths.</returns>
 public static UFile Combine(UDirectory leftPath, UFile rightPath)
 {
     return UPath.Combine(leftPath, rightPath);
 }
Example #27
0
 public void TestWithSimpleDirectory()
 {
     var assetPath = new UDirectory("/a/b/c");
     Assert.AreEqual("/a/b/c", assetPath.GetDirectory());
     Assert.AreEqual("/a/b/c", assetPath.FullPath);
     var directory = new UDirectory("C:/a");
     Assert.AreEqual("/a", directory.GetDirectory());
     directory = new UDirectory("/a");
     Assert.AreEqual("/a", directory.GetDirectory());
 }
Example #28
0
File: UFile.cs Project: zetz/xenko
 /// <summary>
 /// Combines the specified left uniform location and right location and return a new <see cref="UFile"/>
 /// </summary>
 /// <param name="leftPath">The left path.</param>
 /// <param name="rightPath">The right path.</param>
 /// <returns>The combination of both paths.</returns>
 public static UFile Combine(UDirectory leftPath, UFile rightPath)
 {
     return(UPath.Combine(leftPath, rightPath));
 }
Example #29
0
 public void TestContains()
 {
     var dir1 = new UDirectory("C:/a/b/c");
     Assert.IsTrue(dir1.Contains(new UFile("C:/a/b/c/d")));
     Assert.IsTrue(dir1.Contains(new UFile("C:/a/b/c/d/e")));
     Assert.IsTrue(dir1.Contains(new UDirectory("C:/a/b/c/d")));
     Assert.IsTrue(dir1.Contains(new UDirectory("C:/a/b/c/d/e")));
     Assert.IsFalse(dir1.Contains(new UFile("C:/a/b/x")));
     Assert.IsFalse(dir1.Contains(new UFile("C:/a/b/cx")));
 }
Example #30
0
        //[Test]
        public void TestUPathGetComponents()
        {
            var d = new UDirectory("a/b");
            Assert.AreEqual(new UDirectory("").GetComponents().Count(), 0);
            Assert.AreEqual(new UDirectory("/").GetComponents().Count(), 0);
            CollectionAssert.AreEqual(new UDirectory("a").GetComponents(), new string[] { "a" });
            CollectionAssert.AreEqual(new UDirectory("/a").GetComponents(), new string[] { "a" });
            CollectionAssert.AreEqual(new UDirectory("a/b").GetComponents(), new string[] { "a", "b" });
            CollectionAssert.AreEqual(new UDirectory("/a/b").GetComponents(), new string[] { "a", "b" });
            CollectionAssert.AreEqual(new UDirectory("a/b/c").GetComponents(), new string[] { "a", "b", "c" });
            CollectionAssert.AreEqual(new UDirectory("/a/b/c").GetComponents(), new string[] { "a", "b", "c" });
            CollectionAssert.AreEqual(new UDirectory("c:").GetComponents(), new string[] { "c:" });
            CollectionAssert.AreEqual(new UDirectory("c:/a").GetComponents(), new string[] { "c:", "a" });
            CollectionAssert.AreEqual(new UDirectory("c:/a/b").GetComponents(), new string[] { "c:", "a", "b" });
            CollectionAssert.AreEqual(new UDirectory("c:/a/b.ext").GetComponents(), new string[] { "c:", "a", "b.ext" });


            CollectionAssert.AreEqual(new UFile("a").GetComponents(), new string[] { "a" });
            CollectionAssert.AreEqual(new UFile("/a").GetComponents(), new string[] { "a" });
            CollectionAssert.AreEqual(new UFile("a/b").GetComponents(), new string[] { "a", "b" });
            CollectionAssert.AreEqual(new UFile("/a/b").GetComponents(), new string[] { "a", "b" });
            CollectionAssert.AreEqual(new UFile("a/b/c").GetComponents(), new string[] { "a", "b", "c" });
            CollectionAssert.AreEqual(new UFile("/a/b/c").GetComponents(), new string[] { "a", "b", "c" });
            CollectionAssert.AreEqual(new UFile("c:/a").GetComponents(), new string[] { "c:", "a" });
            CollectionAssert.AreEqual(new UFile("c:/a/b").GetComponents(), new string[] { "c:", "a", "b" });
            CollectionAssert.AreEqual(new UFile("c:/a/b.ext").GetComponents(), new string[] { "c:", "a", "b.ext" });
        }
Example #31
0
        private static void GenerateUnitTestProject(string outputDirectory, string templateFile, string name)
        {
            var projectTemplate = ProjectTemplate.Load(templateFile);

            // Force reference to Paradox.Assets (to have acess to SolutionPlatform)
            projectTemplate.Assemblies.Add(typeof(GraphicsProfile).Assembly.FullName);
            projectTemplate.Assemblies.Add(typeof(ParadoxConfig).Assembly.FullName);

            var options = new Dictionary<string, object>();

            var session = new PackageSession();
            var result = new LoggerResult();

            var templateGeneratorParameters = new TemplateGeneratorParameters();
            templateGeneratorParameters.OutputDirectory = outputDirectory;
            templateGeneratorParameters.Session = session;
            templateGeneratorParameters.Name = name;
            templateGeneratorParameters.Logger = result;
            templateGeneratorParameters.Description = new TemplateDescription();

            PackageUnitTestGenerator.Default.Generate(templateGeneratorParameters);
            if (result.HasErrors)
            {
                Console.WriteLine("Error generating package: {0}", result.ToText());
                return;
            }

            var package = templateGeneratorParameters.Package;

            var previousCurrent = session.CurrentPackage;
            session.CurrentPackage = package;

            // Compute Paradox Sdk relative path
            // We are supposed to be in standard output binary folder, so Paradox root should be at ..\..
            var paradoxPath = UDirectory.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), new UDirectory(@"..\.."));
            var paradoxRelativePath = new UDirectory(paradoxPath)
                .MakeRelative(outputDirectory)
                .ToString()
                .Replace('/', '\\');
            paradoxRelativePath = paradoxRelativePath.TrimEnd('\\');

            options["Namespace"] = name;
            options["Package"] = package;
            options["Platforms"] = new List<SolutionPlatform>(AssetRegistry.SupportedPlatforms);
            options["ParadoxSdkRelativeDir"] = paradoxRelativePath;

            // Generate project template
            var projectGuid = Guid.NewGuid();
            result = projectTemplate.Generate(outputDirectory, name, projectGuid, options);
            if (result.HasErrors)
            {
                Console.WriteLine("Error generating solution: {0}", result.ToText());
                return;
            }

            var sharedProfile = package.Profiles[PlatformType.Shared];

            // Setup the assets folder
            Directory.CreateDirectory(UPath.Combine(outputDirectory, (UDirectory)"Assets/Shared"));

            // Add Windows test as Shared library
            var projectWindowsRef = new ProjectReference();
            projectWindowsRef.Id = projectGuid;
            projectWindowsRef.Location = UPath.Combine(outputDirectory, (UFile)(name + ".Windows.csproj"));
            projectWindowsRef.Type = SiliconStudio.Assets.ProjectType.Library;
            sharedProfile.ProjectReferences.Add(projectWindowsRef);

            // Generate executable projects for each platform
            foreach (var platform in AssetRegistry.SupportedPlatforms)
            {
                var platformProfile = new PackageProfile(platform.Name) { Platform = platform.Type };
                platformProfile.AssetFolders.Add(new AssetFolder("Assets/"+ platform.Name));
                
                // Log progress
                var projectName = name + "." + platform.Type;

                // Create project reference
                var projectPlatformRef = new ProjectReference();
                projectPlatformRef.Id = projectGuid;
                projectPlatformRef.Location = UPath.Combine(outputDirectory, (UFile)(projectName + ".csproj"));
                projectPlatformRef.Type = SiliconStudio.Assets.ProjectType.Executable;

                platformProfile.ProjectReferences.Add(projectPlatformRef);

                // Add build configuration per platform
                platform.Properties.CopyTo(platformProfile.Properties, true);

                package.Profiles.Add(platformProfile);
            }

            session.CurrentPackage = previousCurrent;

            result = session.Save();
            if (result.HasErrors)
            {
                Console.WriteLine("Error saving package: {0}", result.ToText());
                return;
            }
        }
Example #32
0
        /// <summary>
        /// Makes this instance relative to the specified anchor directory.
        /// </summary>
        /// <param name="anchorDirectory">The anchor directory.</param>
        /// <returns>A relative path of this instance to the anchor directory.</returns>
        public UPath MakeRelative(UDirectory anchorDirectory)
        {
            if (anchorDirectory == null)
            {
                throw new ArgumentNullException("anchorDirectory");
            }

            // If the toRelativize path is already relative, don't bother
            if (IsRelative)
            {
                return(this);
            }

            // If anchor directory is not absolute directory, throw an error
            if (!anchorDirectory.IsAbsolute || !anchorDirectory.IsDirectoryOnly)
            {
                throw new ArgumentException("Expecting an absolute directory", "anchorDirectory");
            }

            if (anchorDirectory.HasDrive != HasDrive)
            {
                throw new InvalidOperationException("Path should have no drive information/or both drive information simultaneously");
            }

            // Return a "." when the directory is the same
            if (this is UDirectory && anchorDirectory == this)
            {
                return(UDirectory.This);
            }

            // Get the full path of the anchor directory
            var anchorPath = anchorDirectory.FullPath;

            // Builds an absolute path for the toRelative path (directory-only)
            var absoluteFile = Combine(anchorDirectory, this);
            var absolutePath = absoluteFile.GetFullDirectory().FullPath;

            var relativePath = new StringBuilder();

            int  index           = anchorPath.Length;
            bool foundCommonRoot = false;

            for (; index >= 0; index--)
            {
                // Need to be a directory separator or end of string
                if (!((index == anchorPath.Length || anchorPath[index] == DirectorySeparatorChar)))
                {
                    continue;
                }

                // Absolute path needs to also have a directory separator at the same location (or end of string)
                if (index == absolutePath.Length || (index < absolutePath.Length && absolutePath[index] == DirectorySeparatorChar))
                {
                    if (string.Compare(anchorPath, 0, absolutePath, 0, index, true) == 0)
                    {
                        foundCommonRoot = true;
                        break;
                    }
                }

                relativePath.Append("..").Append(DirectorySeparatorChar);
            }

            if (!foundCommonRoot)
            {
                return(this);
            }

            if (index < absolutePath.Length && absolutePath[index] == DirectorySeparatorChar)
            {
                index++;
            }

            relativePath.Append(absolutePath.Substring(index));
            if (absoluteFile is UFile)
            {
                // If not empty, add a separator
                if (relativePath.Length > 0)
                {
                    relativePath.Append(DirectorySeparatorChar);
                }

                // Add filename
                relativePath.Append(((UFile)absoluteFile).GetFileNameWithExtension());
            }
            var newPath = relativePath.ToString();

            return(IsDirectoryOnly ? (UPath) new UDirectory(newPath) : new UFile(newPath));
        }
Example #33
0
        public void TestIsDirectoryOnly()
        {
            var dirPath = new UDirectory("/a/b/c");
            Assert.AreEqual("/a/b/c", dirPath.GetDirectory());

            var filePath = new UFile("/test.txt");
            Assert.AreEqual("/", filePath.GetDirectory());
            Assert.AreEqual("test.txt", filePath.GetFileNameWithExtension());
        }