Пример #1
0
        private bool WriteCMakeLists()
        {
            string        BuildCommand;
            const string  CMakeSectionEnd  = " )\n\n";
            StringBuilder CMakefileContent = new StringBuilder();

            // Create Engine/Project specific lists
            StringBuilder CMakeEngineSourceFilesList  = new StringBuilder("set(ENGINE_SOURCE_FILES \n");
            StringBuilder CMakeProjectSourceFilesList = new StringBuilder("set(PROJECT_SOURCE_FILES \n");
            StringBuilder CMakeEngineHeaderFilesList  = new StringBuilder("set(ENGINE_HEADER_FILES \n");
            StringBuilder CMakeProjectHeaderFilesList = new StringBuilder("set(PROJECT_HEADER_FILES \n");
            StringBuilder CMakeEngineCSFilesList      = new StringBuilder("set(ENGINE_CSHARP_FILES \n");
            StringBuilder CMakeProjectCSFilesList     = new StringBuilder("set(PROJECT_CSHARP_FILES \n");
            StringBuilder CMakeEngineConfigFilesList  = new StringBuilder("set(ENGINE_CONFIG_FILES \n");
            StringBuilder CMakeProjectConfigFilesList = new StringBuilder("set(PROJECT_CONFIG_FILES \n");
            StringBuilder CMakeEngineShaderFilesList  = new StringBuilder("set(ENGINE_SHADER_FILES \n");
            StringBuilder CMakeProjectShaderFilesList = new StringBuilder("set(PROJECT_SHADER_FILES \n");

            StringBuilder IncludeDirectoriesList      = new StringBuilder("include_directories( \n");
            StringBuilder PreprocessorDefinitionsList = new StringBuilder("add_definitions( \n");

            string UE4RootPath          = Utils.CleanDirectorySeparators(UnrealBuildTool.RootDirectory.FullName, '/');
            string CMakeGameRootPath    = "";
            string GameProjectPath      = "";
            string CMakeGameProjectFile = "";

            string HostArchitecture;

            switch (BuildHostPlatform.Current.Platform)
            {
            case UnrealTargetPlatform.Win64:
            {
                HostArchitecture = "Win64";
                BuildCommand     = "call \"" + UE4RootPath + "/Engine/Build/BatchFiles/Build.bat\"";
                break;
            }

            case UnrealTargetPlatform.Mac:
            {
                HostArchitecture    = "Mac";
                BuildCommand        = "cd \"" + UE4RootPath + "\" && bash \"" + UE4RootPath + "/Engine/Build/BatchFiles/" + HostArchitecture + "/Build.sh\"";
                bIncludeIOSTargets  = true;
                bIncludeTVOSTargets = true;
                break;
            }

            case UnrealTargetPlatform.Linux:
            {
                HostArchitecture = "Linux";
                BuildCommand     = "cd \"" + UE4RootPath + "\" && bash \"" + UE4RootPath + "/Engine/Build/BatchFiles/" + HostArchitecture + "/Build.sh\"";
                break;
            }

            default:
            {
                throw new BuildException("ERROR: CMakefileGenerator does not support this platform");
            }
            }

            if (IsProjectBuild)
            {
                GameProjectPath      = OnlyGameProject.Directory.FullName;
                CMakeGameRootPath    = Utils.CleanDirectorySeparators(OnlyGameProject.Directory.FullName, '/');
                CMakeGameProjectFile = Utils.CleanDirectorySeparators(OnlyGameProject.FullName, '/');
            }

            // Additional CMake file definitions
            string EngineHeadersFilePath  = FileReference.Combine(IntermediateProjectFilesPath, CMakeEngineHeadersFileName).ToString();
            string ProjectHeadersFilePath = FileReference.Combine(IntermediateProjectFilesPath, CMakeProjectHeadersFileName).ToString();
            string EngineSourcesFilePath  = FileReference.Combine(IntermediateProjectFilesPath, CMakeEngineSourcesFileName).ToString();
            string ProjectSourcesFilePath = FileReference.Combine(IntermediateProjectFilesPath, CMakeProjectSourcesFileName).ToString();
            string ProjectFilePath        = FileReference.Combine(IntermediateProjectFilesPath, CMakeProjectSourcesFileName).ToString();
            string IncludeFilePath        = FileReference.Combine(IntermediateProjectFilesPath, CMakeIncludesFileName).ToString();
            string EngineConfigsFilePath  = FileReference.Combine(IntermediateProjectFilesPath, CMakeEngineConfigsFileName).ToString();
            string ProjectConfigsFilePath = FileReference.Combine(IntermediateProjectFilesPath, CMakeProjectConfigsFileName).ToString();
            string EngineCSFilePath       = FileReference.Combine(IntermediateProjectFilesPath, CMakeEngineCSFileName).ToString();
            string ProjectCSFilePath      = FileReference.Combine(IntermediateProjectFilesPath, CMakeProjectCSFileName).ToString();
            string EngineShadersFilePath  = FileReference.Combine(IntermediateProjectFilesPath, CMakeEngineShadersFileName).ToString();
            string ProjectShadersFilePath = FileReference.Combine(IntermediateProjectFilesPath, CMakeProjectShadersFileName).ToString();
            string DefinitionsFilePath    = FileReference.Combine(IntermediateProjectFilesPath, CMakeDefinitionsFileName).ToString();

            CMakefileContent.Append(
                "# Makefile generated by CMakefileGenerator.cs (v1.2)\n" +
                "# *DO NOT EDIT*\n\n" +
                "cmake_minimum_required (VERSION 2.6)\n" +
                "project (UE4)\n\n" +
                "# CMake Flags\n" +
                "set(CMAKE_CXX_STANDARD 14)\n" +                 // Need to keep this updated
                "set(CMAKE_CXX_USE_RESPONSE_FILE_FOR_OBJECTS 1 CACHE BOOL \"\" FORCE)\n" +
                "set(CMAKE_CXX_USE_RESPONSE_FILE_FOR_INCLUDES 1 CACHE BOOL \"\" FORCE)\n\n" +
                "# Standard Includes\n" +
                "include(\"" + IncludeFilePath + "\")\n" +
                "include(\"" + DefinitionsFilePath + "\")\n" +
                "include(\"" + EngineHeadersFilePath + "\")\n" +
                "include(\"" + ProjectHeadersFilePath + "\")\n" +
                "include(\"" + EngineSourcesFilePath + "\")\n" +
                "include(\"" + ProjectSourcesFilePath + "\")\n" +
                "include(\"" + EngineCSFilePath + "\")\n" +
                "include(\"" + ProjectCSFilePath + "\")\n\n"
                );

            List <string> IncludeDirectories      = new List <string>();
            List <string> PreprocessorDefinitions = new List <string>();

            foreach (ProjectFile CurProject in GeneratedProjectFiles)
            {
                foreach (string IncludeSearchPath in CurProject.IntelliSenseIncludeSearchPaths)
                {
                    string IncludeDirectory = GetIncludeDirectory(IncludeSearchPath, Path.GetDirectoryName(CurProject.ProjectFilePath.FullName));
                    if (IncludeDirectory != null && !IncludeDirectories.Contains(IncludeDirectory))
                    {
                        if (IncludeDirectory.Contains(UnrealBuildTool.RootDirectory.FullName))
                        {
                            IncludeDirectories.Add(IncludeDirectory.Replace(UnrealBuildTool.RootDirectory.FullName, UE4RootPath));
                        }
                        else
                        {
                            // If the path isn't rooted, then it is relative to the game root
                            if (!Path.IsPathRooted(IncludeDirectory))
                            {
                                IncludeDirectories.Add(CMakeGameRootPath + "/" + IncludeDirectory);
                            }
                            else
                            {
                                // This is a rooted path like /usr/local/sometool/include
                                IncludeDirectories.Add(IncludeDirectory);
                            }
                        }
                    }
                }

                foreach (string PreProcessorDefinition in CurProject.IntelliSensePreprocessorDefinitions)
                {
                    string Definition          = PreProcessorDefinition;
                    string AlternateDefinition = Definition.Contains("=0") ? Definition.Replace("=0", "=1") : Definition.Replace("=1", "=0");

                    if (Definition.Equals("WITH_EDITORONLY_DATA=0") || Definition.Equals("WITH_DATABASE_SUPPORT=1"))
                    {
                        Definition = AlternateDefinition;
                    }

                    if (!PreprocessorDefinitions.Contains(Definition) &&
                        !PreprocessorDefinitions.Contains(AlternateDefinition) &&
                        !Definition.StartsWith("UE_ENGINE_DIRECTORY") &&
                        !Definition.StartsWith("ORIGINAL_FILE_NAME"))
                    {
                        PreprocessorDefinitions.Add(Definition);
                    }
                }
            }

            // Create SourceFiles, HeaderFiles, and ConfigFiles sections.
            List <FileReference> AllModuleFiles = DiscoverModules(FindGameProjects());

            foreach (FileReference CurModuleFile in AllModuleFiles)
            {
                List <FileReference> FoundFiles = SourceFileSearch.FindModuleSourceFiles(CurModuleFile);
                foreach (FileReference CurSourceFile in FoundFiles)
                {
                    string SourceFileRelativeToRoot = CurSourceFile.MakeRelativeTo(UnrealBuildTool.EngineDirectory);

                    // Exclude files/folders on a per-platform basis.
                    if (!IsPathExcludedOnPlatform(SourceFileRelativeToRoot, BuildHostPlatform.Current.Platform))
                    {
                        if (SourceFileRelativeToRoot.EndsWith(".cpp"))
                        {
                            AppendCleanedPathToList(CMakeEngineSourceFilesList, CMakeProjectSourceFilesList, SourceFileRelativeToRoot, CurSourceFile.FullName, GameProjectPath, UE4RootPath, CMakeGameRootPath);
                        }
                        else if (SourceFileRelativeToRoot.EndsWith(".h"))
                        {
                            AppendCleanedPathToList(CMakeEngineHeaderFilesList, CMakeProjectHeaderFilesList, SourceFileRelativeToRoot, CurSourceFile.FullName, GameProjectPath, UE4RootPath, CMakeGameRootPath);
                        }
                        else if (SourceFileRelativeToRoot.EndsWith(".cs"))
                        {
                            AppendCleanedPathToList(CMakeEngineCSFilesList, CMakeProjectCSFilesList, SourceFileRelativeToRoot, CurSourceFile.FullName, GameProjectPath, UE4RootPath, CMakeGameRootPath);
                        }
                        else if (SourceFileRelativeToRoot.EndsWith(".usf") || SourceFileRelativeToRoot.EndsWith(".ush"))
                        {
                            AppendCleanedPathToList(CMakeEngineShaderFilesList, CMakeProjectShaderFilesList, SourceFileRelativeToRoot, CurSourceFile.FullName, GameProjectPath, UE4RootPath, CMakeGameRootPath);
                        }
                        else if (SourceFileRelativeToRoot.EndsWith(".ini"))
                        {
                            AppendCleanedPathToList(CMakeEngineConfigFilesList, CMakeProjectConfigFilesList, SourceFileRelativeToRoot, CurSourceFile.FullName, GameProjectPath, UE4RootPath, CMakeGameRootPath);
                        }
                    }
                }
            }

            foreach (string IncludeDirectory in IncludeDirectories)
            {
                IncludeDirectoriesList.Append("\t\"" + Utils.CleanDirectorySeparators(IncludeDirectory, '/') + "\"\n");
            }

            foreach (string PreprocessorDefinition in PreprocessorDefinitions)
            {
                PreprocessorDefinitionsList.Append("\t-D" + PreprocessorDefinition + "\n");
            }

            // Add Engine/Shaders files (game are added via modules)
            List <FileReference> EngineShaderFiles = SourceFileSearch.FindFiles(DirectoryReference.Combine(UnrealBuildTool.EngineDirectory, "Shaders"));

            foreach (FileReference CurSourceFile in EngineShaderFiles)
            {
                string SourceFileRelativeToRoot = CurSourceFile.MakeRelativeTo(UnrealBuildTool.EngineDirectory);
                if (SourceFileRelativeToRoot.EndsWith(".usf") || SourceFileRelativeToRoot.EndsWith(".ush"))
                {
                    AppendCleanedPathToList(CMakeEngineShaderFilesList, CMakeProjectShaderFilesList, SourceFileRelativeToRoot, CurSourceFile.FullName, GameProjectPath, UE4RootPath, CMakeGameRootPath);
                }
            }

            // Add Engine/Config ini files (game are added via modules)
            List <FileReference> EngineConfigFiles = SourceFileSearch.FindFiles(DirectoryReference.Combine(UnrealBuildTool.EngineDirectory, "Config"));

            foreach (FileReference CurSourceFile in EngineConfigFiles)
            {
                string SourceFileRelativeToRoot = CurSourceFile.MakeRelativeTo(UnrealBuildTool.EngineDirectory);
                if (SourceFileRelativeToRoot.EndsWith(".ini"))
                {
                    AppendCleanedPathToList(CMakeEngineConfigFilesList, CMakeProjectConfigFilesList, SourceFileRelativeToRoot, CurSourceFile.FullName, GameProjectPath, UE4RootPath, CMakeGameRootPath);
                }
            }

            // Add section end to section strings;
            CMakeEngineSourceFilesList.Append(CMakeSectionEnd);
            CMakeEngineHeaderFilesList.Append(CMakeSectionEnd);
            CMakeEngineCSFilesList.Append(CMakeSectionEnd);
            CMakeEngineConfigFilesList.Append(CMakeSectionEnd);
            CMakeEngineShaderFilesList.Append(CMakeSectionEnd);

            CMakeProjectSourceFilesList.Append(CMakeSectionEnd);
            CMakeProjectHeaderFilesList.Append(CMakeSectionEnd);
            CMakeProjectCSFilesList.Append(CMakeSectionEnd);
            CMakeProjectConfigFilesList.Append(CMakeSectionEnd);
            CMakeProjectShaderFilesList.Append(CMakeSectionEnd);

            IncludeDirectoriesList.Append(CMakeSectionEnd);
            PreprocessorDefinitionsList.Append(CMakeSectionEnd);

            if (bIncludeShaderSource)
            {
                CMakefileContent.Append("# Optional Shader Include\n");
                if (!IsProjectBuild || bIncludeEngineSource)
                {
                    CMakefileContent.Append("include(\"" + EngineShadersFilePath + "\")\n");
                    CMakefileContent.Append("set_source_files_properties(${ENGINE_SHADER_FILES} PROPERTIES HEADER_FILE_ONLY TRUE)\n");
                }
                CMakefileContent.Append("include(\"" + ProjectShadersFilePath + "\")\n");
                CMakefileContent.Append("set_source_files_properties(${PROJECT_SHADER_FILES} PROPERTIES HEADER_FILE_ONLY TRUE)\n");
                CMakefileContent.Append("source_group(\"Shader Files\" REGULAR_EXPRESSION .*.usf)\n\n");
            }

            if (bIncludeConfigFiles)
            {
                CMakefileContent.Append("# Optional Config Include\n");
                if (!IsProjectBuild || bIncludeEngineSource)
                {
                    CMakefileContent.Append("include(\"" + EngineConfigsFilePath + "\")\n");
                    CMakefileContent.Append("set_source_files_properties(${ENGINE_CONFIG_FILES} PROPERTIES HEADER_FILE_ONLY TRUE)\n");
                }
                CMakefileContent.Append("include(\"" + ProjectConfigsFilePath + "\")\n");
                CMakefileContent.Append("set_source_files_properties(${PROJECT_CONFIG_FILES} PROPERTIES HEADER_FILE_ONLY TRUE)\n");
                CMakefileContent.Append("source_group(\"Config Files\" REGULAR_EXPRESSION .*.ini)\n\n");
            }

            string CMakeProjectCmdArg = "";
            string UBTArguements      = "";

            if (bGeneratingGameProjectFiles)
            {
                UBTArguements += " -game";
            }
            // Should the builder output progress ticks
            if (ProgressWriter.bWriteMarkup)
            {
                UBTArguements += " -progress";
            }

            foreach (ProjectFile Project in GeneratedProjectFiles)
            {
                foreach (ProjectTarget TargetFile in Project.ProjectTargets)
                {
                    if (TargetFile.TargetFilePath == null)
                    {
                        continue;
                    }

                    string TargetName = TargetFile.TargetFilePath.GetFileNameWithoutAnyExtensions();                           // Remove both ".cs" and ".

                    foreach (UnrealTargetConfiguration CurConfiguration in Enum.GetValues(typeof(UnrealTargetConfiguration)))
                    {
                        if (CurConfiguration != UnrealTargetConfiguration.Unknown && CurConfiguration != UnrealTargetConfiguration.Development)
                        {
                            if (UnrealBuildTool.IsValidConfiguration(CurConfiguration) && !IsTargetExcluded(TargetName, BuildHostPlatform.Current.Platform, CurConfiguration))
                            {
                                if (TargetName == GameProjectName || TargetName == (GameProjectName + "Editor"))
                                {
                                    CMakeProjectCmdArg = "\"-project=" + CMakeGameProjectFile + "\"";
                                }

                                string ConfName = Enum.GetName(typeof(UnrealTargetConfiguration), CurConfiguration);
                                CMakefileContent.Append(String.Format("add_custom_target({0}-{3}-{1} {5} {0} {3} {1} {2}{4} VERBATIM)\n", TargetName, ConfName, CMakeProjectCmdArg, HostArchitecture, UBTArguements, BuildCommand));

                                // Add iOS and TVOS targets if valid
                                if (bIncludeIOSTargets && !IsTargetExcluded(TargetName, UnrealTargetPlatform.IOS, CurConfiguration))
                                {
                                    CMakefileContent.Append(String.Format("add_custom_target({0}-{3}-{1} {5} {0} {3} {1} {2}{4} VERBATIM)\n", TargetName, ConfName, CMakeProjectCmdArg, UnrealTargetPlatform.IOS, UBTArguements, BuildCommand));
                                }
                                if (bIncludeTVOSTargets && !IsTargetExcluded(TargetName, UnrealTargetPlatform.TVOS, CurConfiguration))
                                {
                                    CMakefileContent.Append(String.Format("add_custom_target({0}-{3}-{1} {5} {0} {3} {1} {2}{4} VERBATIM)\n", TargetName, ConfName, CMakeProjectCmdArg, UnrealTargetPlatform.TVOS, UBTArguements, BuildCommand));
                                }
                            }
                        }
                    }
                    if (!IsTargetExcluded(TargetName, BuildHostPlatform.Current.Platform, UnrealTargetConfiguration.Development))
                    {
                        if (TargetName == GameProjectName || TargetName == (GameProjectName + "Editor"))
                        {
                            CMakeProjectCmdArg = "\"-project=" + CMakeGameProjectFile + "\"";
                        }

                        CMakefileContent.Append(String.Format("add_custom_target({0} {4} {0} {2} Development {1}{3} VERBATIM)\n\n", TargetName, CMakeProjectCmdArg, HostArchitecture, UBTArguements, BuildCommand));

                        // Add iOS and TVOS targets if valid
                        if (bIncludeIOSTargets && !IsTargetExcluded(TargetName, UnrealTargetPlatform.IOS, UnrealTargetConfiguration.Development))
                        {
                            CMakefileContent.Append(String.Format("add_custom_target({0}-{3} {5} {0} {3} {1} {2}{4} VERBATIM)\n", TargetName, UnrealTargetConfiguration.Development, CMakeProjectCmdArg, UnrealTargetPlatform.IOS, UBTArguements, BuildCommand));
                        }
                        if (bIncludeTVOSTargets && !IsTargetExcluded(TargetName, UnrealTargetPlatform.TVOS, UnrealTargetConfiguration.Development))
                        {
                            CMakefileContent.Append(String.Format("add_custom_target({0}-{3} {5} {0} {3} {1} {2}{4} VERBATIM)\n", TargetName, UnrealTargetConfiguration.Development, CMakeProjectCmdArg, UnrealTargetPlatform.TVOS, UBTArguements, BuildCommand));
                        }
                    }
                }
            }

            // Create Build Template
            if (IsProjectBuild && !bIncludeEngineSource)
            {
                CMakefileContent.AppendLine("add_executable(FakeTarget ${PROJECT_HEADER_FILES} ${PROJECT_SOURCE_FILES} ${PROJECT_CSHARP_FILES} ${PROJECT_SHADER_FILES} ${PROJECT_CONFIG_FILES})");
            }
            else
            {
                CMakefileContent.AppendLine("add_executable(FakeTarget ${ENGINE_HEADER_FILES} ${ENGINE_SOURCE_FILES} ${ENGINE_CSHARP_FILES} ${ENGINE_SHADER_FILES} ${ENGINE_CONFIG_FILES} ${PROJECT_HEADER_FILES} ${PROJECT_SOURCE_FILES} ${PROJECT_CSHARP_FILES} ${PROJECT_SHADER_FILES} ${PROJECT_CONFIG_FILES})");
            }

            string FullFileName = Path.Combine(MasterProjectPath.FullName, ProjectFileName);

            // Write out CMake files
            bool bWriteMakeList       = WriteFileIfChanged(FullFileName, CMakefileContent.ToString());
            bool bWriteEngineHeaders  = WriteFileIfChanged(EngineHeadersFilePath, CMakeEngineHeaderFilesList.ToString());
            bool bWriteProjectHeaders = WriteFileIfChanged(ProjectHeadersFilePath, CMakeProjectHeaderFilesList.ToString());
            bool bWriteEngineSources  = WriteFileIfChanged(EngineSourcesFilePath, CMakeEngineSourceFilesList.ToString());
            bool bWriteProjectSources = WriteFileIfChanged(ProjectSourcesFilePath, CMakeProjectSourceFilesList.ToString());
            bool bWriteIncludes       = WriteFileIfChanged(IncludeFilePath, IncludeDirectoriesList.ToString());
            bool bWriteDefinitions    = WriteFileIfChanged(DefinitionsFilePath, PreprocessorDefinitionsList.ToString());
            bool bWriteEngineConfigs  = WriteFileIfChanged(EngineConfigsFilePath, CMakeEngineConfigFilesList.ToString());
            bool bWriteProjectConfigs = WriteFileIfChanged(ProjectConfigsFilePath, CMakeProjectConfigFilesList.ToString());
            bool bWriteEngineShaders  = WriteFileIfChanged(EngineShadersFilePath, CMakeEngineShaderFilesList.ToString());
            bool bWriteProjectShaders = WriteFileIfChanged(ProjectShadersFilePath, CMakeProjectShaderFilesList.ToString());
            bool bWriteEngineCS       = WriteFileIfChanged(EngineCSFilePath, CMakeEngineCSFilesList.ToString());
            bool bWriteProjectCS      = WriteFileIfChanged(ProjectCSFilePath, CMakeProjectCSFilesList.ToString());

            // Return success flag if all files were written out successfully
            return(bWriteMakeList &&
                   bWriteEngineHeaders && bWriteProjectHeaders &&
                   bWriteEngineSources && bWriteProjectSources &&
                   bWriteEngineConfigs && bWriteProjectConfigs &&
                   bWriteEngineCS && bWriteProjectCS &&
                   bWriteEngineShaders && bWriteProjectShaders &&
                   bWriteIncludes && bWriteDefinitions);
        }
Пример #2
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="InName">Name of the module</param>
        /// <param name="InType">Type of the module, for UHT</param>
        /// <param name="InModuleDirectory">Base directory for the module</param>
        /// <param name="InRules">Rules for this module</param>
        /// <param name="InRulesFile">Path to the rules file</param>
        /// <param name="InRuntimeDependencies">List of runtime dependencies</param>
        public UEBuildModule(string InName, UHTModuleType InType, DirectoryReference InModuleDirectory, ModuleRules InRules, FileReference InRulesFile, List <RuntimeDependency> InRuntimeDependencies)
        {
            Name            = InName;
            Type            = InType;
            ModuleDirectory = InModuleDirectory;
            Rules           = InRules;
            RulesFile       = InRulesFile;

            NormalizedModuleIncludePath = Utils.CleanDirectorySeparators(ModuleDirectory.MakeRelativeTo(UnrealBuildTool.EngineSourceDirectory), '/');
            ModuleApiDefine             = Name.ToUpperInvariant() + "_API";

            PublicDefinitions               = HashSetFromOptionalEnumerableStringParameter(InRules.PublicDefinitions);
            PublicIncludePaths              = HashSetFromOptionalEnumerableStringParameter(InRules.PublicIncludePaths);
            PublicSystemIncludePaths        = HashSetFromOptionalEnumerableStringParameter(InRules.PublicSystemIncludePaths);
            PublicLibraryPaths              = HashSetFromOptionalEnumerableStringParameter(InRules.PublicLibraryPaths);
            PublicAdditionalLibraries       = HashSetFromOptionalEnumerableStringParameter(InRules.PublicAdditionalLibraries);
            PublicFrameworks                = HashSetFromOptionalEnumerableStringParameter(InRules.PublicFrameworks);
            PublicWeakFrameworks            = HashSetFromOptionalEnumerableStringParameter(InRules.PublicWeakFrameworks);
            PublicAdditionalFrameworks      = InRules.PublicAdditionalFrameworks == null ? new HashSet <UEBuildFramework>() : new HashSet <UEBuildFramework>(InRules.PublicAdditionalFrameworks);
            PublicAdditionalShadowFiles     = HashSetFromOptionalEnumerableStringParameter(InRules.PublicAdditionalShadowFiles);
            PublicAdditionalBundleResources = InRules.AdditionalBundleResources == null ? new HashSet <UEBuildBundleResource>() : new HashSet <UEBuildBundleResource>(InRules.AdditionalBundleResources);
            PublicDelayLoadDLLs             = HashSetFromOptionalEnumerableStringParameter(InRules.PublicDelayLoadDLLs);
            PrivateIncludePaths             = HashSetFromOptionalEnumerableStringParameter(InRules.PrivateIncludePaths);
            RuntimeDependencies             = InRuntimeDependencies;
            IsRedistributableOverride       = InRules.IsRedistributableOverride;

            WhitelistRestrictedFolders = new HashSet <DirectoryReference>(InRules.WhitelistRestrictedFolders.Select(x => DirectoryReference.Combine(ModuleDirectory, x)));
        }
Пример #3
0
        /// <summary>
        /// Sets up the standard compile environment for the toolchain
        /// </summary>
        private void SetupEnvironment(UnrealTargetPlatform Platform)
        {
            // Add the standard Visual C++ include paths
            IncludePaths.Add(DirectoryReference.Combine(ToolChainDir, "INCLUDE"));
            string ArchFolder = WindowsExports.GetArchitectureSubpath(Architecture);

            // Add the standard Visual C++ library paths
            if (ToolChain >= WindowsCompiler.VisualStudio2017)
            {
                if (Platform == UnrealTargetPlatform.HoloLens)
                {
                    LibraryPaths.Add(DirectoryReference.Combine(ToolChainDir, "lib", ArchFolder, "store"));
                }
                else
                {
                    LibraryPaths.Add(DirectoryReference.Combine(ToolChainDir, "lib", ArchFolder));
                }
            }
            else
            {
                DirectoryReference LibsPath = DirectoryReference.Combine(ToolChainDir, "LIB");
                if (Platform == UnrealTargetPlatform.HoloLens)
                {
                    LibsPath = DirectoryReference.Combine(LibsPath, "store");
                }

                if (Architecture == WindowsArchitecture.x64)
                {
                    LibsPath = DirectoryReference.Combine(LibsPath, "amd64");
                }
                else if (Architecture == WindowsArchitecture.ARM32)
                {
                    LibsPath = DirectoryReference.Combine(LibsPath, "arm");
                }

                LibraryPaths.Add(LibsPath);
            }

            // If we're on Visual Studio 2015 and using pre-Windows 10 SDK, we need to find a Windows 10 SDK and add the UCRT include paths
            if (ToolChain >= WindowsCompiler.VisualStudio2015_DEPRECATED && WindowsSdkVersion < new VersionNumber(10))
            {
                KeyValuePair <VersionNumber, DirectoryReference> Pair = WindowsPlatform.FindUniversalCrtDirs().OrderByDescending(x => x.Key).FirstOrDefault();
                if (Pair.Key == null || Pair.Key < new VersionNumber(10))
                {
                    throw new BuildException("{0} requires the Universal CRT to be installed.", WindowsPlatform.GetCompilerName(ToolChain));
                }

                DirectoryReference IncludeRootDir = DirectoryReference.Combine(Pair.Value, "include", Pair.Key.ToString());
                IncludePaths.Add(DirectoryReference.Combine(IncludeRootDir, "ucrt"));

                DirectoryReference LibraryRootDir = DirectoryReference.Combine(Pair.Value, "lib", Pair.Key.ToString());
                LibraryPaths.Add(DirectoryReference.Combine(LibraryRootDir, "ucrt", ArchFolder));
            }

            // Add the NETFXSDK include path. We need this for SwarmInterface.
            DirectoryReference NetFxSdkDir;

            if (WindowsPlatform.TryGetNetFxSdkInstallDir(out NetFxSdkDir))
            {
                IncludePaths.Add(DirectoryReference.Combine(NetFxSdkDir, "include", "um"));
                LibraryPaths.Add(DirectoryReference.Combine(NetFxSdkDir, "lib", "um", ArchFolder));
            }
            else
            {
                throw new BuildException("Could not find NetFxSDK install dir; this will prevent SwarmInterface from installing.  Install a version of .NET Framework SDK at 4.6.0 or higher.");
            }

            // Add the Windows SDK paths
            if (WindowsSdkVersion >= new VersionNumber(10))
            {
                DirectoryReference IncludeRootDir = DirectoryReference.Combine(WindowsSdkDir, "include", WindowsSdkVersion.ToString());
                IncludePaths.Add(DirectoryReference.Combine(IncludeRootDir, "ucrt"));
                IncludePaths.Add(DirectoryReference.Combine(IncludeRootDir, "shared"));
                IncludePaths.Add(DirectoryReference.Combine(IncludeRootDir, "um"));
                IncludePaths.Add(DirectoryReference.Combine(IncludeRootDir, "winrt"));

                DirectoryReference LibraryRootDir = DirectoryReference.Combine(WindowsSdkDir, "lib", WindowsSdkVersion.ToString());
                LibraryPaths.Add(DirectoryReference.Combine(LibraryRootDir, "ucrt", ArchFolder));
                LibraryPaths.Add(DirectoryReference.Combine(LibraryRootDir, "um", ArchFolder));
            }
            else
            {
                DirectoryReference IncludeRootDir = DirectoryReference.Combine(WindowsSdkDir, "include");
                IncludePaths.Add(DirectoryReference.Combine(IncludeRootDir, "shared"));
                IncludePaths.Add(DirectoryReference.Combine(IncludeRootDir, "um"));
                IncludePaths.Add(DirectoryReference.Combine(IncludeRootDir, "winrt"));

                DirectoryReference LibraryRootDir = DirectoryReference.Combine(WindowsSdkDir, "lib", "winv6.3");
                LibraryPaths.Add(DirectoryReference.Combine(LibraryRootDir, "um", ArchFolder));
            }
        }
        private LinkEnvironment SetupBinaryLinkEnvironment(ReadOnlyTargetRules Target, UEToolChain ToolChain, LinkEnvironment LinkEnvironment, CppCompileEnvironment CompileEnvironment, List <PrecompiledHeaderTemplate> SharedPCHs, ISourceFileWorkingSet WorkingSet, ActionGraph ActionGraph)
        {
            LinkEnvironment         BinaryLinkEnvironment         = new LinkEnvironment(LinkEnvironment);
            HashSet <UEBuildModule> LinkEnvironmentVisitedModules = new HashSet <UEBuildModule>();
            List <UEBuildBinary>    BinaryDependencies            = new List <UEBuildBinary>();

            CompileEnvironment.bIsBuildingDLL     = IsBuildingDll(Config.Type);
            CompileEnvironment.bIsBuildingLibrary = IsBuildingLibrary(Config.Type);

            CppCompileEnvironment BinaryCompileEnvironment = new CppCompileEnvironment(CompileEnvironment);

            // @todo: This should be in some Windows code somewhere...
            // Set the original file name macro; used in PCLaunch.rc to set the binary metadata fields.
            string OriginalFilename = (Config.OriginalOutputFilePaths != null) ?
                                      Config.OriginalOutputFilePaths[0].GetFileName() :
                                      Config.OutputFilePaths[0].GetFileName();

            BinaryCompileEnvironment.Definitions.Add("ORIGINAL_FILE_NAME=\"" + OriginalFilename + "\"");

            foreach (UEBuildModule Module in Modules)
            {
                List <FileItem> LinkInputFiles;
                if (Module.Binary == null || Module.Binary == this)
                {
                    // Compile each module.
                    Log.TraceVerbose("Compile module: " + Module.Name);
                    LinkInputFiles = Module.Compile(Target, ToolChain, BinaryCompileEnvironment, SharedPCHs, WorkingSet, ActionGraph);

                    // NOTE: Because of 'Shared PCHs', in monolithic builds the same PCH file may appear as a link input
                    // multiple times for a single binary.  We'll check for that here, and only add it once.  This avoids
                    // a linker warning about redundant .obj files.
                    foreach (FileItem LinkInputFile in LinkInputFiles)
                    {
                        if (!BinaryLinkEnvironment.InputFiles.Contains(LinkInputFile))
                        {
                            BinaryLinkEnvironment.InputFiles.Add(LinkInputFile);
                        }
                    }
                }
                else
                {
                    BinaryDependencies.Add(Module.Binary);
                }

                // Allow the module to modify the link environment for the binary.
                Module.SetupPrivateLinkEnvironment(this, BinaryLinkEnvironment, BinaryDependencies, LinkEnvironmentVisitedModules);
            }


            // Allow the binary dependencies to modify the link environment.
            foreach (UEBuildBinary BinaryDependency in BinaryDependencies)
            {
                BinaryDependency.SetupDependentLinkEnvironment(BinaryLinkEnvironment);
            }

            // Remove the default resource file on Windows (PCLaunch.rc) if the user has specified their own
            if (BinaryLinkEnvironment.InputFiles.Select(Item => Path.GetFileName(Item.AbsolutePath).ToLower()).Any(Name => Name.EndsWith(".res") && !Name.EndsWith(".inl.res") && Name != "pclaunch.rc.res"))
            {
                BinaryLinkEnvironment.InputFiles.RemoveAll(x => Path.GetFileName(x.AbsolutePath).ToLower() == "pclaunch.rc.res");
            }

            // Set the link output file.
            BinaryLinkEnvironment.OutputFilePaths = Config.OutputFilePaths.ToList();

            // Set whether the link is allowed to have exports.
            BinaryLinkEnvironment.bHasExports = Config.bAllowExports;

            // Set the output folder for intermediate files
            BinaryLinkEnvironment.IntermediateDirectory = Config.IntermediateDirectory;

            // Put the non-executable output files (PDB, import library, etc) in the same directory as the production
            BinaryLinkEnvironment.OutputDirectory = Config.OutputFilePaths[0].Directory;

            // Setup link output type
            BinaryLinkEnvironment.bIsBuildingDLL     = IsBuildingDll(Config.Type);
            BinaryLinkEnvironment.bIsBuildingLibrary = IsBuildingLibrary(Config.Type);

            BinaryLinkEnvironment.ProjectFile = Target.ProjectFile;

            // If we don't have any resource file, use the default or compile a custom one for this module
            if (BinaryLinkEnvironment.Platform == CppPlatform.Win32 || BinaryLinkEnvironment.Platform == CppPlatform.Win64)
            {
                if (!BinaryLinkEnvironment.InputFiles.Any(x => x.Reference.HasExtension(".res")))
                {
                    if (BinaryLinkEnvironment.DefaultResourceFiles.Count > 0)
                    {
                        // Use the default resource file if possible
                        BinaryLinkEnvironment.InputFiles.AddRange(BinaryLinkEnvironment.DefaultResourceFiles);
                    }
                    else
                    {
                        // Otherwise compile the default resource file per-binary, so that it gets the correct ORIGINAL_FILE_NAME macro.
                        CppCompileEnvironment BinaryResourceCompileEnvironment = new CppCompileEnvironment(BinaryCompileEnvironment);
                        BinaryResourceCompileEnvironment.OutputDirectory = DirectoryReference.Combine(BinaryResourceCompileEnvironment.OutputDirectory, Modules.First().Name);

                        FileItem  DefaultResourceFile   = FileItem.GetItemByFileReference(FileReference.Combine(UnrealBuildTool.EngineSourceDirectory, "Runtime", "Launch", "Resources", "Windows", "PCLaunch.rc"));
                        CPPOutput DefaultResourceOutput = ToolChain.CompileRCFiles(BinaryResourceCompileEnvironment, new List <FileItem> {
                            DefaultResourceFile
                        }, ActionGraph);
                        BinaryLinkEnvironment.InputFiles.AddRange(DefaultResourceOutput.ObjectFiles);
                    }
                }
            }

            // Add all the common resource files
            BinaryLinkEnvironment.InputFiles.AddRange(BinaryLinkEnvironment.CommonResourceFiles);

            return(BinaryLinkEnvironment);
        }
        /// <summary>
        /// Creates a rules assembly
        /// </summary>
        /// <param name="Scope">Scope for items created from this assembly</param>
        /// <param name="RootDirectories">The root directories to create rules for</param>
        /// <param name="AssemblyPrefix">A prefix for the assembly file name</param>
        /// <param name="Plugins">List of plugins to include in this assembly</param>
        /// <param name="bReadOnly">Whether the assembly should be marked as installed</param>
        /// <param name="bSkipCompile">Whether to skip compilation for this assembly</param>
        /// <param name="Parent">The parent rules assembly</param>
        /// <returns>New rules assembly</returns>
        private static RulesAssembly CreateEngineOrEnterpriseRulesAssembly(RulesScope Scope, List <DirectoryReference> RootDirectories, string AssemblyPrefix, IReadOnlyList <PluginInfo> Plugins, bool bReadOnly, bool bSkipCompile, RulesAssembly Parent)
        {
            // Scope hierarchy
            RulesScope PluginsScope  = new RulesScope(Scope.Name + " Plugins", Scope);
            RulesScope ProgramsScope = new RulesScope(Scope.Name + " Programs", PluginsScope);

            // Find the shared modules, excluding the programs directory. These are used to create an assembly with the bContainsEngineModules flag set to true.
            Dictionary <FileReference, ModuleRulesContext> ModuleFileToContext = new Dictionary <FileReference, ModuleRulesContext>();
            ModuleRulesContext DefaultModuleContext = new ModuleRulesContext(Scope, RootDirectories[0]);

            foreach (DirectoryReference RootDirectory in RootDirectories)
            {
                using (Timeline.ScopeEvent("Finding engine modules"))
                {
                    DirectoryReference SourceDirectory = DirectoryReference.Combine(RootDirectory, "Source");

                    AddEngineModuleRulesWithContext(SourceDirectory, "Runtime", DefaultModuleContext, UHTModuleType.EngineRuntime, ModuleFileToContext);
                    AddEngineModuleRulesWithContext(SourceDirectory, "Developer", DefaultModuleContext, UHTModuleType.EngineDeveloper, ModuleFileToContext);
                    AddEngineModuleRulesWithContext(SourceDirectory, "Editor", DefaultModuleContext, UHTModuleType.EngineEditor, ModuleFileToContext);
                    AddEngineModuleRulesWithContext(SourceDirectory, "ThirdParty", DefaultModuleContext, UHTModuleType.EngineThirdParty, ModuleFileToContext);
                }
            }
            // Add all the plugin modules too (don't need to loop over RootDirectories since the plugins come in already found
            using (Timeline.ScopeEvent("Finding plugin modules"))
            {
                ModuleRulesContext PluginsModuleContext = new ModuleRulesContext(PluginsScope, RootDirectories[0]);
                FindModuleRulesForPlugins(Plugins, PluginsModuleContext, ModuleFileToContext);
            }

            // Create the assembly
            FileReference EngineAssemblyFileName = FileReference.Combine(RootDirectories[0], "Intermediate", "Build", "BuildRules", AssemblyPrefix + "Rules" + FrameworkAssemblyExtension);
            RulesAssembly EngineAssembly         = new RulesAssembly(Scope, RootDirectories[0], Plugins, ModuleFileToContext, new List <FileReference>(), EngineAssemblyFileName, bContainsEngineModules: true, DefaultBuildSettings: BuildSettingsVersion.Latest, bReadOnly: bReadOnly, bSkipCompile: bSkipCompile, Parent: Parent);

            List <FileReference> ProgramTargetFiles = new List <FileReference>();
            Dictionary <FileReference, ModuleRulesContext> ProgramModuleFiles = new Dictionary <FileReference, ModuleRulesContext>();

            foreach (DirectoryReference RootDirectory in RootDirectories)
            {
                DirectoryReference SourceDirectory   = DirectoryReference.Combine(RootDirectory, "Source");
                DirectoryReference ProgramsDirectory = DirectoryReference.Combine(SourceDirectory, "Programs");

                // Also create a scope for them, and update the UHT module type
                ModuleRulesContext ProgramsModuleContext = new ModuleRulesContext(ProgramsScope, RootDirectory);
                ProgramsModuleContext.DefaultUHTModuleType = UHTModuleType.Program;

                using (Timeline.ScopeEvent("Finding program modules"))
                {
                    // Find all the rules files
                    AddModuleRulesWithContext(ProgramsDirectory, ProgramsModuleContext, ProgramModuleFiles);
                }

                using (Timeline.ScopeEvent("Finding program targets"))
                {
                    ProgramTargetFiles.AddRange(FindAllRulesFiles(SourceDirectory, RulesFileType.Target));
                }
            }

            // Create a path to the assembly that we'll either load or compile
            FileReference ProgramAssemblyFileName = FileReference.Combine(RootDirectories[0], "Intermediate", "Build", "BuildRules", AssemblyPrefix + "ProgramRules" + FrameworkAssemblyExtension);
            RulesAssembly ProgramAssembly         = new RulesAssembly(ProgramsScope, RootDirectories[0], new List <PluginInfo>().AsReadOnly(), ProgramModuleFiles, ProgramTargetFiles, ProgramAssemblyFileName, bContainsEngineModules: false, DefaultBuildSettings: BuildSettingsVersion.Latest, bReadOnly: bReadOnly, bSkipCompile: bSkipCompile, Parent: EngineAssembly);

            // Return the combined assembly
            return(ProgramAssembly);
        }
Пример #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="DLCFile"></param>
        /// <param name="OutputDirectory"></param>
        public static void CreateManifestForDLC(FileReference DLCFile, DirectoryReference OutputDirectory)
        {
            string IntermediateDirectory = DirectoryReference.Combine(DLCFile.Directory, "Intermediate", "Deploy").FullName;

            new HoloLensManifestGenerator().CreateManifest(UnrealTargetPlatform.HoloLens, WindowsArchitecture.ARM64, OutputDirectory.FullName, IntermediateDirectory, DLCFile, DLCFile.Directory.FullName, new List <UnrealTargetConfiguration>(), new List <string>(), null);
        }
Пример #7
0
        protected IOSProvisioningData(IOSProjectSettings ProjectSettings, bool bIsTVOS, bool bForDistribtion)
        {
            SigningCertificate = ProjectSettings.SigningCertificate;
            string MobileProvision = ProjectSettings.MobileProvision;

            FileReference ProjectFile = ProjectSettings.ProjectFile;

            if (!string.IsNullOrEmpty(SigningCertificate))
            {
                // verify the certificate
                Process IPPProcess = new Process();
                if (BuildHostPlatform.Current.Platform == UnrealTargetPlatform.Mac)
                {
                    string IPPCmd = "\"" + UnrealBuildTool.EngineDirectory + "/Binaries/DotNET/IOS/IPhonePackager.exe\" certificates " + ((ProjectFile != null) ? ("\"" + ProjectFile.ToString() + "\"") : "Engine") + " -bundlename " + ProjectSettings.BundleIdentifier + (bForDistribtion ? " -distribution" : "");
                    IPPProcess.StartInfo.WorkingDirectory = UnrealBuildTool.EngineDirectory.ToString();
                    IPPProcess.StartInfo.FileName         = UnrealBuildTool.EngineDirectory + "/Build/BatchFiles/Mac/RunMono.sh";
                    IPPProcess.StartInfo.Arguments        = IPPCmd;
                    IPPProcess.OutputDataReceived        += new DataReceivedEventHandler(IPPDataReceivedHandler);
                    IPPProcess.ErrorDataReceived         += new DataReceivedEventHandler(IPPDataReceivedHandler);
                }
                else
                {
                    string IPPCmd = "certificates " + ((ProjectFile != null) ? ("\"" + ProjectFile.ToString() + "\"") : "Engine") + " -bundlename " + ProjectSettings.BundleIdentifier + (bForDistribtion ? " -distribution" : "");
                    IPPProcess.StartInfo.WorkingDirectory = UnrealBuildTool.EngineDirectory.ToString();
                    IPPProcess.StartInfo.FileName         = UnrealBuildTool.EngineDirectory + "\\Binaries\\DotNET\\IOS\\IPhonePackager.exe";
                    IPPProcess.StartInfo.Arguments        = IPPCmd;
                    IPPProcess.OutputDataReceived        += new DataReceivedEventHandler(IPPDataReceivedHandler);
                    IPPProcess.ErrorDataReceived         += new DataReceivedEventHandler(IPPDataReceivedHandler);
                }
                Utils.RunLocalProcess(IPPProcess);
            }
            else
            {
                SigningCertificate = bForDistribtion ? "iPhone Distribution" : "iPhone Developer";
                bHaveCertificate   = true;
            }

            if (!string.IsNullOrEmpty(MobileProvision))
            {
                DirectoryReference MobileProvisionDir;
                if (BuildHostPlatform.Current.Platform == UnrealTargetPlatform.Mac)
                {
                    MobileProvisionDir = DirectoryReference.Combine(new DirectoryReference(Environment.GetEnvironmentVariable("HOME")), "Library", "MobileDevice", "Provisioning Profiles");
                }
                else
                {
                    MobileProvisionDir = DirectoryReference.Combine(DirectoryReference.GetSpecialFolder(Environment.SpecialFolder.LocalApplicationData), "Apple Computer", "MobileDevice", "Provisioning Profiles");
                }

                FileReference PossibleMobileProvisionFile = FileReference.Combine(MobileProvisionDir, MobileProvision);
                if (FileReference.Exists(PossibleMobileProvisionFile))
                {
                    MobileProvisionFile = PossibleMobileProvisionFile;
                }
            }

            if (MobileProvisionFile == null || !bHaveCertificate)
            {
                SigningCertificate  = "";
                MobileProvision     = "";
                MobileProvisionFile = null;
                Log.TraceLog("Provision not specified or not found for " + ((ProjectFile != null) ? ProjectFile.GetFileNameWithoutAnyExtensions() : "UE4Game") + ", searching for compatible match...");
                Process IPPProcess = new Process();
                if (BuildHostPlatform.Current.Platform == UnrealTargetPlatform.Mac)
                {
                    string IPPCmd = "\"" + UnrealBuildTool.EngineDirectory + "/Binaries/DotNET/IOS/IPhonePackager.exe\" signing_match " + ((ProjectFile != null) ? ("\"" + ProjectFile.ToString() + "\"") : "Engine") + " -bundlename " + ProjectSettings.BundleIdentifier + (bIsTVOS ? " -tvos" : "") + (bForDistribtion ? " -distribution" : "");
                    IPPProcess.StartInfo.WorkingDirectory = UnrealBuildTool.EngineDirectory.ToString();
                    IPPProcess.StartInfo.FileName         = UnrealBuildTool.EngineDirectory + "/Build/BatchFiles/Mac/RunMono.sh";
                    IPPProcess.StartInfo.Arguments        = IPPCmd;
                    IPPProcess.OutputDataReceived        += new DataReceivedEventHandler(IPPDataReceivedHandler);
                    IPPProcess.ErrorDataReceived         += new DataReceivedEventHandler(IPPDataReceivedHandler);
                }
                else
                {
                    string IPPCmd = "signing_match " + ((ProjectFile != null) ? ("\"" + ProjectFile.ToString() + "\"") : "Engine") + " -bundlename " + ProjectSettings.BundleIdentifier + (bIsTVOS ? " -tvos" : "") + (bForDistribtion ? " -distribution" : "");
                    IPPProcess.StartInfo.WorkingDirectory = UnrealBuildTool.EngineDirectory.ToString();
                    IPPProcess.StartInfo.FileName         = UnrealBuildTool.EngineDirectory + "\\Binaries\\DotNET\\IOS\\IPhonePackager.exe";
                    IPPProcess.StartInfo.Arguments        = IPPCmd;
                    IPPProcess.OutputDataReceived        += new DataReceivedEventHandler(IPPDataReceivedHandler);
                    IPPProcess.ErrorDataReceived         += new DataReceivedEventHandler(IPPDataReceivedHandler);
                }
                Utils.RunLocalProcess(IPPProcess);
                if (MobileProvisionFile != null)
                {
                    Log.TraceLog("Provision found for " + ((ProjectFile != null) ? ProjectFile.GetFileNameWithoutAnyExtensions() : "UE4Game") + ", Provision: " + MobileProvisionFile + " Certificate: " + SigningCertificate);
                }
            }

            // add to the dictionary
            SigningCertificate = SigningCertificate.Replace("\"", "");

            // read the provision to get the UUID
            if (MobileProvisionFile == null)
            {
                Log.TraceLog("No matching provision file was discovered for {0}. Please ensure you have a compatible provision installed.", ProjectFile);
            }
            else if (!FileReference.Exists(MobileProvisionFile))
            {
                Log.TraceLog("Selected mobile provision for {0} ({1}) was not found. Please ensure you have a compatible provision installed.", ProjectFile, MobileProvisionFile);
            }
            else
            {
                byte[] AllBytes = FileReference.ReadAllBytes(MobileProvisionFile);

                uint StartIndex = (uint)AllBytes.Length;
                uint EndIndex   = (uint)AllBytes.Length;

                for (uint i = 0; i + 4 < AllBytes.Length; i++)
                {
                    if (AllBytes[i] == '<' && AllBytes[i + 1] == '?' && AllBytes[i + 2] == 'x' && AllBytes[i + 3] == 'm' && AllBytes[i + 4] == 'l')
                    {
                        StartIndex = i;
                        break;
                    }
                }

                if (StartIndex < AllBytes.Length)
                {
                    for (uint i = StartIndex; i + 7 < AllBytes.Length; i++)
                    {
                        if (AllBytes[i] == '<' && AllBytes[i + 1] == '/' && AllBytes[i + 2] == 'p' && AllBytes[i + 3] == 'l' && AllBytes[i + 4] == 'i' && AllBytes[i + 5] == 's' && AllBytes[i + 6] == 't' && AllBytes[i + 7] == '>')
                        {
                            EndIndex = i + 7;
                            break;
                        }
                    }
                }

                if (StartIndex < AllBytes.Length && EndIndex < AllBytes.Length)
                {
                    byte[] TextBytes = new byte[EndIndex - StartIndex];
                    Buffer.BlockCopy(AllBytes, (int)StartIndex, TextBytes, 0, (int)(EndIndex - StartIndex));

                    string AllText = Encoding.UTF8.GetString(TextBytes);
                    int    idx     = AllText.IndexOf("<key>UUID</key>");
                    if (idx > 0)
                    {
                        idx = AllText.IndexOf("<string>", idx);
                        if (idx > 0)
                        {
                            idx += "<string>".Length;
                            MobileProvisionUUID = AllText.Substring(idx, AllText.IndexOf("</string>", idx) - idx);
                        }
                    }
                    idx = AllText.IndexOf("<key>com.apple.developer.team-identifier</key>");
                    if (idx > 0)
                    {
                        idx = AllText.IndexOf("<string>", idx);
                        if (idx > 0)
                        {
                            idx     += "<string>".Length;
                            TeamUUID = AllText.Substring(idx, AllText.IndexOf("</string>", idx) - idx);
                        }
                    }
                    idx = AllText.IndexOf("<key>application-identifier</key>");
                    if (idx > 0)
                    {
                        idx = AllText.IndexOf("<string>", idx);
                        if (idx > 0)
                        {
                            idx += "<string>".Length;
                            String FullID = AllText.Substring(idx, AllText.IndexOf("</string>", idx) - idx);
                            BundleIdentifier = FullID.Substring(FullID.IndexOf('.') + 1);
                        }
                    }
                    idx = AllText.IndexOf("<key>Name</key>");
                    if (idx > 0)
                    {
                        idx = AllText.IndexOf("<string>", idx);
                        if (idx > 0)
                        {
                            idx += "<string>".Length;
                            MobileProvisionName = AllText.Substring(idx, AllText.IndexOf("</string>", idx) - idx);
                        }
                    }
                }

                if (string.IsNullOrEmpty(MobileProvisionUUID) || string.IsNullOrEmpty(TeamUUID))
                {
                    MobileProvision    = null;
                    SigningCertificate = null;
                    Log.TraceLog("Failed to parse the mobile provisioning profile.");
                }
            }
        }
Пример #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="RulesFileType"></param>
        /// <param name="GameFolders"></param>
        /// <param name="ForeignPlugins"></param>
        /// <param name="AdditionalSearchPaths"></param>
        /// <param name="bIncludeEngine"></param>
        /// <param name="bIncludeEnterprise"></param>
        /// <returns></returns>
        public static List <FileReference> FindAllRulesSourceFiles(RulesFileType RulesFileType, List <DirectoryReference> GameFolders, List <FileReference> ForeignPlugins, List <DirectoryReference> AdditionalSearchPaths, bool bIncludeEngine = true, bool bIncludeEnterprise = true)
        {
            List <DirectoryReference> Folders = new List <DirectoryReference>();

            // Add all engine source (including third party source)
            if (bIncludeEngine)
            {
                Folders.Add(UnrealBuildTool.EngineSourceDirectory);
            }
            if (bIncludeEnterprise)
            {
                Folders.Add(UnrealBuildTool.EnterpriseSourceDirectory);
            }

            // @todo plugin: Disallow modules from including plugin modules as dependency modules? (except when the module is part of that plugin)

            // Get all the root folders for plugins
            List <DirectoryReference> RootFolders = new List <DirectoryReference>();

            if (bIncludeEngine)
            {
                RootFolders.Add(UnrealBuildTool.EngineDirectory);
            }
            if (bIncludeEnterprise)
            {
                RootFolders.Add(UnrealBuildTool.EnterpriseDirectory);
            }
            if (GameFolders != null)
            {
                RootFolders.AddRange(GameFolders);
            }

            // Find all the plugin source directories
            foreach (DirectoryReference RootFolder in RootFolders)
            {
                DirectoryReference PluginsFolder = DirectoryReference.Combine(RootFolder, "Plugins");
                foreach (FileReference PluginFile in Plugins.EnumeratePlugins(PluginsFolder))
                {
                    Folders.Add(DirectoryReference.Combine(PluginFile.Directory, "Source"));
                }
            }

            // Add all the extra plugin folders
            if (ForeignPlugins != null)
            {
                foreach (FileReference ForeignPlugin in ForeignPlugins)
                {
                    Folders.Add(DirectoryReference.Combine(ForeignPlugin.Directory, "Source"));
                }
            }

            // Add in the game folders to search
            if (GameFolders != null)
            {
                foreach (DirectoryReference GameFolder in GameFolders)
                {
                    DirectoryReference GameSourceFolder = DirectoryReference.Combine(GameFolder, "Source");
                    Folders.Add(GameSourceFolder);
                    DirectoryReference GameIntermediateSourceFolder = DirectoryReference.Combine(GameFolder, "Intermediate", "Source");
                    Folders.Add(GameIntermediateSourceFolder);
                }
            }

            // Process the additional search path, if sent in
            if (AdditionalSearchPaths != null)
            {
                foreach (DirectoryReference AdditionalSearchPath in AdditionalSearchPaths)
                {
                    if (AdditionalSearchPath != null)
                    {
                        if (DirectoryReference.Exists(AdditionalSearchPath))
                        {
                            Folders.Add(AdditionalSearchPath);
                        }
                        else
                        {
                            throw new BuildException("Couldn't find AdditionalSearchPath for rules source files '{0}'", AdditionalSearchPath);
                        }
                    }
                }
            }

            // Iterate over all the folders to check
            List <FileReference>    SourceFiles       = new List <FileReference>();
            HashSet <FileReference> UniqueSourceFiles = new HashSet <FileReference>();

            foreach (DirectoryReference Folder in Folders)
            {
                IReadOnlyList <FileReference> SourceFilesForFolder = FindAllRulesFiles(Folder, RulesFileType);
                foreach (FileReference SourceFile in SourceFilesForFolder)
                {
                    if (UniqueSourceFiles.Add(SourceFile))
                    {
                        SourceFiles.Add(SourceFile);
                    }
                }
            }
            return(SourceFiles);
        }
Пример #9
0
        private VCEnvironment(CppPlatform InPlatform, WindowsCompiler InCompiler)
        {
            Platform = InPlatform;
            Compiler = InCompiler;

            // Get the Visual Studio install directory
            WindowsPlatform.TryGetVSInstallDir(Compiler, out VSInstallDir);

            // Get the Visual C++ compiler install directory.
            if (!WindowsPlatform.TryGetVCInstallDir(Compiler, out VCInstallDir))
            {
                throw new BuildException(WindowsPlatform.GetCompilerName(Compiler) + " must be installed in order to build this target.");
            }

            // Figure out the default toolchain directory. VS15 separates this out into separate directories, with platforms as subdirectories under that.
            DirectoryReference VCToolChainDir = null;

            if (Compiler == WindowsCompiler.VisualStudio2017)
            {
                string Version = File.ReadAllText(FileReference.Combine(VCInstallDir, "Auxiliary", "Build", "Microsoft.VCToolsVersion.default.txt").FullName).Trim();
                VCToolChainDir = DirectoryReference.Combine(VCInstallDir, "Tools", "MSVC", Version);
            }

            WindowsSDKDir          = FindWindowsSDKInstallationFolder(Platform, Compiler);
            WindowsSDKLibVersion   = FindWindowsSDKLibVersion(WindowsSDKDir);
            WindowsSDKExtensionDir = FindWindowsSDKExtensionInstallationFolder(Compiler);
            NetFxSDKExtensionDir   = FindNetFxSDKExtensionInstallationFolder(Compiler);
            WindowsSDKExtensionHeaderLibVersion = FindWindowsSDKExtensionLatestVersion(WindowsSDKExtensionDir);
            FindUniversalCRT(Compiler, out UniversalCRTDir, out UniversalCRTVersion);

            VCToolPath32 = GetVCToolPath32(Compiler, VCInstallDir, VCToolChainDir);
            VCToolPath64 = GetVCToolPath64(Compiler, VCInstallDir, VCToolChainDir);

            // Compile using 64 bit tools for 64 bit targets, and 32 for 32.
            DirectoryReference CompilerDir = (Platform == CppPlatform.Win64) ? VCToolPath64 : VCToolPath32;

            // Regardless of the target, if we're linking on a 64 bit machine, we want to use the 64 bit linker (it's faster than the 32 bit linker and can handle large linking jobs)
            DirectoryReference LinkerDir = VCToolPath64;

            CompilerPath         = GetCompilerToolPath(InPlatform, CompilerDir);
            CLExeVersion         = FindCLExeVersion(CompilerPath.FullName);
            LinkerPath           = GetLinkerToolPath(InPlatform, LinkerDir);
            LibraryManagerPath   = GetLibraryLinkerToolPath(InPlatform, LinkerDir);
            ResourceCompilerPath = new FileReference(GetResourceCompilerToolPath(Platform));

            // Make sure the base 32-bit VS tool path is in the PATH, regardless of which configuration we're using. The toolchain may need to reference support DLLs from this directory (eg. mspdb120.dll).
            string PathEnvironmentVariable = Environment.GetEnvironmentVariable("PATH") ?? "";

            if (!PathEnvironmentVariable.Split(';').Any(x => String.Compare(x, VCToolPath32.FullName, true) == 0))
            {
                PathEnvironmentVariable = VCToolPath32.FullName + ";" + PathEnvironmentVariable;
                Environment.SetEnvironmentVariable("PATH", PathEnvironmentVariable);
            }

            // Setup the INCLUDE environment variable
            List <string> IncludePaths = GetVisualCppIncludePaths(Compiler, VCInstallDir, VCToolChainDir, UniversalCRTDir, UniversalCRTVersion, NetFxSDKExtensionDir, WindowsSDKDir, WindowsSDKLibVersion);

            if (InitialIncludePaths != null)
            {
                IncludePaths.Add(InitialIncludePaths);
            }
            Environment.SetEnvironmentVariable("INCLUDE", String.Join(";", IncludePaths));

            // Setup the LIB environment variable
            List <string> LibraryPaths = GetVisualCppLibraryPaths(Compiler, VCInstallDir, VCToolChainDir, UniversalCRTDir, UniversalCRTVersion, NetFxSDKExtensionDir, WindowsSDKDir, WindowsSDKLibVersion, Platform);

            if (InitialLibraryPaths != null)
            {
                LibraryPaths.Add(InitialLibraryPaths);
            }
            Environment.SetEnvironmentVariable("LIB", String.Join(";", LibraryPaths));
        }
Пример #10
0
        /// <summary>
        /// Main entry point
        /// </summary>
        /// <param name="Arguments">Command-line arguments</param>
        /// <returns>One of the values of ECompilationResult</returns>
        public override int Execute(CommandLineArguments Arguments)
        {
            Arguments.ApplyTo(this);

            // Create the build configuration object, and read the settings
            BuildConfiguration BuildConfiguration = new BuildConfiguration();

            XmlConfig.ApplyTo(BuildConfiguration);
            Arguments.ApplyTo(BuildConfiguration);

            // Parse all the targets being built
            List <TargetDescriptor> TargetDescriptors = TargetDescriptor.ParseCommandLine(Arguments, BuildConfiguration.bUsePrecompiled, bSkipRulesCompile);

            if (TargetDescriptors.Count == 0)
            {
                throw new BuildException("No targets specified to clean");
            }

            // Also add implicit descriptors for cleaning UnrealBuildTool
            if (!BuildConfiguration.bDoNotBuildUHT)
            {
                const string UnrealHeaderToolTarget = "UnrealHeaderTool";

                // Get a list of project files to clean UHT for
                List <FileReference> ProjectFiles = new List <FileReference>();
                foreach (TargetDescriptor TargetDesc in TargetDescriptors)
                {
                    if (TargetDesc.Name != UnrealHeaderToolTarget && !RemoteMac.HandlesTargetPlatform(TargetDesc.Platform))
                    {
                        if (ProjectFiles.Count == 0)
                        {
                            ProjectFiles.Add(null);
                        }
                        if (TargetDesc.ProjectFile != null && !ProjectFiles.Contains(TargetDesc.ProjectFile))
                        {
                            ProjectFiles.Add(TargetDesc.ProjectFile);
                        }
                    }
                }

                // Add descriptors for cleaning UHT with all these projects
                if (ProjectFiles.Count > 0)
                {
                    UnrealTargetConfiguration Configuration = BuildConfiguration.bForceDebugUnrealHeaderTool ? UnrealTargetConfiguration.Debug : UnrealTargetConfiguration.Development;
                    string Architecture = UEBuildPlatform.GetBuildPlatform(BuildHostPlatform.Current.Platform).GetDefaultArchitecture(null);
                    foreach (FileReference ProjectFile in ProjectFiles)
                    {
                        TargetDescriptors.Add(new TargetDescriptor(ProjectFile, UnrealHeaderToolTarget, BuildHostPlatform.Current.Platform, Configuration, Architecture, null));
                    }
                }
            }

            // Output the list of targets that we're cleaning
            Log.TraceInformation("Cleaning {0} binaries...", StringUtils.FormatList(TargetDescriptors.Select(x => x.Name).Distinct()));

            // Loop through all the targets, and clean them all
            HashSet <FileReference>      FilesToDelete       = new HashSet <FileReference>();
            HashSet <DirectoryReference> DirectoriesToDelete = new HashSet <DirectoryReference>();

            foreach (TargetDescriptor TargetDescriptor in TargetDescriptors)
            {
                // Create the rules assembly
                RulesAssembly RulesAssembly = RulesCompiler.CreateTargetRulesAssembly(TargetDescriptor.ProjectFile, TargetDescriptor.Name, bSkipRulesCompile, BuildConfiguration.bUsePrecompiled, TargetDescriptor.ForeignPlugin);

                // Create the rules object
                ReadOnlyTargetRules Target = new ReadOnlyTargetRules(RulesAssembly.CreateTargetRules(TargetDescriptor.Name, TargetDescriptor.Platform, TargetDescriptor.Configuration, TargetDescriptor.Architecture, TargetDescriptor.ProjectFile, TargetDescriptor.AdditionalArguments));

                // Find the base folders that can contain binaries
                List <DirectoryReference> BaseDirs = new List <DirectoryReference>();
                BaseDirs.Add(UnrealBuildTool.EngineDirectory);
                BaseDirs.Add(UnrealBuildTool.EnterpriseDirectory);
                foreach (FileReference Plugin in Plugins.EnumeratePlugins(Target.ProjectFile))
                {
                    BaseDirs.Add(Plugin.Directory);
                }
                if (Target.ProjectFile != null)
                {
                    BaseDirs.Add(Target.ProjectFile.Directory);
                }

                // If we're running a precompiled build, remove anything under the engine folder
                BaseDirs.RemoveAll(x => RulesAssembly.IsReadOnly(x));

                // Get all the names which can prefix build products
                List <string> NamePrefixes = new List <string>();
                if (Target.Type != TargetType.Program)
                {
                    NamePrefixes.Add(UEBuildTarget.GetAppNameForTargetType(Target.Type));
                }
                NamePrefixes.Add(Target.Name);

                // Get the suffixes for this configuration
                List <string> NameSuffixes = new List <string>();
                if (Target.Configuration == Target.UndecoratedConfiguration)
                {
                    NameSuffixes.Add("");
                }
                NameSuffixes.Add(String.Format("-{0}-{1}", Target.Platform.ToString(), Target.Configuration.ToString()));
                if (!String.IsNullOrEmpty(Target.Architecture))
                {
                    NameSuffixes.AddRange(NameSuffixes.ToArray().Select(x => x + Target.Architecture));
                }

                // Add all the makefiles and caches to be deleted
                FilesToDelete.Add(TargetMakefile.GetLocation(Target.ProjectFile, Target.Name, Target.Platform, Target.Configuration));
                FilesToDelete.UnionWith(SourceFileMetadataCache.GetFilesToClean(Target.ProjectFile));
                FilesToDelete.UnionWith(ActionHistory.GetFilesToClean(Target.ProjectFile, Target.Name, Target.Platform, Target.Type, Target.Architecture));

                // Add all the intermediate folders to be deleted
                foreach (DirectoryReference BaseDir in BaseDirs)
                {
                    foreach (string NamePrefix in NamePrefixes)
                    {
                        DirectoryReference GeneratedCodeDir = DirectoryReference.Combine(BaseDir, "Intermediate", "Build", Target.Platform.ToString(), NamePrefix, "Inc");
                        if (DirectoryReference.Exists(GeneratedCodeDir))
                        {
                            DirectoriesToDelete.Add(GeneratedCodeDir);
                        }

                        DirectoryReference IntermediateDir = DirectoryReference.Combine(BaseDir, "Intermediate", "Build", Target.Platform.ToString(), NamePrefix, Target.Configuration.ToString());
                        if (DirectoryReference.Exists(IntermediateDir))
                        {
                            DirectoriesToDelete.Add(IntermediateDir);
                        }
                    }
                }

                // List of additional files and directories to clean, specified by the target platform
                List <FileReference>      AdditionalFilesToDelete       = new List <FileReference>();
                List <DirectoryReference> AdditionalDirectoriesToDelete = new List <DirectoryReference>();

                // Add all the build products from this target
                string[] NamePrefixesArray = NamePrefixes.Distinct().ToArray();
                string[] NameSuffixesArray = NameSuffixes.Distinct().ToArray();
                foreach (DirectoryReference BaseDir in BaseDirs)
                {
                    DirectoryReference BinariesDir = DirectoryReference.Combine(BaseDir, "Binaries", Target.Platform.ToString());
                    if (DirectoryReference.Exists(BinariesDir))
                    {
                        UEBuildPlatform.GetBuildPlatform(Target.Platform).FindBuildProductsToClean(BinariesDir, NamePrefixesArray, NameSuffixesArray, AdditionalFilesToDelete, AdditionalDirectoriesToDelete);
                    }
                }

                // Get all the additional intermediate folders created by this platform
                UEBuildPlatform.GetBuildPlatform(Target.Platform).FindAdditionalBuildProductsToClean(Target, AdditionalFilesToDelete, AdditionalDirectoriesToDelete);

                // Add the platform's files and directories to the main list
                FilesToDelete.UnionWith(AdditionalFilesToDelete);
                DirectoriesToDelete.UnionWith(AdditionalDirectoriesToDelete);
            }

            // Delete all the directories, then all the files. By sorting the list of directories before we delete them, we avoid spamming the log if a parent directory is deleted first.
            foreach (DirectoryReference DirectoryToDelete in DirectoriesToDelete.OrderBy(x => x.FullName))
            {
                if (DirectoryReference.Exists(DirectoryToDelete))
                {
                    Log.TraceVerbose("    Deleting {0}{1}...", DirectoryToDelete, Path.DirectorySeparatorChar);
                    try
                    {
                        DirectoryReference.Delete(DirectoryToDelete, true);
                    }
                    catch (Exception Ex)
                    {
                        throw new BuildException(Ex, "Unable to delete {0} ({1})", DirectoryToDelete, Ex.Message.TrimEnd());
                    }
                }
            }

            foreach (FileReference FileToDelete in FilesToDelete.OrderBy(x => x.FullName))
            {
                if (FileReference.Exists(FileToDelete))
                {
                    Log.TraceVerbose("    Deleting " + FileToDelete);
                    try
                    {
                        FileReference.Delete(FileToDelete);
                    }
                    catch (Exception Ex)
                    {
                        throw new BuildException(Ex, "Unable to delete {0} ({1})", FileToDelete, Ex.Message.TrimEnd());
                    }
                }
            }

            // Also clean all the remote targets
            for (int Idx = 0; Idx < TargetDescriptors.Count; Idx++)
            {
                TargetDescriptor TargetDescriptor = TargetDescriptors[Idx];
                if (RemoteMac.HandlesTargetPlatform(TargetDescriptor.Platform))
                {
                    RemoteMac RemoteMac = new RemoteMac(TargetDescriptor.ProjectFile);
                    RemoteMac.Clean(TargetDescriptor);
                }
            }

            return(0);
        }
        private void MakePackage(TargetReceipt Receipt, TargetReceipt NewReceipt, WindowsArchitecture Architecture, List <string> UpdatedFiles)
        {
            string OutputName             = String.Format("{0}_{1}_{2}_{3}", Receipt.TargetName, Receipt.Platform, Receipt.Configuration, WindowsExports.GetArchitectureSubpath(Architecture));
            string IntermediateDirectory  = Path.Combine(Receipt.ProjectDir != null ? Receipt.ProjectDir.FullName : UnrealBuildTool.EngineDirectory.FullName, "Intermediate", "Deploy", WindowsExports.GetArchitectureSubpath(Architecture));
            string OutputDirectory        = Receipt.Launch.Directory.FullName;
            string OutputAppX             = Path.Combine(OutputDirectory, OutputName + ".appx");
            string SigningCertificate     = @"Build\HoloLens\SigningCertificate.pfx";
            string SigningCertificatePath = Path.Combine(Receipt.ProjectDir != null ? Receipt.ProjectDir.FullName : UnrealBuildTool.EngineDirectory.FullName, SigningCertificate);

            string MapFilename = Path.Combine(IntermediateDirectory, OutputName + ".pkgmap");
            var    LocalRoot   = Receipt.ProjectDir;
            var    EngineRoot  = UnrealBuildTool.RootDirectory;
            var    AddedFiles  = new Dictionary <string, string>();
            bool   PackageFileNeedToBeUpdated = !File.Exists(OutputAppX);

            DateTime AppXTime = DateTime.Now;

            PackageFileNeedToBeUpdated = true;

            if (!PackageFileNeedToBeUpdated)
            {
                AppXTime = File.GetLastWriteTimeUtc(OutputAppX);
            }

            {
                foreach (var Product in Receipt.BuildProducts)
                {
                    if (Product.Type == BuildProductType.Executable || Product.Type == BuildProductType.DynamicLibrary || Product.Type == BuildProductType.RequiredResource)
                    {
                        string Filename;
                        if (AddedFiles.ContainsKey(Product.Path.FullName))
                        {
                            continue;
                        }

                        if (LocalRoot != null && Product.Path.IsUnderDirectory(LocalRoot))
                        {
                            Filename = Product.Path.MakeRelativeTo(LocalRoot.ParentDirectory);
                        }
                        else if (Product.Path.IsUnderDirectory(EngineRoot))
                        {
                            Filename = Product.Path.MakeRelativeTo(EngineRoot);
                        }
                        else
                        {
                            throw new BuildException("Failed to parse target receipt file.  See log for details.");
                        }

                        AddedFiles.Add(Product.Path.FullName, Filename);
                    }
                }

                foreach (var Dep in Receipt.RuntimeDependencies)
                {
                    if (Dep.Type == StagedFileType.NonUFS)
                    {
                        if (AddedFiles.ContainsKey(Dep.Path.FullName))
                        {
                            continue;
                        }

                        string Filename;
                        if (LocalRoot != null && Dep.Path.IsUnderDirectory(LocalRoot))
                        {
                            Filename = Dep.Path.MakeRelativeTo(LocalRoot.ParentDirectory);
                        }
                        else if (Dep.Path.IsUnderDirectory(EngineRoot))
                        {
                            Filename = Dep.Path.MakeRelativeTo(EngineRoot);
                        }
                        else
                        {
                            throw new BuildException("Failed to parse target receipt file.  See log for details.");
                        }

                        AddedFiles.Add(Dep.Path.FullName, Filename);
                    }
                }
            }

            string ManifestName = String.Format("AppxManifest_{0}.xml", WindowsExports.GetArchitectureSubpath(Architecture));

            AddedFiles.Add(Path.Combine(OutputDirectory, ManifestName), "AppxManifest.xml");

            //manually add resources
            string PriFileName = String.Format("resources_{0}.pri", WindowsExports.GetArchitectureSubpath(Architecture));

            AddedFiles.Add(Path.Combine(OutputDirectory, PriFileName), "resources.pri");
            {
                DirectoryReference ResourceFolder = DirectoryReference.Combine(Receipt.Launch.Directory, WindowsExports.GetArchitectureSubpath(Architecture));
                foreach (var ResourcePath in UpdatedFiles)
                {
                    var ResourceFile = new FileReference(ResourcePath);

                    if (ResourceFile.IsUnderDirectory(ResourceFolder))
                    {
                        AddedFiles.Add(ResourceFile.FullName, ResourceFile.MakeRelativeTo(ResourceFolder));
                    }
                    else
                    {
                        Log.TraceError("Wrong path to resource \'{0}\', the resource should be in \'{1}\'", ResourceFile.FullName, ResourceFolder.FullName);
                        throw new BuildException("Failed to generate AppX file.  See log for details.");
                    }
                }
            }


            FileReference SourceNetworkManifestPath = new FileReference(Path.Combine(OutputDirectory, "NetworkManifest.xml"));

            if (FileReference.Exists(SourceNetworkManifestPath))
            {
                AddedFiles.Add(SourceNetworkManifestPath.FullName, "NetworkManifest.xml");
            }
            FileReference SourceXboxConfigPath = new FileReference(Path.Combine(OutputDirectory, "xboxservices.config"));

            if (FileReference.Exists(SourceXboxConfigPath))
            {
                AddedFiles.Add(SourceXboxConfigPath.FullName, "xboxservices.config");
            }

            do
            {
                if (PackageFileNeedToBeUpdated)
                {
                    break;
                }

                if (!File.Exists(MapFilename))
                {
                    PackageFileNeedToBeUpdated = true;
                    break;
                }
                string[] lines      = File.ReadAllLines(MapFilename, Encoding.UTF8);
                int      filesCount = 0;

                foreach (var line in lines)
                {
                    if (line[0] == '[')
                    {
                        continue;
                    }

                    string[] files = line.Split('\t');

                    if (files.Length != 2)
                    {
                        PackageFileNeedToBeUpdated = true;
                        break;
                    }

                    files[0] = files[0].Trim('\"');
                    files[1] = files[1].Trim('\"');

                    if (!AddedFiles.ContainsKey(files[0]))
                    {
                        PackageFileNeedToBeUpdated = true;
                        break;
                    }

                    if (AddedFiles[files[0]] != files[1])
                    {
                        PackageFileNeedToBeUpdated = true;
                        break;
                    }

                    if (File.GetLastWriteTimeUtc(files[0]).CompareTo(AppXTime) >= 0)
                    {
                        PackageFileNeedToBeUpdated = true;
                        break;
                    }

                    ++filesCount;
                }

                if (PackageFileNeedToBeUpdated)
                {
                    break;
                }

                if (filesCount != AddedFiles.Count)
                {
                    PackageFileNeedToBeUpdated = true;
                    break;
                }

                if (File.Exists(SigningCertificatePath) && File.GetLastWriteTimeUtc(SigningCertificatePath).CompareTo(AppXTime) >= 0)
                {
                    PackageFileNeedToBeUpdated = true;
                    break;
                }
            }while(false);

            if (!PackageFileNeedToBeUpdated)
            {
                NewReceipt.BuildProducts.Add(new BuildProduct(new FileReference(OutputAppX), BuildProductType.Package));
                return;
            }

            try
            {
                DeployHelper_DeleteFile(OutputAppX);
            }
            catch (Exception exceptionMessage)
            {
                Log.TraceError("Failed to delete {0} from deployment: {1}", OutputAppX, exceptionMessage);
                throw new BuildException("Failed to generate AppX file.  See log for details.");
            }

            var AppXRecipeBuiltFiles = new StringBuilder();

            AppXRecipeBuiltFiles.AppendLine(@"[Files]");
            foreach (var f in AddedFiles)
            {
                AppXRecipeBuiltFiles.AppendLine(String.Format("\"{0}\"\t\"{1}\"", f.Key, f.Value));
            }
            File.WriteAllText(MapFilename, AppXRecipeBuiltFiles.ToString(), Encoding.UTF8);

            NewReceipt.BuildProducts.Add(new BuildProduct(new FileReference(MapFilename), BuildProductType.MapFile));
        }
        /// <summary>
        /// Write project file info in JSON file.
        /// For every combination of <c>UnrealTargetPlatform</c>, <c>UnrealTargetConfiguration</c> and <c>TargetType</c>
        /// will be generated separate JSON file.
        /// Project file will be stored:
        /// For UE4:  {UE4Root}/Engine/Intermediate/ProjectFiles/.Rider/{Platform}/{Configuration}/{TargetType}/{ProjectName}.json
        /// For game: {GameRoot}/Intermediate/ProjectFiles/.Rider/{Platform}/{Configuration}/{TargetType}/{ProjectName}.json
        /// </summary>
        /// <remarks>
        /// * <c>UnrealTargetPlatform.Win32</c> will be always ignored.
        /// * <c>TargetType.Editor</c> will be generated for current platform only and will ignore <c>UnrealTargetConfiguration.Test</c> and <c>UnrealTargetConfiguration.Shipping</c> configurations
        /// * <c>TargetType.Program</c>  will be generated for current platform only and <c>UnrealTargetConfiguration.Development</c> configuration only
        /// </remarks>
        /// <param name="InPlatforms"></param>
        /// <param name="InConfigurations"></param>
        /// <param name="PlatformProjectGenerators"></param>
        /// <param name="Minimize"></param>
        /// <returns></returns>
        public bool WriteProjectFile(List <UnrealTargetPlatform> InPlatforms,
                                     List <UnrealTargetConfiguration> InConfigurations,
                                     PlatformProjectGeneratorCollection PlatformProjectGenerators, JsonWriterStyle Minimize)
        {
            string             ProjectName       = ProjectFilePath.GetFileNameWithoutAnyExtensions();
            DirectoryReference ProjectRootFolder = RootPath;
            List <Tuple <FileReference, UEBuildTarget> > FileToTarget = new List <Tuple <FileReference, UEBuildTarget> >();

            foreach (UnrealTargetPlatform Platform in InPlatforms)
            {
                foreach (UnrealTargetConfiguration Configuration in InConfigurations)
                {
                    foreach (ProjectTarget ProjectTarget in ProjectTargets)
                    {
                        if (TargetTypes.Any() && !TargetTypes.Contains(ProjectTarget.TargetRules.Type))
                        {
                            continue;
                        }

                        // Skip Programs for all configs except for current platform + Development & Debug configurations
                        if (ProjectTarget.TargetRules.Type == TargetType.Program &&
                            (BuildHostPlatform.Current.Platform != Platform ||
                             !(Configuration == UnrealTargetConfiguration.Development || Configuration == UnrealTargetConfiguration.Debug)))
                        {
                            continue;
                        }

                        // Skip Editor for all platforms except for current platform
                        if (ProjectTarget.TargetRules.Type == TargetType.Editor && (BuildHostPlatform.Current.Platform != Platform || (Configuration == UnrealTargetConfiguration.Test || Configuration == UnrealTargetConfiguration.Shipping)))
                        {
                            continue;
                        }

                        DirectoryReference ConfigurationFolder = DirectoryReference.Combine(ProjectRootFolder, Platform.ToString(), Configuration.ToString());

                        DirectoryReference TargetFolder =
                            DirectoryReference.Combine(ConfigurationFolder, ProjectTarget.TargetRules.Type.ToString());

                        string DefaultArchitecture = UEBuildPlatform
                                                     .GetBuildPlatform(Platform)
                                                     .GetDefaultArchitecture(ProjectTarget.UnrealProjectFilePath);
                        TargetDescriptor TargetDesc = new TargetDescriptor(ProjectTarget.UnrealProjectFilePath, ProjectTarget.Name,
                                                                           Platform, Configuration, DefaultArchitecture, Arguments);
                        try
                        {
                            UEBuildTarget BuildTarget = UEBuildTarget.Create(TargetDesc, false, false);

                            FileReference OutputFile = FileReference.Combine(TargetFolder, $"{ProjectName}.json");
                            FileToTarget.Add(Tuple.Create(OutputFile, BuildTarget));
                        }
                        catch (Exception Ex)
                        {
                            Log.TraceWarning("Exception while generating include data for Target:{0}, Platform: {1}, Configuration: {2}", TargetDesc.Name, Platform.ToString(), Configuration.ToString());
                            Log.TraceWarning(Ex.ToString());
                        }
                    }
                }
            }
            foreach (Tuple <FileReference, UEBuildTarget> tuple in FileToTarget)
            {
                CurrentTarget = tuple.Item2;
                CurrentTarget.PreBuildSetup();
                SerializeTarget(tuple.Item1, CurrentTarget, Minimize);
            }

            return(true);
        }
Пример #13
0
        public virtual void SetUpSpecificEnvironment(ReadOnlyTargetRules Target, CppCompileEnvironment CompileEnvironment, LinkEnvironment LinkEnvironment)
        {
            // we want gcc toolchain 4.9, but fall back to 4.8 or 4.6 for now if it doesn't exist
            string NDKPath = Environment.GetEnvironmentVariable("NDKROOT");

            NDKPath = NDKPath.Replace("\"", "");

            AndroidToolChain ToolChain = new AndroidToolChain(Target.ProjectFile, false, Target.AndroidPlatform.Architectures, Target.AndroidPlatform.GPUArchitectures);

            // figure out the NDK version
            string NDKToolchainVersion = ToolChain.NDKToolchainVersion;
            string NDKDefine           = ToolChain.NDKDefine;

            // PLATFORM_ANDROID_NDK_VERSION is in the form 150100, where 15 is major version, 01 is the letter (1 is 'a'), 00 indicates beta revision if letter is 00
            Log.TraceInformation("PLATFORM_ANDROID_NDK_VERSION = {0}", NDKDefine);
            CompileEnvironment.Definitions.Add("PLATFORM_ANDROID_NDK_VERSION=" + NDKDefine);

            string GccVersion    = "4.6";
            int    NDKVersionInt = ToolChain.GetNdkApiLevelInt();

            if (Directory.Exists(Path.Combine(NDKPath, @"sources/cxx-stl/gnu-libstdc++/4.9")))
            {
                GccVersion = "4.9";
            }
            else
            if (Directory.Exists(Path.Combine(NDKPath, @"sources/cxx-stl/gnu-libstdc++/4.8")))
            {
                GccVersion = "4.8";
            }

            Log.TraceInformation("NDK toolchain: {0}, NDK version: {1}, GccVersion: {2}, ClangVersion: {3}", NDKToolchainVersion, NDKVersionInt.ToString(), GccVersion, ToolChain.GetClangVersionString());


            CompileEnvironment.Definitions.Add("PLATFORM_USED_NDK_VERSION_INTEGER=" + NDKVersionInt);


            CompileEnvironment.Definitions.Add("PLATFORM_DESKTOP=0");
            CompileEnvironment.Definitions.Add("PLATFORM_CAN_SUPPORT_EDITORONLY_DATA=0");

            CompileEnvironment.Definitions.Add("WITH_OGGVORBIS=1");

            CompileEnvironment.Definitions.Add("UNICODE");
            CompileEnvironment.Definitions.Add("_UNICODE");

            CompileEnvironment.Definitions.Add("PLATFORM_ANDROID=1");
            CompileEnvironment.Definitions.Add("ANDROID=1");

            CompileEnvironment.Definitions.Add("WITH_EDITOR=0");
            CompileEnvironment.Definitions.Add("USE_NULL_RHI=0");

            DirectoryReference NdkDir = new DirectoryReference(NDKPath);

            CompileEnvironment.SystemIncludePaths.Add(DirectoryReference.Combine(NdkDir, "sources/cxx-stl/gnu-libstdc++/" + GccVersion + "/include"));

            // the toolchain will actually filter these out
            CompileEnvironment.SystemIncludePaths.Add(DirectoryReference.Combine(NdkDir, "sources/cxx-stl/gnu-libstdc++/" + GccVersion + "/libs/armeabi-v7a/include"));
            CompileEnvironment.SystemIncludePaths.Add(DirectoryReference.Combine(NdkDir, "sources/cxx-stl/gnu-libstdc++/" + GccVersion + "/libs/arm64-v8a/include"));
            CompileEnvironment.SystemIncludePaths.Add(DirectoryReference.Combine(NdkDir, "sources/cxx-stl/gnu-libstdc++/" + GccVersion + "/libs/x86/include"));
            CompileEnvironment.SystemIncludePaths.Add(DirectoryReference.Combine(NdkDir, "sources/cxx-stl/gnu-libstdc++/" + GccVersion + "/libs/x86_64/include"));

            LinkEnvironment.LibraryPaths.Add(DirectoryReference.Combine(NdkDir, "sources/cxx-stl/gnu-libstdc++/" + GccVersion + "/libs/armeabi-v7a"));
            LinkEnvironment.LibraryPaths.Add(DirectoryReference.Combine(NdkDir, "sources/cxx-stl/gnu-libstdc++/" + GccVersion + "/libs/arm64-v8a"));
            LinkEnvironment.LibraryPaths.Add(DirectoryReference.Combine(NdkDir, "sources/cxx-stl/gnu-libstdc++/" + GccVersion + "/libs/x86"));
            LinkEnvironment.LibraryPaths.Add(DirectoryReference.Combine(NdkDir, "sources/cxx-stl/gnu-libstdc++/" + GccVersion + "/libs/x86_64"));

            CompileEnvironment.SystemIncludePaths.Add(DirectoryReference.Combine(NdkDir, "sources/android/native_app_glue"));
            CompileEnvironment.SystemIncludePaths.Add(DirectoryReference.Combine(NdkDir, "sources/android/cpufeatures"));

            //@TODO: Tegra Gfx Debugger - standardize locations - for now, change the hardcoded paths and force this to return true to test
            if (UseTegraGraphicsDebugger(Target))
            {
                //LinkEnvironment.LibraryPaths.Add("ThirdParty/NVIDIA/TegraGfxDebugger");
                //LinkEnvironment.LibraryPaths.Add("F:/NVPACK/android-kk-egl-t124-a32/stub");
                //LinkEnvironment.AdditionalLibraries.Add("Nvidia_gfx_debugger_stub");
            }

            if (!UseTegraGraphicsDebugger(Target))
            {
                LinkEnvironment.AdditionalLibraries.Add("GLESv2");
                LinkEnvironment.AdditionalLibraries.Add("EGL");
            }
            LinkEnvironment.AdditionalLibraries.Add("android");
            LinkEnvironment.AdditionalLibraries.Add("OpenSLES");
        }
        /// <summary>
        /// Creates a rules assembly with the given parameters.
        /// </summary>
        /// <param name="ProjectFileName">The project file to create rules for. Null for the engine.</param>
        /// <param name="bUsePrecompiled">Whether to use a precompiled engine</param>
        /// <param name="bSkipCompile">Whether to skip compilation for this assembly</param>
        /// <returns>New rules assembly</returns>
        public static RulesAssembly CreateProjectRulesAssembly(FileReference ProjectFileName, bool bUsePrecompiled, bool bSkipCompile)
        {
            // Check if there's an existing assembly for this project
            RulesAssembly ProjectRulesAssembly;

            if (!LoadedAssemblyMap.TryGetValue(ProjectFileName, out ProjectRulesAssembly))
            {
                ProjectDescriptor Project = ProjectDescriptor.FromFile(ProjectFileName);

                // Create the parent assembly
                RulesAssembly Parent;
                if (Project.IsEnterpriseProject)
                {
                    Parent = CreateEnterpriseRulesAssembly(bUsePrecompiled, bSkipCompile);
                }
                else
                {
                    Parent = CreateEngineRulesAssembly(bUsePrecompiled, bSkipCompile);
                }

                DirectoryReference MainProjectDirectory       = ProjectFileName.Directory;
                DirectoryReference MainProjectSourceDirectory = DirectoryReference.Combine(MainProjectDirectory, "Source");

                // Create a scope for things in this assembly
                RulesScope Scope = new RulesScope("Project", Parent.Scope);

                // Create a new context for modules created by this assembly
                ModuleRulesContext DefaultModuleContext = new ModuleRulesContext(Scope, MainProjectDirectory);
                DefaultModuleContext.bCanBuildDebugGame          = true;
                DefaultModuleContext.bCanHotReload               = true;
                DefaultModuleContext.bClassifyAsGameModuleForUHT = true;
                DefaultModuleContext.bCanUseForSharedPCH         = false;

                // gather modules from project and platforms
                Dictionary <FileReference, ModuleRulesContext> ModuleFiles = new Dictionary <FileReference, ModuleRulesContext>();
                List <FileReference> TargetFiles = new List <FileReference>();

                // Find all the rules/plugins under the project source directories
                foreach (DirectoryReference ProjectDirectory in UnrealBuildTool.GetAllProjectDirectories(ProjectFileName))
                {
                    DirectoryReference ProjectSourceDirectory = DirectoryReference.Combine(ProjectDirectory, "Source");

                    AddModuleRulesWithContext(ProjectSourceDirectory, DefaultModuleContext, ModuleFiles);
                    TargetFiles.AddRange(FindAllRulesFiles(ProjectSourceDirectory, RulesFileType.Target));
                }

                // Find all the project plugins
                List <PluginInfo> ProjectPlugins = new List <PluginInfo>();
                ProjectPlugins.AddRange(Plugins.ReadProjectPlugins(MainProjectDirectory));

                // Add the project's additional plugin directories plugins too
                if (Project.AdditionalPluginDirectories != null)
                {
                    foreach (string AdditionalPluginDirectory in Project.AdditionalPluginDirectories)
                    {
                        ProjectPlugins.AddRange(Plugins.ReadAdditionalPlugins(MainProjectDirectory, AdditionalPluginDirectory));
                    }
                }


                // Find all the plugin module rules
                FindModuleRulesForPlugins(ProjectPlugins, DefaultModuleContext, ModuleFiles);

                // Add the games project's intermediate source folder
                DirectoryReference ProjectIntermediateSourceDirectory = DirectoryReference.Combine(MainProjectDirectory, "Intermediate", "Source");
                if (DirectoryReference.Exists(ProjectIntermediateSourceDirectory))
                {
                    AddModuleRulesWithContext(ProjectIntermediateSourceDirectory, DefaultModuleContext, ModuleFiles);
                    TargetFiles.AddRange(FindAllRulesFiles(ProjectIntermediateSourceDirectory, RulesFileType.Target));
                }

                // Compile the assembly. If there are no module or target files, just use the parent assembly.
                FileReference AssemblyFileName = FileReference.Combine(MainProjectDirectory, "Intermediate", "Build", "BuildRules", ProjectFileName.GetFileNameWithoutExtension() + "ModuleRules" + FrameworkAssemblyExtension);
                if (ModuleFiles.Count == 0 && TargetFiles.Count == 0)
                {
                    ProjectRulesAssembly = Parent;
                }
                else
                {
                    ProjectRulesAssembly = new RulesAssembly(Scope, MainProjectDirectory, ProjectPlugins, ModuleFiles, TargetFiles, AssemblyFileName, bContainsEngineModules: false, DefaultBuildSettings: null, bReadOnly: UnrealBuildTool.IsProjectInstalled(), bSkipCompile: bSkipCompile, Parent: Parent);
                }
                LoadedAssemblyMap.Add(ProjectFileName, ProjectRulesAssembly);
            }
            return(ProjectRulesAssembly);
        }
Пример #15
0
        protected override bool WriteMasterProjectFile(ProjectFile UBTProject)
        {
            var SolutionFileName               = MasterProjectName + SolutionExtension;
            var CodeCompletionFile             = MasterProjectName + CodeCompletionFileName;
            var CodeCompletionPreProcessorFile = MasterProjectName + CodeCompletionPreProcessorFileName;

            var FullCodeLiteMasterFile                     = Path.Combine(MasterProjectPath.FullName, SolutionFileName);
            var FullCodeLiteCodeCompletionFile             = Path.Combine(MasterProjectPath.FullName, CodeCompletionFile);
            var FullCodeLiteCodeCompletionPreProcessorFile = Path.Combine(MasterProjectPath.FullName, CodeCompletionPreProcessorFile);

            //
            // HACK
            // TODO This is for now a hack. According to the original submitter, Eranif (a CodeLite developer) will support code completion folders in *.workspace files.
            // We create a separate file with all the folder name in it to copy manually into the code completion
            // filed of CodeLite workspace. (Workspace Settings/Code Completion -> copy the content of the file threre.)
            List <string> IncludeDirectories = new List <string>();
            List <string> PreProcessor       = new List <string>();

            foreach (var CurProject in GeneratedProjectFiles)
            {
                CodeLiteProject Project = CurProject as CodeLiteProject;
                if (Project == null)
                {
                    continue;
                }

                foreach (var CurrentPath in Project.IntelliSenseIncludeSearchPaths)
                {
                    // Convert relative path into absolute.
                    DirectoryReference IntelliSenseIncludeSearchPath = DirectoryReference.Combine(Project.ProjectFilePath.Directory, CurrentPath);
                    IncludeDirectories.Add(IntelliSenseIncludeSearchPath.FullName);
                }
                foreach (var CurrentPath in Project.IntelliSenseSystemIncludeSearchPaths)
                {
                    // Convert relative path into absolute.
                    DirectoryReference IntelliSenseSystemIncludeSearchPath = DirectoryReference.Combine(Project.ProjectFilePath.Directory, CurrentPath);
                    IncludeDirectories.Add(IntelliSenseSystemIncludeSearchPath.FullName);
                }

                foreach (var CurDef in Project.IntelliSensePreprocessorDefinitions)
                {
                    if (!PreProcessor.Contains(CurDef))
                    {
                        PreProcessor.Add(CurDef);
                    }
                }
            }

            //
            // Write code completions data into files.
            //
            File.WriteAllLines(FullCodeLiteCodeCompletionFile, IncludeDirectories);
            File.WriteAllLines(FullCodeLiteCodeCompletionPreProcessorFile, PreProcessor);

            //
            // Write CodeLites Workspace
            //
            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent = true;

            XElement   CodeLiteWorkspace      = new XElement("CodeLite_Workspace");
            XAttribute CodeLiteWorkspaceName  = new XAttribute("Name", MasterProjectName);
            XAttribute CodeLiteWorkspaceSWTLW = new XAttribute("SWTLW", "Yes");             // This flag will only work in CodeLite version > 8.0. See below

            CodeLiteWorkspace.Add(CodeLiteWorkspaceName);
            CodeLiteWorkspace.Add(CodeLiteWorkspaceSWTLW);

            //
            // ATTN This part will work for the next release of CodeLite. That may
            // be CodeLite version > 8.0. CodeLite 8.0 does not have this functionality.
            // TODO Macros are ignored for now.
            //
            // Write Code Completion folders into the WorkspaceParserPaths section.
            //
            XElement CodeLiteWorkspaceParserPaths = new XElement("WorkspaceParserPaths");

            foreach (var CurrentPath in IncludeDirectories)
            {
                XElement   CodeLiteWorkspaceParserPathInclude = new XElement("Include");
                XAttribute CodeLiteWorkspaceParserPath        = new XAttribute("Path", CurrentPath);
                CodeLiteWorkspaceParserPathInclude.Add(CodeLiteWorkspaceParserPath);
                CodeLiteWorkspaceParserPaths.Add(CodeLiteWorkspaceParserPathInclude);
            }
            CodeLiteWorkspace.Add(CodeLiteWorkspaceParserPaths);

            //
            // Write project file information into CodeLite's workspace file.
            //
            foreach (var CurProject in AllProjectFiles)
            {
                var ProjectExtension = CurProject.ProjectFilePath.GetExtension();

                //
                // TODO For now ignore C# project files.
                //
                if (ProjectExtension == ".csproj")
                {
                    continue;
                }

                //
                // Iterate through all targets.
                //
                foreach (ProjectTarget CurrentTarget in CurProject.ProjectTargets)
                {
                    string[] tmp = CurrentTarget.ToString().Split('.');
                    string   ProjectTargetFileName = CurProject.ProjectFilePath.Directory.MakeRelativeTo(MasterProjectPath) + "/" + tmp[0] + ProjectExtension;
                    String   ProjectName           = tmp[0];


                    XElement   CodeLiteWorkspaceProject       = new XElement("Project");
                    XAttribute CodeLiteWorkspaceProjectName   = new XAttribute("Name", ProjectName);
                    XAttribute CodeLiteWorkspaceProjectPath   = new XAttribute("Path", ProjectTargetFileName);
                    XAttribute CodeLiteWorkspaceProjectActive = new XAttribute("Active", "No");
                    CodeLiteWorkspaceProject.Add(CodeLiteWorkspaceProjectName);
                    CodeLiteWorkspaceProject.Add(CodeLiteWorkspaceProjectPath);
                    CodeLiteWorkspaceProject.Add(CodeLiteWorkspaceProjectActive);
                    CodeLiteWorkspace.Add(CodeLiteWorkspaceProject);
                }
            }

            //
            // We need to create the configuration matrix. That will assign the project configuration to
            // the samge workspace configuration.
            //
            XElement CodeLiteWorkspaceBuildMatrix = new XElement("BuildMatrix");

            foreach (UnrealTargetConfiguration CurConfiguration in SupportedConfigurations)
            {
                if (UnrealBuildTool.IsValidConfiguration(CurConfiguration))
                {
                    XElement   CodeLiteWorkspaceBuildMatrixConfiguration = new XElement("WorkspaceConfiguration");
                    XAttribute CodeLiteWorkspaceProjectName     = new XAttribute("Name", CurConfiguration.ToString());
                    XAttribute CodeLiteWorkspaceProjectSelected = new XAttribute("Selected", "no");
                    CodeLiteWorkspaceBuildMatrixConfiguration.Add(CodeLiteWorkspaceProjectName);
                    CodeLiteWorkspaceBuildMatrixConfiguration.Add(CodeLiteWorkspaceProjectSelected);

                    foreach (var CurProject in AllProjectFiles)
                    {
                        var ProjectExtension = CurProject.ProjectFilePath.GetExtension();

                        //
                        // TODO For now ignore C# project files.
                        //
                        if (ProjectExtension == ".csproj")
                        {
                            continue;
                        }

                        foreach (ProjectTarget target in CurProject.ProjectTargets)
                        {
                            string[] tmp         = target.ToString().Split('.');
                            String   ProjectName = tmp[0];

                            XElement   CodeLiteWorkspaceBuildMatrixConfigurationProject           = new XElement("Project");
                            XAttribute CodeLiteWorkspaceBuildMatrixConfigurationProjectName       = new XAttribute("Name", ProjectName);
                            XAttribute CodeLiteWorkspaceBuildMatrixConfigurationProjectConfigName = new XAttribute("ConfigName", CurConfiguration.ToString());
                            CodeLiteWorkspaceBuildMatrixConfigurationProject.Add(CodeLiteWorkspaceBuildMatrixConfigurationProjectName);
                            CodeLiteWorkspaceBuildMatrixConfigurationProject.Add(CodeLiteWorkspaceBuildMatrixConfigurationProjectConfigName);
                            CodeLiteWorkspaceBuildMatrixConfiguration.Add(CodeLiteWorkspaceBuildMatrixConfigurationProject);
                        }
                    }
                    CodeLiteWorkspaceBuildMatrix.Add(CodeLiteWorkspaceBuildMatrixConfiguration);
                }
            }

            CodeLiteWorkspace.Add(CodeLiteWorkspaceBuildMatrix);
            CodeLiteWorkspace.Save(FullCodeLiteMasterFile);

            return(true);
        }
Пример #16
0
        /// <summary>
        /// Sets the Visual C++ INCLUDE environment variable
        /// </summary>
        static List <string> GetVisualCppIncludePaths(WindowsCompiler Compiler, DirectoryReference VisualCppDir, DirectoryReference VisualCppToolchainDir, string UniversalCRTDir, string UniversalCRTVersion, string NetFXSDKDir, string WindowsSDKDir, string WindowsSDKLibVersion)
        {
            List <string> IncludePaths = new List <string>();

            // Add the standard Visual C++ include paths
            if (Compiler == WindowsCompiler.VisualStudio2017)
            {
                DirectoryReference StdIncludeDir = DirectoryReference.Combine(VisualCppToolchainDir, "INCLUDE");
                if (DirectoryReference.Exists(StdIncludeDir))
                {
                    IncludePaths.Add(StdIncludeDir.FullName);
                }
                DirectoryReference AtlMfcIncludeDir = DirectoryReference.Combine(VisualCppToolchainDir, "ATLMFC", "INCLUDE");
                if (DirectoryReference.Exists(AtlMfcIncludeDir))
                {
                    IncludePaths.Add(AtlMfcIncludeDir.FullName);
                }
            }
            else
            {
                DirectoryReference StdIncludeDir = DirectoryReference.Combine(VisualCppDir, "INCLUDE");
                if (DirectoryReference.Exists(StdIncludeDir))
                {
                    IncludePaths.Add(StdIncludeDir.FullName);
                }
                DirectoryReference AtlMfcIncludeDir = DirectoryReference.Combine(VisualCppDir, "ATLMFC", "INCLUDE");
                if (DirectoryReference.Exists(AtlMfcIncludeDir))
                {
                    IncludePaths.Add(AtlMfcIncludeDir.FullName);
                }
            }

            // Add the universal CRT paths
            if (!String.IsNullOrEmpty(UniversalCRTDir) && !String.IsNullOrEmpty(UniversalCRTVersion))
            {
                IncludePaths.Add(Path.Combine(UniversalCRTDir, "include", UniversalCRTVersion, "ucrt"));
            }

            // Add the NETFXSDK include path
            if (!String.IsNullOrEmpty(NetFXSDKDir))
            {
                IncludePaths.Add(Path.Combine(NetFXSDKDir, "include", "um"));                 // 2015
            }

            // Add the Windows SDK paths
            if (Compiler >= WindowsCompiler.VisualStudio2015 && WindowsPlatform.bUseWindowsSDK10)
            {
                IncludePaths.Add(Path.Combine(WindowsSDKDir, "include", WindowsSDKLibVersion, "shared"));
                IncludePaths.Add(Path.Combine(WindowsSDKDir, "include", WindowsSDKLibVersion, "um"));
                IncludePaths.Add(Path.Combine(WindowsSDKDir, "include", WindowsSDKLibVersion, "winrt"));
            }
            else
            {
                IncludePaths.Add(Path.Combine(WindowsSDKDir, "include", "shared"));
                IncludePaths.Add(Path.Combine(WindowsSDKDir, "include", "um"));
                IncludePaths.Add(Path.Combine(WindowsSDKDir, "include", "winrt"));
            }

            // Add the existing include paths
            string ExistingIncludePaths = Environment.GetEnvironmentVariable("INCLUDE");

            if (ExistingIncludePaths != null)
            {
                IncludePaths.AddRange(ExistingIncludePaths.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
            }

            // Set the environment variable
            return(IncludePaths);
        }
Пример #17
0
        /// <summary>
        /// Discover and fill in the project info
        /// </summary>
        public static void FillProjectInfo()
        {
            DateTime StartTime = DateTime.Now;

            List <DirectoryReference> DirectoriesToSearch = new List <DirectoryReference>();

            // Find all the .uprojectdirs files contained in the root folder and add their entries to the search array
            string EngineSourceDirectory = Path.GetFullPath(Path.Combine(RootDirectory, "Engine", "Source"));

            foreach (FileReference ProjectDirsFile in UnrealBuildTool.RootDirectory.EnumerateFileReferences("*.uprojectdirs", SearchOption.TopDirectoryOnly))
            {
                Log.TraceVerbose("\tFound uprojectdirs file {0}", ProjectDirsFile.FullName);
                foreach (string Line in File.ReadAllLines(ProjectDirsFile.FullName))
                {
                    string TrimLine = Line.Trim();
                    if (!TrimLine.StartsWith(";"))
                    {
                        DirectoryReference BaseProjectDir = DirectoryReference.Combine(UnrealBuildTool.RootDirectory, TrimLine);
                        if (BaseProjectDir.IsUnderDirectory(UnrealBuildTool.RootDirectory))
                        {
                            DirectoriesToSearch.Add(BaseProjectDir);
                        }
                        else
                        {
                            Log.TraceWarning("Project search path '{0}' is not under root directory, ignoring.", TrimLine);
                        }
                    }
                }
            }

            Log.TraceVerbose("\tFound {0} directories to search", DirectoriesToSearch.Count);

            foreach (DirectoryReference DirToSearch in DirectoriesToSearch)
            {
                Log.TraceVerbose("\t\tSearching {0}", DirToSearch.FullName);
                if (DirToSearch.Exists())
                {
                    foreach (DirectoryReference SubDir in DirToSearch.EnumerateDirectoryReferences("*", SearchOption.TopDirectoryOnly))
                    {
                        Log.TraceVerbose("\t\t\tFound subdir {0}", SubDir.FullName);
                        foreach (FileReference UProjFile in SubDir.EnumerateFileReferences("*.uproject", SearchOption.TopDirectoryOnly))
                        {
                            Log.TraceVerbose("\t\t\t\t{0}", UProjFile.FullName);
                            AddProject(UProjFile);
                        }
                    }
                }
                else
                {
                    Log.TraceVerbose("ProjectInfo: Skipping directory {0} from .uprojectdirs file as it doesn't exist.", DirToSearch);
                }
            }

            DateTime StopTime = DateTime.Now;

            if (BuildConfiguration.bPrintPerformanceInfo)
            {
                TimeSpan TotalProjectInfoTime = StopTime - StartTime;
                Log.TraceInformation("FillProjectInfo took {0} milliseconds", TotalProjectInfoTime.Milliseconds);
            }

            if (UnrealBuildTool.CommandLineContains("-dumpprojectinfo"))
            {
                UProjectInfo.DumpProjectInfo();
            }
        }
Пример #18
0
        /// <summary>
        /// Sets the Visual C++ LIB environment variable
        /// </summary>
        static List <string> GetVisualCppLibraryPaths(WindowsCompiler Compiler, DirectoryReference VisualCppDir, DirectoryReference VisualCppToolchainDir, string UniversalCRTDir, string UniversalCRTVersion, string NetFXSDKDir, string WindowsSDKDir, string WindowsSDKLibVersion, CppPlatform Platform)
        {
            List <string> LibraryPaths = new List <string>();

            // Add the standard Visual C++ library paths
            if (Compiler == WindowsCompiler.VisualStudio2017)
            {
                if (Platform == CppPlatform.Win32)
                {
                    DirectoryReference StdLibraryDir = DirectoryReference.Combine(VisualCppToolchainDir, "lib", "x86");
                    if (DirectoryReference.Exists(StdLibraryDir))
                    {
                        LibraryPaths.Add(StdLibraryDir.FullName);
                    }
                }
                else
                {
                    DirectoryReference StdLibraryDir = DirectoryReference.Combine(VisualCppToolchainDir, "lib", "x64");
                    if (DirectoryReference.Exists(StdLibraryDir))
                    {
                        LibraryPaths.Add(StdLibraryDir.FullName);
                    }
                }
            }
            else
            {
                if (Platform == CppPlatform.Win32)
                {
                    DirectoryReference StdLibraryDir = DirectoryReference.Combine(VisualCppDir, "LIB");
                    if (DirectoryReference.Exists(StdLibraryDir))
                    {
                        LibraryPaths.Add(StdLibraryDir.FullName);
                    }
                    DirectoryReference AtlMfcLibraryDir = DirectoryReference.Combine(VisualCppDir, "ATLMFC", "LIB");
                    if (DirectoryReference.Exists(AtlMfcLibraryDir))
                    {
                        LibraryPaths.Add(AtlMfcLibraryDir.FullName);
                    }
                }
                else
                {
                    DirectoryReference StdLibraryDir = DirectoryReference.Combine(VisualCppDir, "LIB", "amd64");
                    if (DirectoryReference.Exists(StdLibraryDir))
                    {
                        LibraryPaths.Add(StdLibraryDir.FullName);
                    }
                    DirectoryReference AtlMfcLibraryDir = DirectoryReference.Combine(VisualCppDir, "ATLMFC", "LIB", "amd64");
                    if (DirectoryReference.Exists(AtlMfcLibraryDir))
                    {
                        LibraryPaths.Add(AtlMfcLibraryDir.FullName);
                    }
                }
            }

            // Add the Universal CRT
            if (!String.IsNullOrEmpty(UniversalCRTDir) && !String.IsNullOrEmpty(UniversalCRTVersion))
            {
                if (Platform == CppPlatform.Win32)
                {
                    LibraryPaths.Add(Path.Combine(UniversalCRTDir, "lib", UniversalCRTVersion, "ucrt", "x86"));
                }
                else
                {
                    LibraryPaths.Add(Path.Combine(UniversalCRTDir, "lib", UniversalCRTVersion, "ucrt", "x64"));
                }
            }

            // Add the NETFXSDK include path
            if (!String.IsNullOrEmpty(NetFXSDKDir))
            {
                if (Platform == CppPlatform.Win32)
                {
                    LibraryPaths.Add(Path.Combine(NetFXSDKDir, "lib", "um", "x86"));
                }
                else
                {
                    LibraryPaths.Add(Path.Combine(NetFXSDKDir, "lib", "um", "x64"));
                }
            }

            // Add the standard Windows SDK paths
            if (Platform == CppPlatform.Win32)
            {
                LibraryPaths.Add(Path.Combine(WindowsSDKDir, "lib", WindowsSDKLibVersion, "um", "x86"));
            }
            else
            {
                LibraryPaths.Add(Path.Combine(WindowsSDKDir, "lib", WindowsSDKLibVersion, "um", "x64"));
            }

            // Add the existing library paths
            string ExistingLibraryPaths = Environment.GetEnvironmentVariable("LIB");

            if (ExistingLibraryPaths != null)
            {
                LibraryPaths.AddRange(ExistingLibraryPaths.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
            }

            return(LibraryPaths);
        }
Пример #19
0
        /// <summary>
        /// Setup the target environment for building
        /// </summary>
        /// <param name="Target">Settings for the target being compiled</param>
        /// <param name="CompileEnvironment">The compile environment for this target</param>
        /// <param name="LinkEnvironment">The link environment for this target</param>
        public override void SetUpEnvironment(ReadOnlyTargetRules Target, CppCompileEnvironment CompileEnvironment, LinkEnvironment LinkEnvironment)
        {
            IOSProjectSettings ProjectSettings = ((IOSPlatform)UEBuildPlatform.GetBuildPlatform(Target.Platform)).ReadProjectSettings(Target.ProjectFile);

            if (!ProjectFileGenerator.bGenerateProjectFiles)
            {
                Log.TraceInformation("Compiling against OS Version {0} [minimum allowed at runtime]", ProjectSettings.RuntimeVersion);
            }

            CompileEnvironment.Definitions.Add("PLATFORM_IOS=1");
            CompileEnvironment.Definitions.Add("PLATFORM_APPLE=1");
            CompileEnvironment.Definitions.Add("GLES_SILENCE_DEPRECATION=1");              // suppress GLES "deprecated" warnings until a proper solution is implemented (see UE-65643)

            CompileEnvironment.Definitions.Add("WITH_TTS=0");
            CompileEnvironment.Definitions.Add("WITH_SPEECH_RECOGNITION=0");
            CompileEnvironment.Definitions.Add("WITH_EDITOR=0");
            CompileEnvironment.Definitions.Add("USE_NULL_RHI=0");

            if (ProjectSettings.bNotificationsEnabled)
            {
                CompileEnvironment.Definitions.Add("NOTIFICATIONS_ENABLED=1");
            }
            else
            {
                CompileEnvironment.Definitions.Add("NOTIFICATIONS_ENABLED=0");
            }
            if (ProjectSettings.bBackgroundFetchEnabled)
            {
                CompileEnvironment.Definitions.Add("BACKGROUNDFETCH_ENABLED=1");
            }
            else
            {
                CompileEnvironment.Definitions.Add("BACKGROUNDFETCH_ENABLED=0");
            }
            if (ProjectSettings.bFileSharingEnabled)
            {
                CompileEnvironment.Definitions.Add("FILESHARING_ENABLED=1");
            }
            else
            {
                CompileEnvironment.Definitions.Add("FILESHARING_ENABLED=0");
            }

            CompileEnvironment.Definitions.Add("UE_DISABLE_FORCE_INLINE=" + (ProjectSettings.bDisableForceInline ? "1" : "0"));

            if (Target.Architecture == "-simulator")
            {
                CompileEnvironment.Definitions.Add("WITH_SIMULATOR=1");
            }
            else
            {
                CompileEnvironment.Definitions.Add("WITH_SIMULATOR=0");
            }

            if (ProjectSettings.bEnableAdvertisingIdentifier)
            {
                CompileEnvironment.Definitions.Add("ENABLE_ADVERTISING_IDENTIFIER=1");
            }

            CompileEnvironment.Definitions.Add("HAS_OPENGL_ES=" + ((Target.IOSPlatform.RuntimeVersion < 12.0) ? "1" : "0"));

            // if the project has an Oodle compression Dll, enable the decompressor on IOS
            if (Target.ProjectFile != null)
            {
                DirectoryReference ProjectDir   = DirectoryReference.GetParentDirectory(Target.ProjectFile);
                string             OodleDllPath = DirectoryReference.Combine(ProjectDir, "Binaries/ThirdParty/Oodle/Mac/libUnrealPakPlugin.dylib").FullName;
                if (File.Exists(OodleDllPath))
                {
                    Log.TraceVerbose("        Registering custom oodle compressor for {0}", UnrealTargetPlatform.IOS.ToString());
                    CompileEnvironment.Definitions.Add("REGISTER_OODLE_CUSTOM_COMPRESSOR=1");
                }
            }

            // convert runtime version into standardized integer
            float TargetFloat = Target.IOSPlatform.RuntimeVersion;
            int   IntPart     = (int)TargetFloat;
            int   FracPart    = (int)((TargetFloat - IntPart) * 10);
            int   TargetNum   = IntPart * 10000 + FracPart * 100;

            CompileEnvironment.Definitions.Add("MINIMUM_UE4_COMPILED_IOS_VERSION=" + TargetNum);

            LinkEnvironment.AdditionalFrameworks.Add(new UEBuildFramework("GameKit"));
            LinkEnvironment.AdditionalFrameworks.Add(new UEBuildFramework("StoreKit"));
            LinkEnvironment.AdditionalFrameworks.Add(new UEBuildFramework("DeviceCheck"));
        }
Пример #20
0
 /// <summary>
 /// Returns the in-tree root for the Linux Toolchain for this host platform.
 /// </summary>
 private static DirectoryReference GetInTreeSDKRoot()
 {
     return(DirectoryReference.Combine(UnrealBuildTool.RootDirectory, "Engine/Extras/ThirdPartyNotUE/SDKs", "Host" + BuildHostPlatform.Current.Platform, TargetPlatformName));
 }
Пример #21
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="Rules">Rules for this module</param>
        public UEBuildModule(ModuleRules Rules)
        {
            this.Rules = Rules;

            ModuleApiDefine    = Name.ToUpperInvariant() + "_API";
            ModuleVTableDefine = Name.ToUpperInvariant() + "_VTABLE";

            PublicDefinitions         = HashSetFromOptionalEnumerableStringParameter(Rules.PublicDefinitions);
            PublicIncludePaths        = CreateDirectoryHashSet(Rules.PublicIncludePaths);
            PublicSystemIncludePaths  = CreateDirectoryHashSet(Rules.PublicSystemIncludePaths);
            PublicLibraryPaths        = CreateDirectoryHashSet(Rules.PublicLibraryPaths);
            PublicAdditionalLibraries = HashSetFromOptionalEnumerableStringParameter(Rules.PublicAdditionalLibraries);
            PublicFrameworks          = HashSetFromOptionalEnumerableStringParameter(Rules.PublicFrameworks);
            PublicWeakFrameworks      = HashSetFromOptionalEnumerableStringParameter(Rules.PublicWeakFrameworks);

            PublicAdditionalFrameworks = new HashSet <UEBuildFramework>();
            if (Rules.PublicAdditionalFrameworks != null)
            {
                foreach (ModuleRules.Framework FrameworkRules in Rules.PublicAdditionalFrameworks)
                {
                    UEBuildFramework Framework;
                    if (String.IsNullOrEmpty(FrameworkRules.ZipPath))
                    {
                        Framework = new UEBuildFramework(FrameworkRules.Name, FrameworkRules.CopyBundledAssets);
                    }
                    else
                    {
                        Framework = new UEBuildFramework(FrameworkRules.Name, FileReference.Combine(ModuleDirectory, FrameworkRules.ZipPath), DirectoryReference.Combine(UnrealBuildTool.EngineDirectory, "Intermediate", "UnzippedFrameworks", Name, Path.GetFileNameWithoutExtension(FrameworkRules.ZipPath)), FrameworkRules.CopyBundledAssets);
                    }
                    PublicAdditionalFrameworks.Add(Framework);
                }
            }

            PublicAdditionalBundleResources = Rules.AdditionalBundleResources == null ? new HashSet <UEBuildBundleResource>() : new HashSet <UEBuildBundleResource>(Rules.AdditionalBundleResources.Select(x => new UEBuildBundleResource(x)));
            PublicDelayLoadDLLs             = HashSetFromOptionalEnumerableStringParameter(Rules.PublicDelayLoadDLLs);
            if (Rules.bUsePrecompiled)
            {
                PrivateIncludePaths = new HashSet <DirectoryReference>();
            }
            else
            {
                PrivateIncludePaths = CreateDirectoryHashSet(Rules.PrivateIncludePaths);
            }
            IsRedistributableOverride = Rules.IsRedistributableOverride;

            WhitelistRestrictedFolders = new HashSet <DirectoryReference>(Rules.WhitelistRestrictedFolders.Select(x => DirectoryReference.Combine(ModuleDirectory, x)));

            // merge the main directory and any others set in the Rules
            List <DirectoryReference> MergedDirectories = new List <DirectoryReference> {
                ModuleDirectory
            };

            DirectoryReference[] ExtraModuleDirectories = Rules.GetModuleDirectoriesForAllSubClasses();
            if (ExtraModuleDirectories != null)
            {
                MergedDirectories.AddRange(ExtraModuleDirectories);
            }

            // cache the results (it will always at least have the ModuleDirectory)
            ModuleDirectories = MergedDirectories.ToArray();
        }
Пример #22
0
        private FileReference GetExecutableFilename(ProjectFile Project, ProjectTarget Target, UnrealTargetPlatform Platform, UnrealTargetConfiguration Configuration)
        {
            TargetRules   TargetRulesObject = Target.TargetRules;
            FileReference TargetFilePath    = Target.TargetFilePath;
            string        TargetName        = TargetFilePath == null?Project.ProjectFilePath.GetFileNameWithoutExtension() : TargetFilePath.GetFileNameWithoutAnyExtensions();

            string UBTPlatformName      = Platform.ToString();
            string UBTConfigurationName = Configuration.ToString();

            string ProjectName = Project.ProjectFilePath.GetFileNameWithoutExtension();

            // Setup output path
            UEBuildPlatform BuildPlatform = UEBuildPlatform.GetBuildPlatform(Platform);

            // Figure out if this is a monolithic build
            bool bShouldCompileMonolithic = BuildPlatform.ShouldCompileMonolithicBinary(Platform);

            if (TargetRulesObject != null)
            {
                bShouldCompileMonolithic |= (Target.CreateRulesDelegate(Platform, Configuration).GetLegacyLinkType(Platform, Configuration) == TargetLinkType.Monolithic);
            }

            TargetType TargetRulesType = Target.TargetRules == null ? TargetType.Program : Target.TargetRules.Type;

            // Get the output directory
            DirectoryReference RootDirectory = UnrealBuildTool.EngineDirectory;

            if (TargetRulesType != TargetType.Program && (bShouldCompileMonolithic || TargetRulesObject.BuildEnvironment == TargetBuildEnvironment.Unique) && !TargetRulesObject.bOutputToEngineBinaries)
            {
                if (OnlyGameProject != null && TargetFilePath.IsUnderDirectory(OnlyGameProject.Directory))
                {
                    RootDirectory = OnlyGameProject.Directory;
                }
                else
                {
                    FileReference ProjectFileName;
                    if (UProjectInfo.TryGetProjectFileName(ProjectName, out ProjectFileName))
                    {
                        RootDirectory = ProjectFileName.Directory;
                    }
                }
            }

            if (TargetRulesType == TargetType.Program && (TargetRulesObject == null || !TargetRulesObject.bOutputToEngineBinaries))
            {
                FileReference ProjectFileName;
                if (UProjectInfo.TryGetProjectForTarget(TargetName, out ProjectFileName))
                {
                    RootDirectory = ProjectFileName.Directory;
                }
            }

            // Get the output directory
            DirectoryReference OutputDirectory = DirectoryReference.Combine(RootDirectory, "Binaries", UBTPlatformName);

            // Get the executable name (minus any platform or config suffixes)
            string BaseExeName = TargetName;

            if (!bShouldCompileMonolithic && TargetRulesType != TargetType.Program)
            {
                // Figure out what the compiled binary will be called so that we can point the IDE to the correct file
                string TargetConfigurationName = TargetRulesType.ToString();
                if (TargetConfigurationName != TargetType.Game.ToString() && TargetConfigurationName != TargetType.Program.ToString())
                {
                    BaseExeName = "UE4" + TargetConfigurationName;
                }
            }

            // Make the output file path
            string ExecutableFilename = FileReference.Combine(OutputDirectory, BaseExeName).ToString();

            if ((Configuration != UnrealTargetConfiguration.DebugGame || bShouldCompileMonolithic))
            {
                ExecutableFilename += "-" + UBTPlatformName + "-" + UBTConfigurationName;
            }
            ExecutableFilename += TargetRulesObject.Architecture;
            ExecutableFilename += BuildPlatform.GetBinaryExtension(UEBuildBinaryType.Executable);

            return(FileReference.MakeFromNormalizedFullPath(ExecutableFilename));
        }
Пример #23
0
        /// <summary>
        /// Sets up the standard compile environment for the toolchain
        /// </summary>
        private void SetupEnvironment(CppPlatform Platform)
        {
            // Add the standard Visual C++ include paths
            IncludePaths.Add(DirectoryReference.Combine(ToolChainDir, "INCLUDE"));

            // Add the standard Visual C++ library paths
            if (ToolChain >= WindowsCompiler.VisualStudio2017)
            {
                if (Platform == CppPlatform.Win32)
                {
                    LibraryPaths.Add(DirectoryReference.Combine(ToolChainDir, "lib", "x86"));
                }
                else
                {
                    LibraryPaths.Add(DirectoryReference.Combine(ToolChainDir, "lib", "x64"));
                }
            }
            else
            {
                if (Platform == CppPlatform.Win32)
                {
                    LibraryPaths.Add(DirectoryReference.Combine(ToolChainDir, "LIB"));
                }
                else
                {
                    LibraryPaths.Add(DirectoryReference.Combine(ToolChainDir, "LIB", "amd64"));
                }
            }

            // If we're on Visual Studio 2015 and using pre-Windows 10 SDK, we need to find a Windows 10 SDK and add the UCRT include paths
            if (ToolChain >= WindowsCompiler.VisualStudio2015_DEPRECATED && WindowsSdkVersion < new VersionNumber(10))
            {
                KeyValuePair <VersionNumber, DirectoryReference> Pair = WindowsPlatform.FindUniversalCrtDirs().OrderByDescending(x => x.Key).FirstOrDefault();
                if (Pair.Key == null || Pair.Key < new VersionNumber(10))
                {
                    throw new BuildException("{0} requires the Universal CRT to be installed.", WindowsPlatform.GetCompilerName(ToolChain));
                }

                DirectoryReference IncludeRootDir = DirectoryReference.Combine(Pair.Value, "include", Pair.Key.ToString());
                IncludePaths.Add(DirectoryReference.Combine(IncludeRootDir, "ucrt"));

                DirectoryReference LibraryRootDir = DirectoryReference.Combine(Pair.Value, "lib", Pair.Key.ToString());
                if (Platform == CppPlatform.Win64)
                {
                    LibraryPaths.Add(DirectoryReference.Combine(LibraryRootDir, "ucrt", "x64"));
                }
                else
                {
                    LibraryPaths.Add(DirectoryReference.Combine(LibraryRootDir, "ucrt", "x86"));
                }
            }

            // Add the NETFXSDK include path. We need this for SwarmInterface.
            DirectoryReference NetFxSdkDir;

            if (WindowsPlatform.TryGetNetFxSdkInstallDir(out NetFxSdkDir))
            {
                IncludePaths.Add(DirectoryReference.Combine(NetFxSdkDir, "include", "um"));
                if (Platform == CppPlatform.Win32)
                {
                    LibraryPaths.Add(DirectoryReference.Combine(NetFxSdkDir, "lib", "um", "x86"));
                }
                else
                {
                    LibraryPaths.Add(DirectoryReference.Combine(NetFxSdkDir, "lib", "um", "x64"));
                }
            }

            // Add the Windows SDK paths
            if (WindowsSdkVersion >= new VersionNumber(10))
            {
                DirectoryReference IncludeRootDir = DirectoryReference.Combine(WindowsSdkDir, "include", WindowsSdkVersion.ToString());
                IncludePaths.Add(DirectoryReference.Combine(IncludeRootDir, "ucrt"));
                IncludePaths.Add(DirectoryReference.Combine(IncludeRootDir, "shared"));
                IncludePaths.Add(DirectoryReference.Combine(IncludeRootDir, "um"));
                IncludePaths.Add(DirectoryReference.Combine(IncludeRootDir, "winrt"));

                DirectoryReference LibraryRootDir = DirectoryReference.Combine(WindowsSdkDir, "lib", WindowsSdkVersion.ToString());
                if (Platform == CppPlatform.Win64)
                {
                    LibraryPaths.Add(DirectoryReference.Combine(LibraryRootDir, "ucrt", "x64"));
                    LibraryPaths.Add(DirectoryReference.Combine(LibraryRootDir, "um", "x64"));
                }
                else
                {
                    LibraryPaths.Add(DirectoryReference.Combine(LibraryRootDir, "ucrt", "x86"));
                    LibraryPaths.Add(DirectoryReference.Combine(LibraryRootDir, "um", "x86"));
                }
            }
            else
            {
                DirectoryReference IncludeRootDir = DirectoryReference.Combine(WindowsSdkDir, "include");
                IncludePaths.Add(DirectoryReference.Combine(IncludeRootDir, "shared"));
                IncludePaths.Add(DirectoryReference.Combine(IncludeRootDir, "um"));
                IncludePaths.Add(DirectoryReference.Combine(IncludeRootDir, "winrt"));

                DirectoryReference LibraryRootDir = DirectoryReference.Combine(WindowsSdkDir, "lib", "winv6.3");
                if (Platform == CppPlatform.Win64)
                {
                    LibraryPaths.Add(DirectoryReference.Combine(LibraryRootDir, "um", "x64"));
                }
                else
                {
                    LibraryPaths.Add(DirectoryReference.Combine(LibraryRootDir, "um", "x86"));
                }
            }
        }
Пример #24
0
        public override CPPOutput CompileCPPFiles(CppCompileEnvironment CompileEnvironment, List <FileItem> InputFiles, DirectoryReference OutputDir, string ModuleName, IActionGraphBuilder Graph)
        {
            // Use a subdirectory for PVS output, to avoid clobbering regular build artifacts
            OutputDir = DirectoryReference.Combine(OutputDir, "PVS");

            // Preprocess the source files with the regular toolchain
            CppCompileEnvironment PreprocessCompileEnvironment = new CppCompileEnvironment(CompileEnvironment);

            PreprocessCompileEnvironment.bPreprocessOnly = true;
            PreprocessCompileEnvironment.bEnableUndefinedIdentifierWarnings = false;             // Not sure why THIRD_PARTY_INCLUDES_START doesn't pick this up; the _Pragma appears in the preprocessed output. Perhaps in preprocess-only mode the compiler doesn't respect these?
            PreprocessCompileEnvironment.Definitions.Add("PVS_STUDIO");

            List <Action> PreprocessActions = new List <Action>();
            CPPOutput     Result            = InnerToolChain.CompileCPPFiles(PreprocessCompileEnvironment, InputFiles, OutputDir, ModuleName, new ActionGraphCapture(Graph, PreprocessActions));

            // Run the source files through PVS-Studio
            foreach (Action PreprocessAction in PreprocessActions)
            {
                if (PreprocessAction.ActionType != ActionType.Compile)
                {
                    continue;
                }

                FileItem SourceFileItem = PreprocessAction.PrerequisiteItems.FirstOrDefault(x => x.HasExtension(".c") || x.HasExtension(".cc") || x.HasExtension(".cpp"));
                if (SourceFileItem == null)
                {
                    Log.TraceWarning("Unable to find source file from command: {0} {1}", PreprocessAction.CommandArguments);
                    continue;
                }

                FileItem PreprocessedFileItem = PreprocessAction.ProducedItems.FirstOrDefault(x => x.HasExtension(".i"));
                if (PreprocessedFileItem == null)
                {
                    Log.TraceWarning("Unable to find preprocessed output file from command: {0} {1}", PreprocessAction.CommandArguments);
                    continue;
                }

                // Disable a few warnings that seem to come from the preprocessor not respecting _Pragma
                PreprocessAction.CommandArguments += " /wd4005";                 // macro redefinition
                PreprocessAction.CommandArguments += " /wd4828";                 // file contains a character starting at offset xxxx that is illegal in the current source character set

                // Write the PVS studio config file
                StringBuilder ConfigFileContents = new StringBuilder();
                foreach (DirectoryReference IncludePath in Target.WindowsPlatform.Environment.IncludePaths)
                {
                    ConfigFileContents.AppendFormat("exclude-path={0}\n", IncludePath.FullName);
                }
                if (ApplicationSettings != null && ApplicationSettings.PathMasks != null)
                {
                    foreach (string PathMask in ApplicationSettings.PathMasks)
                    {
                        if (PathMask.Contains(":") || PathMask.Contains("\\") || PathMask.Contains("/"))
                        {
                            if (Path.IsPathRooted(PathMask) && !PathMask.Contains(":"))
                            {
                                ConfigFileContents.AppendFormat("exclude-path=*{0}*\n", PathMask);
                            }
                            else
                            {
                                ConfigFileContents.AppendFormat("exclude-path={0}\n", PathMask);
                            }
                        }
                    }
                }
                if (Platform == UnrealTargetPlatform.Win64)
                {
                    ConfigFileContents.Append("platform=x64\n");
                }
                else if (Platform == UnrealTargetPlatform.Win32)
                {
                    ConfigFileContents.Append("platform=Win32\n");
                }
                else
                {
                    throw new BuildException("PVS-Studio does not support this platform");
                }
                ConfigFileContents.Append("preprocessor=visualcpp\n");
                ConfigFileContents.Append("language=C++\n");
                ConfigFileContents.Append("skip-cl-exe=yes\n");
                ConfigFileContents.AppendFormat("i-file={0}\n", PreprocessedFileItem.Location.FullName);

                string BaseFileName = PreprocessedFileItem.Location.GetFileNameWithoutExtension();

                FileReference ConfigFileLocation = FileReference.Combine(OutputDir, BaseFileName + ".cfg");
                FileItem      ConfigFileItem     = Graph.CreateIntermediateTextFile(ConfigFileLocation, ConfigFileContents.ToString());

                // Run the analzyer on the preprocessed source file
                FileReference OutputFileLocation = FileReference.Combine(OutputDir, BaseFileName + ".pvslog");
                FileItem      OutputFileItem     = FileItem.GetItemByFileReference(OutputFileLocation);

                Action AnalyzeAction = Graph.CreateAction(ActionType.Compile);
                AnalyzeAction.CommandDescription = "Analyzing";
                AnalyzeAction.StatusDescription  = BaseFileName;
                AnalyzeAction.WorkingDirectory   = UnrealBuildTool.EngineSourceDirectory;
                AnalyzeAction.CommandPath        = AnalyzerFile;
                AnalyzeAction.CommandArguments   = String.Format("--cl-params \"{0}\" --source-file \"{1}\" --output-file \"{2}\" --cfg \"{3}\" --analysis-mode {4}", PreprocessAction.CommandArguments, SourceFileItem.AbsolutePath, OutputFileLocation, ConfigFileItem.AbsolutePath, (uint)Settings.ModeFlags);
                if (LicenseFile != null)
                {
                    AnalyzeAction.CommandArguments += String.Format(" --lic-file \"{0}\"", LicenseFile);
                    AnalyzeAction.PrerequisiteItems.Add(FileItem.GetItemByFileReference(LicenseFile));
                }
                AnalyzeAction.PrerequisiteItems.Add(ConfigFileItem);
                AnalyzeAction.PrerequisiteItems.Add(PreprocessedFileItem);
                AnalyzeAction.PrerequisiteItems.AddRange(InputFiles);          // Add the InputFiles as PrerequisiteItems so that in SingleFileCompile mode the PVSAnalyze step is not filtered out
                AnalyzeAction.ProducedItems.Add(OutputFileItem);
                AnalyzeAction.DeleteItems.Add(OutputFileItem);                 // PVS Studio will append by default, so need to delete produced items

                Result.ObjectFiles.AddRange(AnalyzeAction.ProducedItems);
            }
            return(Result);
        }