Ejemplo n.º 1
0
        private BuildResultCode BuildMaster()
        {
            assetLogger = new RemoteLogForwarder(builderOptions.Logger, builderOptions.LogPipeNames);
            GlobalLogger.GlobalMessageLogged += assetLogger;

            // TODO handle solution file + package-id ?

            // When the current platform is not on windows, we need to make sure that all plugins are build, so we
            // setup auto-compile when loading the session
            var sessionLoadParameters = new PackageLoadParameters
                {
                    AutoCompileProjects = builderOptions.Platform != PlatformType.Windows || builderOptions.ProjectConfiguration != "Debug", // Avoid compiling if Windows|Debug
                    ExtraCompileProperties = builderOptions.ExtraCompileProperties,
                };

            // Loads the root Package
            var projectSessionResult = PackageSession.Load(builderOptions.PackageFile, sessionLoadParameters);
            if (projectSessionResult.HasErrors)
            {
                projectSessionResult.CopyTo(builderOptions.Logger);
                return BuildResultCode.BuildError;
            }

            var projectSession = projectSessionResult.Session;

            // Check build configuration
            var package = projectSession.LocalPackages.First();

            // Check build profile
            var sharedProfile = package.Profiles.FindSharedProfile();
            var buildProfile = package.Profiles.FirstOrDefault(pair => pair.Name == builderOptions.BuildProfile);
            if (buildProfile == null)
            {
                builderOptions.Logger.Error("Unable to find profile [{0}] in package [{1}]", builderOptions.BuildProfile, package.FullPath);
                return BuildResultCode.BuildError;
            }

            // Setup variables
            var buildDirectory = builderOptions.BuildDirectory;
            var outputDirectory = builderOptions.OutputDirectory;

            // Builds the project
            var assetBuilder = new PackageCompiler();
            assetBuilder.AssetCompiled += RegisterBuildStepProcessedHandler;

            // Create context
            var context = new AssetCompilerContext
            {
                Package = package,
                Platform = builderOptions.Platform
            };

            // Copy properties from shared profiles to context properties
            if (sharedProfile != null)
            {
                foreach (var propertyValue in sharedProfile.Properties)
                    context.Properties.Set(propertyValue.Key, propertyValue.Value);
            }

            context.Properties.Set(Paradox.Assets.ParadoxConfig.GraphicsPlatform, builderOptions.GraphicsPlatform.HasValue ? builderOptions.GraphicsPlatform.Value : builderOptions.GetDefaultGraphicsPlatform());

            // Copy properties from build profile
            foreach (var propertyValue in buildProfile.Properties)
            {
                context.Properties.Set(propertyValue.Key, propertyValue.Value);
            }

            var assetBuildResult = assetBuilder.Compile(context);
            assetBuildResult.CopyTo(builderOptions.Logger);
            if (assetBuildResult.HasErrors)
                return BuildResultCode.BuildError;

            // Create the builder
            var indexName = "index." + builderOptions.BuildProfile;
            builder = new Builder(buildDirectory, builderOptions.BuildProfile, indexName, "InputHashes", builderOptions.Logger) { ThreadCount = builderOptions.ThreadCount };
            builder.MonitorPipeNames.AddRange(builderOptions.MonitorPipeNames);

            // Add build steps generated by AssetBuilder
            builder.Root.Add(assetBuildResult.BuildSteps);

            // Run builder
            var result = builder.Run(Builder.Mode.Build);
            builder.WriteIndexFile(false);

            // Fill list of bundles
            var bundlePacker = new BundlePacker();
            bundlePacker.Build(builderOptions.Logger, projectSession, buildProfile, indexName, outputDirectory, builder.DisableCompressionIds);

            // Flush and close logger
            GlobalLogger.GlobalMessageLogged -= assetLogger;
            assetLogger.Dispose();
            
            return result;
        }
Ejemplo n.º 2
0
        private BuildResultCode BuildMaster()
        {
            // Only querying graphics platform, let's load package, print it and exit
            if (builderOptions.GetGraphicsPlatform)
            {
                return BuildGetGraphicsPlatform();
            }

            assetLogger = new RemoteLogForwarder(builderOptions.Logger, builderOptions.LogPipeNames);
            GlobalLogger.GlobalMessageLogged += assetLogger;
            PackageSession projectSession = null;
            try
            {
                // TODO handle solution file + package-id ?

                // When the current platform is not on windows, we need to make sure that all plugins are build, so we
                // setup auto-compile when loading the session
                var sessionLoadParameters = new PackageLoadParameters
                {
                    AutoCompileProjects = builderOptions.Platform != PlatformType.Windows || !builderOptions.DisableAutoCompileProjects,
                    ExtraCompileProperties = builderOptions.ExtraCompileProperties,
                };

                // Loads the root Package
                var projectSessionResult = PackageSession.Load(builderOptions.PackageFile, sessionLoadParameters);
                if (projectSessionResult.HasErrors)
                {
                    projectSessionResult.CopyTo(builderOptions.Logger);
                    return BuildResultCode.BuildError;
                }

                projectSession = projectSessionResult.Session;

                // Check build configuration
                var package = projectSession.LocalPackages.Last();

                // Check build profile
                var sharedProfile = package.Profiles.FindSharedProfile();
                var buildProfile = package.Profiles.FirstOrDefault(pair => pair.Name == builderOptions.BuildProfile);
                if (buildProfile == null)
                {
                    builderOptions.Logger.Error("Unable to find profile [{0}] in package [{1}]", builderOptions.BuildProfile, package.FullPath);
                    return BuildResultCode.BuildError;
                }

                // Setup variables
                var buildDirectory = builderOptions.BuildDirectory;
                var outputDirectory = builderOptions.OutputDirectory;

                // Process game settings asset
                var gameSettingsAsset = package.GetGameSettingsAsset();
                if (gameSettingsAsset == null)
                {
                    builderOptions.Logger.Warning("Could not find game settings asset at location [{0}]. Use a Default One", GameSettingsAsset.GameSettingsLocation);
                    gameSettingsAsset = new GameSettingsAsset();
                }

                // Create context
                var context = new AssetCompilerContext
                {
                    Profile = builderOptions.BuildProfile,
                    Platform = builderOptions.Platform
                };
                context.SetGameSettingsAsset(gameSettingsAsset);

                // Copy properties from shared profiles to context properties
                if (sharedProfile != null)
                {
                    sharedProfile.Properties.CopyTo(context.PackageProperties, true);
                }

                // Copy properties from build profile
                buildProfile.Properties.CopyTo(context.PackageProperties, true);

                // Builds the project
                var assetBuilder = new PackageCompiler(new RootPackageAssetEnumerator(package));
                assetBuilder.AssetCompiled += RegisterBuildStepProcessedHandler;

                var assetBuildResult = assetBuilder.Compile(context);
                assetBuildResult.CopyTo(builderOptions.Logger);
                if (assetBuildResult.HasErrors)
                    return BuildResultCode.BuildError;

                // Create the builder
                var indexName = "index." + builderOptions.BuildProfile;
                builder = new Builder(buildDirectory, builderOptions.BuildProfile, indexName, builderOptions.Logger) { ThreadCount = builderOptions.ThreadCount };
                builder.MonitorPipeNames.AddRange(builderOptions.MonitorPipeNames);

                // Add build steps generated by AssetBuilder
                builder.Root.Add(assetBuildResult.BuildSteps);

                // Run builder
                var result = builder.Run(Builder.Mode.Build);
                builder.WriteIndexFile(false);

                // Fill list of bundles
                var bundlePacker = new BundlePacker();
                bundlePacker.Build(builderOptions.Logger, projectSession, buildProfile, indexName, outputDirectory, builder.DisableCompressionIds);

                return result;
            }
            finally
            {
                if (builder != null)
                {
                    builder.Dispose();
                }

                // Dispose the session (in order to unload assemblies)
                if (projectSession != null)
                {
                    projectSession.Dispose();
                }

                // Flush and close logger
                GlobalLogger.GlobalMessageLogged -= assetLogger;
                assetLogger.Dispose();
            }
        }
Ejemplo n.º 3
0
        private BuildResultCode BuildMaster()
        {
            assetLogger = new RemoteLogForwarder(builderOptions.Logger, builderOptions.LogPipeNames);
            GlobalLogger.GlobalMessageLogged += assetLogger;

            // TODO handle solution file + package-id ?

            // When the current platform is not on windows, we need to make sure that all plugins are build, so we
            // setup auto-compile when loading the session
            var sessionLoadParameters = new PackageLoadParameters
            {
                AutoCompileProjects    = builderOptions.Platform != PlatformType.Windows || builderOptions.ProjectConfiguration != "Debug",  // Avoid compiling if Windows|Debug
                ExtraCompileProperties = builderOptions.ExtraCompileProperties,
            };

            // Loads the root Package
            var projectSessionResult = PackageSession.Load(builderOptions.PackageFile, sessionLoadParameters);

            if (projectSessionResult.HasErrors)
            {
                projectSessionResult.CopyTo(builderOptions.Logger);
                return(BuildResultCode.BuildError);
            }

            var projectSession = projectSessionResult.Session;

            // Check build configuration
            var package = projectSession.LocalPackages.First();

            // Check build profile
            var sharedProfile = package.Profiles.FindSharedProfile();
            var buildProfile  = package.Profiles.FirstOrDefault(pair => pair.Name == builderOptions.BuildProfile);

            if (buildProfile == null)
            {
                builderOptions.Logger.Error("Unable to find profile [{0}] in package [{1}]", builderOptions.BuildProfile, package.FullPath);
                return(BuildResultCode.BuildError);
            }

            // Setup variables
            var buildDirectory  = builderOptions.BuildDirectory;
            var outputDirectory = builderOptions.OutputDirectory;

            // Builds the project
            var assetBuilder = new PackageCompiler();

            assetBuilder.AssetCompiled += RegisterBuildStepProcessedHandler;

            // Create context
            var context = new AssetCompilerContext
            {
                Package  = package,
                Platform = builderOptions.Platform
            };

            // Copy properties from shared profiles to context properties
            if (sharedProfile != null)
            {
                foreach (var propertyValue in sharedProfile.Properties)
                {
                    context.Properties.Set(propertyValue.Key, propertyValue.Value);
                }
            }

            context.Properties.Set(Paradox.Assets.ParadoxConfig.GraphicsPlatform, builderOptions.GraphicsPlatform.HasValue ? builderOptions.GraphicsPlatform.Value : builderOptions.GetDefaultGraphicsPlatform());

            // Copy properties from build profile
            foreach (var propertyValue in buildProfile.Properties)
            {
                context.Properties.Set(propertyValue.Key, propertyValue.Value);
            }

            var assetBuildResult = assetBuilder.Compile(context);

            assetBuildResult.CopyTo(builderOptions.Logger);
            if (assetBuildResult.HasErrors)
            {
                return(BuildResultCode.BuildError);
            }

            // Create the builder
            var indexName = "index." + builderOptions.BuildProfile;

            builder = new Builder(buildDirectory, builderOptions.BuildProfile, indexName, "InputHashes", builderOptions.Logger)
            {
                ThreadCount = builderOptions.ThreadCount
            };
            builder.MonitorPipeNames.AddRange(builderOptions.MonitorPipeNames);

            // Add build steps generated by AssetBuilder
            builder.Root.Add(assetBuildResult.BuildSteps);

            // Run builder
            var result = builder.Run(Builder.Mode.Build);

            builder.WriteIndexFile(false);

            // Fill list of bundles
            var bundlePacker = new BundlePacker();

            bundlePacker.Build(builderOptions.Logger, projectSession, buildProfile, indexName, outputDirectory, builder.DisableCompressionIds);

            // Flush and close logger
            GlobalLogger.GlobalMessageLogged -= assetLogger;
            assetLogger.Dispose();

            return(result);
        }
Ejemplo n.º 4
0
        private BuildResultCode BuildMaster()
        {
            // Only querying graphics platform, let's load package, print it and exit
            if (builderOptions.GetGraphicsPlatform)
            {
                return(BuildGetGraphicsPlatform());
            }

            assetLogger = new RemoteLogForwarder(builderOptions.Logger, builderOptions.LogPipeNames);
            GlobalLogger.GlobalMessageLogged += assetLogger;
            PackageSession projectSession = null;

            try
            {
                // TODO handle solution file + package-id ?

                // When the current platform is not on windows, we need to make sure that all plugins are build, so we
                // setup auto-compile when loading the session
                var sessionLoadParameters = new PackageLoadParameters
                {
                    AutoCompileProjects    = builderOptions.Platform != PlatformType.Windows || !builderOptions.DisableAutoCompileProjects,
                    ExtraCompileProperties = builderOptions.ExtraCompileProperties,
                };

                // Loads the root Package
                var projectSessionResult = PackageSession.Load(builderOptions.PackageFile, sessionLoadParameters);
                if (projectSessionResult.HasErrors)
                {
                    projectSessionResult.CopyTo(builderOptions.Logger);
                    return(BuildResultCode.BuildError);
                }

                projectSession = projectSessionResult.Session;

                // Check build configuration
                var package = projectSession.LocalPackages.Last();

                // Check build profile
                var sharedProfile = package.Profiles.FindSharedProfile();
                var buildProfile  = package.Profiles.FirstOrDefault(pair => pair.Name == builderOptions.BuildProfile);
                if (buildProfile == null)
                {
                    builderOptions.Logger.Error("Unable to find profile [{0}] in package [{1}]", builderOptions.BuildProfile, package.FullPath);
                    return(BuildResultCode.BuildError);
                }

                // Setup variables
                var buildDirectory  = builderOptions.BuildDirectory;
                var outputDirectory = builderOptions.OutputDirectory;

                // Process game settings asset
                var gameSettingsAsset = package.GetGameSettingsAsset();
                if (gameSettingsAsset == null)
                {
                    builderOptions.Logger.Warning("Could not find game settings asset at location [{0}]. Use a Default One", GameSettingsAsset.GameSettingsLocation);
                    gameSettingsAsset = new GameSettingsAsset();
                }

                // Create context
                var context = new AssetCompilerContext
                {
                    Profile  = builderOptions.BuildProfile,
                    Platform = builderOptions.Platform
                };
                context.SetGameSettingsAsset(gameSettingsAsset);

                // Copy properties from shared profiles to context properties
                if (sharedProfile != null)
                {
                    sharedProfile.Properties.CopyTo(context.PackageProperties, true);
                }

                // Copy properties from build profile
                buildProfile.Properties.CopyTo(context.PackageProperties, true);

                // Builds the project
                var assetBuilder = new PackageCompiler(new RootPackageAssetEnumerator(package));
                assetBuilder.AssetCompiled += RegisterBuildStepProcessedHandler;

                var assetBuildResult = assetBuilder.Compile(context);
                assetBuildResult.CopyTo(builderOptions.Logger);
                if (assetBuildResult.HasErrors)
                {
                    return(BuildResultCode.BuildError);
                }

                // Create the builder
                var indexName = "index." + builderOptions.BuildProfile;
                builder = new Builder(buildDirectory, builderOptions.BuildProfile, indexName, builderOptions.Logger)
                {
                    ThreadCount = builderOptions.ThreadCount
                };
                builder.MonitorPipeNames.AddRange(builderOptions.MonitorPipeNames);

                // Add build steps generated by AssetBuilder
                builder.Root.Add(assetBuildResult.BuildSteps);

                // Run builder
                var result = builder.Run(Builder.Mode.Build);
                builder.WriteIndexFile(false);

                // Fill list of bundles
                var bundlePacker = new BundlePacker();
                bundlePacker.Build(builderOptions.Logger, projectSession, buildProfile, indexName, outputDirectory, builder.DisableCompressionIds);

                return(result);
            }
            finally
            {
                if (builder != null)
                {
                    builder.Dispose();
                }

                // Dispose the session (in order to unload assemblies)
                if (projectSession != null)
                {
                    projectSession.Dispose();
                }

                // Flush and close logger
                GlobalLogger.GlobalMessageLogged -= assetLogger;
                assetLogger.Dispose();
            }
        }
Ejemplo n.º 5
0
        private BuildResultCode BuildMaster()
        {
            // Only querying graphics platform, let's load package, print it and exit
            if (builderOptions.GetGraphicsPlatform)
            {
                return(BuildGetGraphicsPlatform());
            }

            AssetCompilerContext context        = null;
            PackageSession       projectSession = null;

            try
            {
                // When the current platform is not on windows, we need to make sure that all plugins are build, so we
                // setup auto-compile when loading the session
                var sessionLoadParameters = new PackageLoadParameters
                {
                    AutoCompileProjects     = builderOptions.Platform != PlatformType.Windows || !builderOptions.DisableAutoCompileProjects,
                    ExtraCompileProperties  = builderOptions.ExtraCompileProperties,
                    RemoveUnloadableObjects = true,
                };

                // Loads the root Package
                var projectSessionResult = PackageSession.Load(builderOptions.PackageFile, sessionLoadParameters);
                projectSessionResult.CopyTo(builderOptions.Logger);
                if (projectSessionResult.HasErrors)
                {
                    return(BuildResultCode.BuildError);
                }

                projectSession = projectSessionResult.Session;

                // Check build configuration
                var package = projectSession.LocalPackages.Last();

                // Check build profile
                var buildProfile = package.Profiles.FirstOrDefault(pair => pair.Name == builderOptions.BuildProfile);
                if (buildProfile == null)
                {
                    builderOptions.Logger.Error($"Unable to find profile [{builderOptions.BuildProfile}] in package [{package.FullPath}]");
                    return(BuildResultCode.BuildError);
                }

                // Setup variables
                var buildDirectory  = builderOptions.BuildDirectory;
                var outputDirectory = builderOptions.OutputDirectory;

                // Process game settings asset
                var gameSettingsAsset = package.GetGameSettingsAsset();
                if (gameSettingsAsset == null)
                {
                    builderOptions.Logger.Warning($"Could not find game settings asset at location [{GameSettingsAsset.GameSettingsLocation}]. Use a Default One");
                    gameSettingsAsset = GameSettingsFactory.Create();
                }

                // Create context
                context = new AssetCompilerContext
                {
                    Profile            = builderOptions.BuildProfile,
                    Platform           = builderOptions.Platform,
                    CompilationContext = typeof(AssetCompilationContext),
                    BuildConfiguration = builderOptions.ProjectConfiguration
                };

                // Command line properties
                foreach (var property in builderOptions.Properties)
                {
                    context.OptionProperties.Add(property.Key, property.Value);
                }

                // Set current game settings
                context.SetGameSettingsAsset(gameSettingsAsset);

                // Builds the project
                var assetBuilder = new PackageCompiler(new RootPackageAssetEnumerator(package));
                assetBuilder.AssetCompiled += RegisterBuildStepProcessedHandler;

                context.Properties.Set(BuildAssetNode.VisitRuntimeTypes, true);
                var assetBuildResult = assetBuilder.Prepare(context);
                assetBuildResult.CopyTo(builderOptions.Logger);
                if (assetBuildResult.HasErrors)
                {
                    return(BuildResultCode.BuildError);
                }

                // Create the builder
                var indexName = "index." + builderOptions.BuildProfile;
                builder = new Builder(builderOptions.Logger, buildDirectory, builderOptions.BuildProfile, indexName)
                {
                    ThreadCount = builderOptions.ThreadCount
                };

                // Note: try to get exec server if it exists, otherwise use CompilerApp.exe
                builder.SlaveBuilderPath = (string)AppDomain.CurrentDomain.GetData("RealEntryAssemblyFile") ?? typeof(PackageBuilder).Assembly.Location;

                builder.MonitorPipeNames.AddRange(builderOptions.MonitorPipeNames);

                // Add build steps generated by AssetBuilder
                builder.Root.Add(assetBuildResult.BuildSteps);

                // Run builder
                var result = builder.Run(Builder.Mode.Build);
                builder.WriteIndexFile(false);

                // Fill list of bundles
                var bundlePacker = new BundlePacker();
                bundlePacker.Build(builderOptions.Logger, projectSession, buildProfile, indexName, outputDirectory, builder.DisableCompressionIds, context.GetCompilationMode() != CompilationMode.AppStore);

                return(result);
            }
            finally
            {
                builder?.Dispose();
                // Dispose the session (in order to unload assemblies)
                projectSession?.Dispose();
                context?.Dispose();
            }
        }
Ejemplo n.º 6
0
        private BuildResultCode BuildMaster()
        {
            // Only querying graphics platform, let's load package, print it and exit
            if (builderOptions.GetGraphicsPlatform)
            {
                return(BuildGetGraphicsPlatform());
            }

            AssetCompilerContext context        = null;
            PackageSession       projectSession = null;

            try
            {
                // TODO handle solution file + package-id ?

                // When the current platform is not on windows, we need to make sure that all plugins are build, so we
                // setup auto-compile when loading the session
                var sessionLoadParameters = new PackageLoadParameters
                {
                    AutoCompileProjects     = builderOptions.Platform != PlatformType.Windows || !builderOptions.DisableAutoCompileProjects,
                    ExtraCompileProperties  = builderOptions.ExtraCompileProperties,
                    RemoveUnloadableObjects = true,
                };

                // Loads the root Package
                var projectSessionResult = PackageSession.Load(builderOptions.PackageFile, sessionLoadParameters);
                projectSessionResult.CopyTo(builderOptions.Logger);
                if (projectSessionResult.HasErrors)
                {
                    return(BuildResultCode.BuildError);
                }

                projectSession = projectSessionResult.Session;

                // Check build configuration
                var package = projectSession.LocalPackages.Last();

                // Check build profile
                var sharedProfile = package.Profiles.FindSharedProfile();
                var buildProfile  = package.Profiles.FirstOrDefault(pair => pair.Name == builderOptions.BuildProfile);
                if (buildProfile == null)
                {
                    builderOptions.Logger.Error("Unable to find profile [{0}] in package [{1}]", builderOptions.BuildProfile, package.FullPath);
                    return(BuildResultCode.BuildError);
                }

                // Setup variables
                var buildDirectory  = builderOptions.BuildDirectory;
                var outputDirectory = builderOptions.OutputDirectory;

                // Process game settings asset
                var gameSettingsAsset = package.GetGameSettingsAsset();
                if (gameSettingsAsset == null)
                {
                    builderOptions.Logger.Warning("Could not find game settings asset at location [{0}]. Use a Default One", GameSettingsAsset.GameSettingsLocation);
                    gameSettingsAsset = GameSettingsFactory.Create();
                }

                // Create context
                context = new AssetCompilerContext
                {
                    Profile            = builderOptions.BuildProfile,
                    Platform           = builderOptions.Platform,
                    BuildConfiguration = builderOptions.ProjectConfiguration
                };

                // Command line properties
                foreach (var property in builderOptions.Properties)
                {
                    context.OptionProperties.Add(property.Key, property.Value);
                }

                // Set current game settings
                context.SetGameSettingsAsset(gameSettingsAsset);

                // Builds the project
                var assetBuilder = new PackageCompiler(new RootPackageAssetEnumerator(package));
                assetBuilder.AssetCompiled += RegisterBuildStepProcessedHandler;

                var assetBuildResult = assetBuilder.Compile(context);
                assetBuildResult.CopyTo(builderOptions.Logger);
                if (assetBuildResult.HasErrors)
                {
                    return(BuildResultCode.BuildError);
                }

                // Add specific steps to generate shaders
                // TODO: This doesn't really belong here, where should we move it?
                //assetBuildResult.BuildSteps.Add(new WaitBuildStep());
                //assetBuildResult.BuildSteps.Add(new CompileDefaultSceneEffectCommand(context, package, assetBuildResult));

                // Create the builder
                var indexName = "index." + builderOptions.BuildProfile;
                builder = new Builder(builderOptions.Logger, buildDirectory, builderOptions.BuildProfile, indexName)
                {
                    ThreadCount = builderOptions.ThreadCount
                };
                builder.MonitorPipeNames.AddRange(builderOptions.MonitorPipeNames);

                // Add build steps generated by AssetBuilder
                builder.Root.Add(assetBuildResult.BuildSteps);

                // Run builder
                var result = builder.Run(Builder.Mode.Build);
                builder.WriteIndexFile(false);

                // Fill list of bundles
                var bundlePacker = new BundlePacker();
                bundlePacker.Build(builderOptions.Logger, projectSession, buildProfile, indexName, outputDirectory, builder.DisableCompressionIds);

                return(result);
            }
            finally
            {
                builder?.Dispose();
                // Dispose the session (in order to unload assemblies)
                projectSession?.Dispose();
                context?.Dispose();
            }
        }
Ejemplo n.º 7
0
 public override bool Upgrade(PackageLoadParameters loadParameters, PackageSession session, ILogger log, Package dependentPackage, PackageDependency dependency, Package dependencyPackage, IList <PackageLoadingAssetFile> assetFiles)
 {
     return(true);
 }
Ejemplo n.º 8
0
        public override bool UpgradeBeforeAssembliesLoaded(PackageLoadParameters loadParameters, PackageSession session, ILogger log, Package dependentPackage, PackageDependency dependency, Package dependencyPackage)
        {
            // Update NuGet references
            var projectFullPath = (dependentPackage.Container as SolutionProject)?.FullPath;

            if (projectFullPath != null)
            {
                try
                {
                    var project        = VSProjectHelper.LoadProject(projectFullPath.ToWindowsPath());
                    var isProjectDirty = false;

                    var packageReferences = project.GetItems("PackageReference").ToList();

                    // Upgrade from 3.0 to 3.1 (Xenko split in several nuget packages)
                    if (dependency.Version.MinVersion < new PackageVersion("3.1.0.0"))
                    {
                        var xenkoReference = packageReferences.FirstOrDefault(packageReference => packageReference.EvaluatedInclude == "Xenko");
                        if (xenkoReference != null)
                        {
                            var items = new List <Microsoft.Build.Evaluation.ProjectItem> {
                                xenkoReference
                            };

                            // Turn Xenko reference into Xenko.Engine
                            xenkoReference.UnevaluatedInclude = "Xenko.Engine";
                            xenkoReference.SetMetadataValue("Version", CurrentVersion);

                            // Add plugins (old Xenko is equivalent to a meta package with all plugins)
                            items.AddRange(project.AddItem("PackageReference", "Xenko.Video", new[] { new KeyValuePair <string, string>("Version", CurrentVersion), new KeyValuePair <string, string>("PrivateAssets", "contentfiles;analyzers") }));
                            items.AddRange(project.AddItem("PackageReference", "Xenko.Physics", new[] { new KeyValuePair <string, string>("Version", CurrentVersion), new KeyValuePair <string, string>("PrivateAssets", "contentfiles;analyzers") }));
                            items.AddRange(project.AddItem("PackageReference", "Xenko.Navigation", new[] { new KeyValuePair <string, string>("Version", CurrentVersion), new KeyValuePair <string, string>("PrivateAssets", "contentfiles;analyzers") }));
                            items.AddRange(project.AddItem("PackageReference", "Xenko.Particles", new[] { new KeyValuePair <string, string>("Version", CurrentVersion), new KeyValuePair <string, string>("PrivateAssets", "contentfiles;analyzers") }));
                            items.AddRange(project.AddItem("PackageReference", "Xenko.UI", new[] { new KeyValuePair <string, string>("Version", CurrentVersion), new KeyValuePair <string, string>("PrivateAssets", "contentfiles;analyzers") }));
                            // Necessary until "build" flows transitively
                            items.AddRange(project.AddItem("PackageReference", "Xenko.Core", new[] { new KeyValuePair <string, string>("Version", CurrentVersion), new KeyValuePair <string, string>("PrivateAssets", "contentfiles;analyzers") }));

                            // Asset compiler
                            items.AddRange(project.AddItem("PackageReference", "Xenko.Core.Assets.CompilerApp", new[] { new KeyValuePair <string, string>("Version", CurrentVersion), new KeyValuePair <string, string>("PrivateAssets", "contentfiles;analyzers"), new KeyValuePair <string, string>("IncludeAssets", "build") }));

                            foreach (var item in items)
                            {
                                foreach (var metadata in item.Metadata)
                                {
                                    metadata.Xml.ExpressedAsAttribute = true;
                                }
                            }

                            isProjectDirty = true;
                        }
                    }

                    foreach (var packageReference in packageReferences)
                    {
                        if (packageReference.EvaluatedInclude.StartsWith("Xenko.") && packageReference.GetMetadataValue("Version") != CurrentVersion)
                        {
                            packageReference.SetMetadataValue("Version", CurrentVersion).Xml.ExpressedAsAttribute = true;
                            foreach (var metadata in packageReference.Metadata)
                            {
                                metadata.Xml.ExpressedAsAttribute = true;
                            }
                            isProjectDirty = true;
                        }
                    }

                    if (isProjectDirty)
                    {
                        project.Save();
                    }

                    project.ProjectCollection.UnloadAllProjects();
                    project.ProjectCollection.Dispose();
                }
                catch (Exception e)
                {
                    log.Warning($"Unable to load project [{projectFullPath.GetFileName()}]", e);
                }
            }

            return(true);
        }
Ejemplo n.º 9
0
        public override bool UpgradeBeforeAssembliesLoaded(PackageLoadParameters loadParameters, PackageSession session, ILogger log, Package dependentPackage, PackageDependency dependency, Package dependencyPackage)
        {
            // Xenko to Stride renaming
            if (dependency.Version.MinVersion < new PackageVersion("4.0.0.0"))
            {
                UpgradeStrideCode(dependentPackage, log);
            }

            // Update NuGet references
            var projectFullPath = (dependentPackage.Container as SolutionProject)?.FullPath;

            if (projectFullPath != null)
            {
                try
                {
                    var project        = VSProjectHelper.LoadProject(projectFullPath.ToWindowsPath());
                    var isProjectDirty = false;

                    var packageReferences = project.GetItems("PackageReference").ToList();

                    foreach (var packageReference in packageReferences)
                    {
                        if (packageReference.EvaluatedInclude.StartsWith("Stride.") && packageReference.GetMetadataValue("Version") != CurrentVersion)
                        {
                            packageReference.SetMetadataValue("Version", CurrentVersion).Xml.ExpressedAsAttribute = true;
                            foreach (var metadata in packageReference.Metadata)
                            {
                                metadata.Xml.ExpressedAsAttribute = true;
                            }
                            isProjectDirty = true;
                        }
                    }

                    // Change shader generated file from .cs to .xksl.cs or .xkfx.cs
                    // Note: we support both 3.1.0.1 (.cs) and 3.2.0.1 (.xksl.cs)
                    if (dependency.Version.MinVersion < new PackageVersion("4.0.0.0"))
                    {
                        // Find xksl files
                        var shaderFiles = project.Items.Where(x => x.ItemType == "None" && (x.EvaluatedInclude.EndsWith(".xksl", StringComparison.InvariantCultureIgnoreCase) || x.EvaluatedInclude.EndsWith(".xkfx", StringComparison.InvariantCultureIgnoreCase)) && x.HasMetadata("Generator")).ToArray();

                        foreach (var shaderFile in shaderFiles)
                        {
                            isProjectDirty = true;

                            var shaderFilePath       = Path.Combine(projectFullPath.GetFullDirectory(), new UFile(shaderFile.EvaluatedInclude));
                            var oldGeneratedFilePath = Path.ChangeExtension(shaderFilePath, ".cs");

                            if (!File.Exists(oldGeneratedFilePath))
                            {
                                oldGeneratedFilePath = shaderFilePath + ".cs";
                            }

                            if (File.Exists(oldGeneratedFilePath))
                            {
                                var newShaderFilePath = shaderFilePath.Replace(".xk", ".sd");
                                File.Move(shaderFilePath, newShaderFilePath);
                                File.Move(oldGeneratedFilePath, newShaderFilePath + ".cs");

                                // Remove Items (.xksl .cs and .xksl.cs)
                                foreach (var csElement in project.Xml.ItemGroups.SelectMany(x => x.Items).Where(x =>
                                                                                                                new UFile(x.Include) == new UFile(Path.ChangeExtension(shaderFile.EvaluatedInclude, ".cs")) ||
                                                                                                                new UFile(x.Include) == new UFile(shaderFile.EvaluatedInclude + ".cs") ||
                                                                                                                new UFile(x.Include) == new UFile(shaderFile.EvaluatedInclude) ||
                                                                                                                new UFile(x.Update) == new UFile(Path.ChangeExtension(shaderFile.EvaluatedInclude, ".cs")) ||
                                                                                                                new UFile(x.Update) == new UFile(shaderFile.EvaluatedInclude + ".cs") ||
                                                                                                                new UFile(x.Update) == new UFile(shaderFile.EvaluatedInclude)
                                                                                                                ).ToArray())
                                {
                                    csElement.Parent.RemoveChild(csElement);
                                }

                                if (!shaderFile.IsImported)
                                {
                                    project.RemoveItem(shaderFile);
                                }
                            }
                        }
                    }

                    if (isProjectDirty)
                    {
                        project.Save();
                    }

                    project.ProjectCollection.UnloadAllProjects();
                    project.ProjectCollection.Dispose();
                }
                catch (Exception e)
                {
                    log.Warning($"Unable to load project [{projectFullPath.GetFileName()}]", e);
                }
            }

            return(true);
        }
Ejemplo n.º 10
0
        private BuildResultCode BuildMaster()
        {
            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;
                builderOptions.Logger.Error(message);
                return(BuildResultCode.BuildError);
            }

            AssetCompilerContext context        = null;
            PackageSession       projectSession = null;

            try
            {
                var sessionLoadParameters = new PackageLoadParameters
                {
                    AutoCompileProjects     = !builderOptions.DisableAutoCompileProjects,
                    ExtraCompileProperties  = builderOptions.ExtraCompileProperties,
                    RemoveUnloadableObjects = true,
                    BuildConfiguration      = builderOptions.ProjectConfiguration,
                };

                // Loads the root Package
                var projectSessionResult = PackageSession.Load(builderOptions.PackageFile, sessionLoadParameters);
                projectSessionResult.CopyTo(builderOptions.Logger);
                if (projectSessionResult.HasErrors)
                {
                    return(BuildResultCode.BuildError);
                }

                projectSession = projectSessionResult.Session;

                // Find loaded package (either sdpkg or csproj) -- otherwise fallback to first one
                var packageFile = (UFile)builderOptions.PackageFile;
                var package     = projectSession.Packages.FirstOrDefault(x => x.FullPath == packageFile || (x.Container is SolutionProject project && project.FullPath == packageFile))
                                  ?? projectSession.LocalPackages.FirstOrDefault()
                                  ?? projectSession.Packages.FirstOrDefault();

                // Setup variables
                var buildDirectory  = builderOptions.BuildDirectory;
                var outputDirectory = builderOptions.OutputDirectory;

                // Process game settings asset
                var gameSettingsAsset = package.GetGameSettingsAsset();
                if (gameSettingsAsset == null)
                {
                    builderOptions.Logger.Warning($"Could not find game settings asset at location [{GameSettingsAsset.GameSettingsLocation}]. Use a Default One");
                    gameSettingsAsset = GameSettingsFactory.Create();
                }

                // Create context
                context = new AssetCompilerContext
                {
                    Platform           = builderOptions.Platform,
                    CompilationContext = typeof(AssetCompilationContext),
                    BuildConfiguration = builderOptions.ProjectConfiguration,
                    Package            = package,
                };

                // Command line properties
                foreach (var property in builderOptions.Properties)
                {
                    context.OptionProperties.Add(property.Key, property.Value);
                }

                // Set current game settings
                context.SetGameSettingsAsset(gameSettingsAsset);

                // Builds the project
                var assetBuilder = new PackageCompiler(new RootPackageAssetEnumerator(package));
                assetBuilder.AssetCompiled += RegisterBuildStepProcessedHandler;

                context.Properties.Set(BuildAssetNode.VisitRuntimeTypes, true);
                var assetBuildResult = assetBuilder.Prepare(context);
                assetBuildResult.CopyTo(builderOptions.Logger);
                if (assetBuildResult.HasErrors)
                {
                    return(BuildResultCode.BuildError);
                }

                // Setup the remote process build
                var remoteBuilderHelper = new PackageBuilderRemoteHelper(projectSession.AssemblyContainer, builderOptions);

                var indexName = $"index.{package.Meta.Name}.{builderOptions.Platform}";
                // Add runtime identifier (if any) to avoid clash when building multiple at the same time (this happens when using ExtrasBuildEachRuntimeIdentifier feature of MSBuild.Sdk.Extras)
                if (builderOptions.Properties.TryGetValue("RuntimeIdentifier", out var runtimeIdentifier))
                {
                    indexName += $".{runtimeIdentifier}";
                }
                if (builderOptions.ExtraCompileProperties != null && builderOptions.ExtraCompileProperties.TryGetValue("StrideGraphicsApi", out var graphicsApi))
                {
                    indexName += $".{graphicsApi}";
                }

                // Create the builder
                builder = new Builder(builderOptions.Logger, buildDirectory, indexName)
                {
                    ThreadCount = builderOptions.ThreadCount, TryExecuteRemote = remoteBuilderHelper.TryExecuteRemote
                };

                builder.MonitorPipeNames.AddRange(builderOptions.MonitorPipeNames);

                // Add build steps generated by AssetBuilder
                builder.Root.Add(assetBuildResult.BuildSteps);

                // Run builder
                var result = builder.Run(Builder.Mode.Build);
                builder.WriteIndexFile(false);

                // Fill list of bundles
                var bundlePacker = new BundlePacker();
                var bundleFiles  = new List <string>();
                bundlePacker.Build(builderOptions.Logger, projectSession, package, indexName, outputDirectory, builder.DisableCompressionIds, context.GetCompilationMode() != CompilationMode.AppStore, bundleFiles);

                if (builderOptions.MSBuildUpToDateCheckFileBase != null)
                {
                    SaveBuildUpToDateFile(builderOptions.MSBuildUpToDateCheckFileBase, package, bundleFiles);
                }

                return(result);
            }
            finally
            {
                builder?.Dispose();
                // Dispose the session (in order to unload assemblies)
                projectSession?.Dispose();
                context?.Dispose();

                // Make sure that MSBuild doesn't hold anything else
                VSProjectHelper.Reset();
            }
        }
Ejemplo n.º 11
0
        protected override bool Generate(SessionTemplateGeneratorParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }
            parameters.Validate();

            var description = (TemplateSampleDescription)parameters.Description;
            var log         = parameters.Logger;

            // The package might depend on other packages which need to be copied together when instanciating it.
            //  However some of these packages might be in a parent folder, which can result in undesired behavior when copied.
            //  Setting this to true will enforce all package dependencies to be moved to a folder local to the project
            bool doMoveParentDependencies = true;

            var packageFile = Path.ChangeExtension(description.FullPath, Package.PackageFileExtension);

            if (!File.Exists(packageFile))
            {
                log.Error($"Unable to find package [{packageFile}]");
                return(false);
            }

            var packageLoadResult = new LoggerResult();
            var package           = Package.Load(packageLoadResult, packageFile, new PackageLoadParameters
            {
                AutoLoadTemporaryAssets = false,
                AutoCompileProjects     = false,
                LoadAssemblyReferences  = false,
            });

            packageLoadResult.CopyTo(log);
            if (packageLoadResult.HasErrors)
            {
                return(false);
            }

            // We are going to replace all projects id by new ids
            var idsToReplace = package.Profiles.SelectMany(profile => profile.ProjectReferences).Select(project => project.Id).Distinct().ToDictionary(guid => guid.ToString("D"), guid => Guid.NewGuid(), StringComparer.OrdinalIgnoreCase);

            idsToReplace.Add(package.Id.ToString("D"), Guid.NewGuid());

            // Add dependencies
            foreach (var packageReference in package.LocalDependencies)
            {
                description.FullPath.GetFullDirectory();

                var referencePath = UPath.Combine(description.FullPath.GetFullDirectory(), packageReference.Location);

                if (!File.Exists(referencePath))
                {
                    log.Error($"Unable to find dependency package [{referencePath}]");
                    return(false);
                }

                var referenceLoadResult = new LoggerResult();
                var reference           = Package.Load(referenceLoadResult, referencePath, new PackageLoadParameters
                {
                    AutoLoadTemporaryAssets = false,
                    AutoCompileProjects     = false,
                    LoadAssemblyReferences  = false,
                });
                referenceLoadResult.CopyTo(log);
                if (referenceLoadResult.HasErrors)
                {
                    return(false);
                }

                var extraIdsToReplace = reference.Profiles.SelectMany(profile => profile.ProjectReferences).Select(project => project.Id).Distinct().ToDictionary(guid => guid.ToString("D"), guid => Guid.NewGuid(), StringComparer.OrdinalIgnoreCase);

                idsToReplace.AddRange(extraIdsToReplace);
            }

            var guidRegexPattern = new StringBuilder();

            guidRegexPattern.Append("(");
            guidRegexPattern.Append(string.Join("|", idsToReplace.Keys));
            guidRegexPattern.Append(")");

            var regexes = new List <Tuple <Regex, MatchEvaluator> >();

            var guidRegex = new Tuple <Regex, MatchEvaluator>(new Regex(guidRegexPattern.ToString(), RegexOptions.IgnoreCase),
                                                              match => idsToReplace[match.Groups[1].Value].ToString("D"));

            regexes.Add(guidRegex);
            var patternName = description.PatternName ?? description.DefaultOutputName;

            // Samples don't support spaces and dot in name (we would need to separate package name, package short name and namespace renaming for that).
            var parametersName = parameters.Name.Replace(" ", string.Empty).Replace(".", string.Empty);

            if (patternName != parametersName)
            {
                // Make sure the target name is a safe for use everywhere, since both an asset or script might reference a filename
                //  in which case they should match and be valid in that context
                string validNamespaceName = Utilities.BuildValidNamespaceName(parametersName);

                // Rename for general occurences of template name
                regexes.Add(new Tuple <Regex, MatchEvaluator>(new Regex($@"\b{patternName}\b"), match => validNamespaceName));

                // Rename App as well (used in code) -- this is the only pattern of "package short name" that we have so far in Windows samples
                regexes.Add(new Tuple <Regex, MatchEvaluator>(new Regex($@"\b{patternName}App\b"), match => validNamespaceName));
            }

            var outputDirectory = parameters.OutputDirectory;

            if (!Directory.Exists(outputDirectory))
            {
                Directory.CreateDirectory(outputDirectory);
            }

            //write gitignore
            WriteGitIgnore(parameters);

            UFile packageOutputFile = null;

            // Process files
            foreach (var directory in FileUtility.EnumerateDirectories(description.TemplateDirectory, SearchDirection.Down))
            {
                foreach (var file in directory.GetFiles())
                {
                    // If the file is ending with the Template extension or a directory with the sample extension, don;t copy it
                    if (file.FullName.EndsWith(TemplateDescription.FileExtension) ||
                        string.Compare(directory.Name, TemplateDescription.FileExtension, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        continue;
                    }

                    var relativeFile = new UFile(file.FullName).MakeRelative(description.TemplateDirectory);

                    // Replace the name in the files if necessary
                    foreach (var nameRegex in regexes)
                    {
                        relativeFile = nameRegex.Item1.Replace(relativeFile, nameRegex.Item2);
                    }

                    // Create the output directory if needed
                    var outputFile          = UPath.Combine(outputDirectory, relativeFile);
                    var outputFileDirectory = outputFile.GetParent();

                    // Grab the name of the output package file
                    var isPackageFile = (packageOutputFile == null && file.FullName.EndsWith(Package.PackageFileExtension));

                    if (isPackageFile)
                    {
                        packageOutputFile = outputFile;
                    }

                    if (!Directory.Exists(outputFileDirectory))
                    {
                        Directory.CreateDirectory(outputFileDirectory);
                    }

                    if (IsBinaryFile(file.FullName))
                    {
                        File.Copy(file.FullName, outputFile, true);
                    }
                    else
                    {
                        ProcessTextFile(file.FullName, outputFile, regexes, (isPackageFile && doMoveParentDependencies));
                    }
                }
            }

            // Copy dependency files locally
            //  We only want to copy the asset files. The raw files are in Resources and the game assets are in Assets.
            //  If we copy each file locally they will be included in the package and we can then delete the dependency packages.
            foreach (var packageReference in package.LocalDependencies)
            {
                var packageDirectory = packageReference.Location.GetFullDirectory();
                foreach (var directory in FileUtility.EnumerateDirectories(packageDirectory, SearchDirection.Down))
                {
                    foreach (var file in directory.GetFiles())
                    {
                        // If the file is ending with the Template extension or a directory with the sample extension, don`t copy it
                        if (file.FullName.EndsWith(TemplateDescription.FileExtension) ||
                            string.Compare(directory.Name, TemplateDescription.FileExtension, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            continue;
                        }

                        var relativeFile     = new UFile(file.FullName).MakeRelative(packageDirectory);
                        var relativeFilename = relativeFile.ToString();

                        bool isAsset    = relativeFilename.Contains("Assets");
                        bool isResource = relativeFilename.Contains("Resources");

                        if (!isAsset && !isResource)
                        {
                            continue;
                        }

                        // Replace the name in the files if necessary
                        foreach (var nameRegex in regexes)
                        {
                            relativeFile = nameRegex.Item1.Replace(relativeFile, nameRegex.Item2);
                        }

                        var outputFile = UPath.Combine(outputDirectory, relativeFile);
                        {   // Create the output directory if needed
                            var outputFileDirectory = outputFile.GetParent();
                            if (!Directory.Exists(outputFileDirectory))
                            {
                                Directory.CreateDirectory(outputFileDirectory);
                            }
                        }

                        if (IsBinaryFile(file.FullName))
                        {
                            File.Copy(file.FullName, outputFile, true);
                        }
                        else
                        {
                            ProcessTextFile(file.FullName, outputFile, regexes);
                        }
                    }
                }
            }

            if (packageOutputFile != null)
            {
                // Add package to session
                var loadParams = PackageLoadParameters.Default();
                loadParams.ForceNugetRestore       = true;
                loadParams.GenerateNewAssetIds     = true;
                loadParams.LoadMissingDependencies = false;
                var session       = parameters.Session;
                var loadedPackage = session.AddExistingPackage(packageOutputFile, log, loadParams);

                RemoveUnusedAssets(loadedPackage, session);

                parameters.Tags.Add(GeneratedPackageKey, loadedPackage);
            }
            else
            {
                log.Error("Unable to find generated package for this template");
            }

            // Make sure we transfer overrides, etc. from what we deserialized to the asset graphs that we are going to save right after.
            ApplyMetadata(parameters);
            return(true);
        }
Ejemplo n.º 12
0
        protected override bool Generate(SessionTemplateGeneratorParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }
            parameters.Validate();

            var description = (TemplateSampleDescription)parameters.Description;
            var log         = parameters.Logger;

            // The package might depend on other packages which need to be copied together when instanciating it.
            //  However some of these packages might be in a parent folder, which can result in undesired behavior when copied.
            //  Setting this to true will enforce all package dependencies to be moved to a folder local to the project
            bool doMoveParentDependencies = true;

            var regexes     = new List <Tuple <Regex, MatchEvaluator> >();
            var patternName = description.PatternName ?? description.DefaultOutputName;

            // Samples don't support spaces and dot in name (we would need to separate package name, package short name and namespace renaming for that).
            var parametersName = parameters.Name.Replace(" ", string.Empty).Replace(".", string.Empty);

            if (patternName != parametersName)
            {
                // Make sure the target name is a safe for use everywhere, since both an asset or script might reference a filename
                //  in which case they should match and be valid in that context
                string validNamespaceName = Utilities.BuildValidNamespaceName(parametersName);

                // Rename for general occurences of template name
                regexes.Add(new Tuple <Regex, MatchEvaluator>(new Regex($@"\b{patternName}\b"), match => validNamespaceName));

                // Rename App as well (used in code) -- this is the only pattern of "package short name" that we have so far in Windows samples
                regexes.Add(new Tuple <Regex, MatchEvaluator>(new Regex($@"\b{patternName}App\b"), match => validNamespaceName));
            }

            var outputDirectory = parameters.OutputDirectory;

            if (!Directory.Exists(outputDirectory))
            {
                Directory.CreateDirectory(outputDirectory);
            }

            //write gitignore
            WriteGitIgnore(parameters);

            UFile projectOutputFile = null;
            UFile projectInputFile  = null;

            // Process files
            foreach (var directory in FileUtility.EnumerateDirectories(description.TemplateDirectory, SearchDirection.Down))
            {
                foreach (var file in directory.GetFiles())
                {
                    // If the file is ending with the Template extension or a directory with the sample extension, don;t copy it
                    if (file.FullName.EndsWith(TemplateDescription.FileExtension) ||
                        string.Compare(directory.Name, TemplateDescription.FileExtension, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        continue;
                    }

                    var relativeFile = new UFile(file.FullName).MakeRelative(description.TemplateDirectory);

                    // Replace the name in the files if necessary
                    foreach (var nameRegex in regexes)
                    {
                        relativeFile = nameRegex.Item1.Replace(relativeFile, nameRegex.Item2);
                    }

                    // Create the output directory if needed
                    var outputFile          = UPath.Combine(outputDirectory, relativeFile);
                    var outputFileDirectory = outputFile.GetParent();

                    // Determine if we are processing the main game project
                    var isPackageFile = (projectOutputFile == null && Path.GetExtension(file.FullName).ToLowerInvariant() == ".csproj" && !Path.GetFileNameWithoutExtension(file.FullName).EndsWith(".Windows"));

                    if (isPackageFile)
                    {
                        projectInputFile  = file.FullName;
                        projectOutputFile = outputFile;
                    }

                    if (!Directory.Exists(outputFileDirectory))
                    {
                        Directory.CreateDirectory(outputFileDirectory);
                    }

                    if (IsBinaryFile(file.FullName))
                    {
                        File.Copy(file.FullName, outputFile, true);
                    }
                    else
                    {
                        ProcessTextFile(file.FullName, outputFile, regexes, (isPackageFile && doMoveParentDependencies));
                    }
                }
            }

            if (projectOutputFile != null)
            {
                var inputProject   = (SolutionProject)Package.LoadProject(log, projectInputFile);
                var outputProject  = (SolutionProject)Package.LoadProject(log, projectOutputFile);
                var msbuildProject = VSProjectHelper.LoadProject(outputProject.FullPath, platform: "NoPlatform");

                // If requested, add reference to Xenko.Games.Testing
                if (parameters.TryGetTag(AddGamesTestingKey))
                {
                    var items = msbuildProject.AddItem("PackageReference", "Xenko.Games.Testing", new[] { new KeyValuePair <string, string>("Version", XenkoVersion.NuGetVersion), new KeyValuePair <string, string>("PrivateAssets", "contentfiles;analyzers") });
                    foreach (var item in items)
                    {
                        foreach (var metadata in item.Metadata)
                        {
                            metadata.Xml.ExpressedAsAttribute = true;
                        }
                    }
                }

                // Copy dependency files locally
                //  We only want to copy the asset files. The raw files are in Resources and the game assets are in Assets.
                //  If we copy each file locally they will be included in the package and we can then delete the dependency packages.
                foreach (var projectReference in msbuildProject.GetItems("ProjectReference").ToList())
                {
                    var packageDirectory = UPath.Combine(inputProject.FullPath.GetFullDirectory(), (UFile)projectReference.EvaluatedInclude).GetFullDirectory();
                    foreach (var directory in FileUtility.EnumerateDirectories(packageDirectory, SearchDirection.Down))
                    {
                        foreach (var file in directory.GetFiles())
                        {
                            // If the file is ending with the Template extension or a directory with the sample extension, don`t copy it
                            if (file.FullName.EndsWith(TemplateDescription.FileExtension) ||
                                string.Compare(directory.Name, TemplateDescription.FileExtension, StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                continue;
                            }

                            var relativeFile     = new UFile(file.FullName).MakeRelative(packageDirectory);
                            var relativeFilename = relativeFile.ToString();

                            bool isAsset    = relativeFilename.Contains("Assets");
                            bool isResource = relativeFilename.Contains("Resources");

                            if (!isAsset && !isResource)
                            {
                                continue;
                            }

                            // Replace the name in the files if necessary
                            foreach (var nameRegex in regexes)
                            {
                                relativeFile = nameRegex.Item1.Replace(relativeFile, nameRegex.Item2);
                            }

                            var outputFile = UPath.Combine(outputDirectory, relativeFile);
                            {   // Create the output directory if needed
                                var outputFileDirectory = outputFile.GetParent();
                                if (!Directory.Exists(outputFileDirectory))
                                {
                                    Directory.CreateDirectory(outputFileDirectory);
                                }
                            }

                            if (IsBinaryFile(file.FullName))
                            {
                                File.Copy(file.FullName, outputFile, true);
                            }
                            else
                            {
                                ProcessTextFile(file.FullName, outputFile, regexes);
                            }
                        }
                    }

                    msbuildProject.RemoveItem(projectReference);
                }

                // Save csproj without ProjectReferences
                msbuildProject.Save();
                msbuildProject.ProjectCollection.UnloadAllProjects();
                msbuildProject.ProjectCollection.Dispose();

                // Add package to session
                var loadParams = PackageLoadParameters.Default();
                loadParams.GenerateNewAssetIds     = true;
                loadParams.LoadMissingDependencies = false;
                var session = parameters.Session;
                // We should switch to loading .csproj once all samples are upgraded
                var loadedProject = session.AddExistingProject(projectOutputFile, log, loadParams);

                RemoveUnusedAssets(loadedProject.Package, session);

                parameters.Tags.Add(GeneratedPackageKey, loadedProject.Package);
            }
            else
            {
                log.Error("Unable to find generated package for this template");
            }

            // Make sure we transfer overrides, etc. from what we deserialized to the asset graphs that we are going to save right after.
            ApplyMetadata(parameters);
            return(true);
        }
Ejemplo n.º 13
0
        private BuildResultCode BuildMaster()
        {
            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;
                builderOptions.Logger.Error(message);
                return(BuildResultCode.BuildError);
            }

            AssetCompilerContext context        = null;
            PackageSession       projectSession = null;

            try
            {
                var sessionLoadParameters = new PackageLoadParameters
                {
                    AutoCompileProjects     = !builderOptions.DisableAutoCompileProjects,
                    ExtraCompileProperties  = builderOptions.ExtraCompileProperties,
                    RemoveUnloadableObjects = true,
                    BuildConfiguration      = builderOptions.ProjectConfiguration,
                };

                // Loads the root Package
                var projectSessionResult = PackageSession.Load(builderOptions.PackageFile, sessionLoadParameters);
                projectSessionResult.CopyTo(builderOptions.Logger);
                if (projectSessionResult.HasErrors)
                {
                    return(BuildResultCode.BuildError);
                }

                projectSession = projectSessionResult.Session;

                // Check build configuration
                var package = projectSession.LocalPackages.Last();

                // Setup variables
                var buildDirectory  = builderOptions.BuildDirectory;
                var outputDirectory = builderOptions.OutputDirectory;

                // Process game settings asset
                var gameSettingsAsset = package.GetGameSettingsAsset();
                if (gameSettingsAsset == null)
                {
                    builderOptions.Logger.Warning($"Could not find game settings asset at location [{GameSettingsAsset.GameSettingsLocation}]. Use a Default One");
                    gameSettingsAsset = GameSettingsFactory.Create();
                }

                // Create context
                context = new AssetCompilerContext
                {
                    Platform           = builderOptions.Platform,
                    CompilationContext = typeof(AssetCompilationContext),
                    BuildConfiguration = builderOptions.ProjectConfiguration
                };

                // Command line properties
                foreach (var property in builderOptions.Properties)
                {
                    context.OptionProperties.Add(property.Key, property.Value);
                }

                // Set current game settings
                context.SetGameSettingsAsset(gameSettingsAsset);

                // Builds the project
                var assetBuilder = new PackageCompiler(new RootPackageAssetEnumerator(package));
                assetBuilder.AssetCompiled += RegisterBuildStepProcessedHandler;

                context.Properties.Set(BuildAssetNode.VisitRuntimeTypes, true);
                var assetBuildResult = assetBuilder.Prepare(context);
                assetBuildResult.CopyTo(builderOptions.Logger);
                if (assetBuildResult.HasErrors)
                {
                    return(BuildResultCode.BuildError);
                }

                // Setup the remote process build
                var remoteBuilderHelper = new PackageBuilderRemoteHelper(projectSession.AssemblyContainer, builderOptions);

                // Create the builder
                var indexName = "index." + package.Meta.Name;
                builder = new Builder(builderOptions.Logger, buildDirectory, indexName)
                {
                    ThreadCount = builderOptions.ThreadCount, TryExecuteRemote = remoteBuilderHelper.TryExecuteRemote
                };

                builder.MonitorPipeNames.AddRange(builderOptions.MonitorPipeNames);

                // Add build steps generated by AssetBuilder
                builder.Root.Add(assetBuildResult.BuildSteps);

                // Run builder
                var result = builder.Run(Builder.Mode.Build);
                builder.WriteIndexFile(false);

                // Fill list of bundles
                var bundlePacker = new BundlePacker();
                bundlePacker.Build(builderOptions.Logger, projectSession, indexName, outputDirectory, builder.DisableCompressionIds, context.GetCompilationMode() != CompilationMode.AppStore);

                return(result);
            }
            finally
            {
                builder?.Dispose();
                // Dispose the session (in order to unload assemblies)
                projectSession?.Dispose();
                context?.Dispose();

                // Make sure that MSBuild doesn't hold anything else
                VSProjectHelper.Reset();
            }
        }