public static string[] Compile(string[] sources, string[] references, string[] defines, string outputFile, bool allowUnsafeCode)
        {
            var assembly = new ScriptAssembly
            {
                BuildTarget              = BuildTarget.StandaloneWindows,
                Files                    = sources,
                References               = references,
                Defines                  = defines,
                OutputDirectory          = AssetPath.GetDirectoryName(outputFile),
                Filename                 = AssetPath.GetFileName(outputFile),
                CompilerOptions          = new Compilation.ScriptCompilerOptions(),
                ScriptAssemblyReferences = new ScriptAssembly[0]
            };

            assembly.CompilerOptions.AllowUnsafeCode       = allowUnsafeCode;
            assembly.CompilerOptions.ApiCompatibilityLevel = ApiCompatibilityLevel.NET_Standard_2_0;

            using (var c = new MicrosoftCSharpCompiler(assembly, assembly.OutputDirectory))
            {
                c.BeginCompiling();
                while (!c.Poll())
                {
                    System.Threading.Thread.Sleep(50);
                }
                return(c.GetCompilerMessages().Select(cm => cm.message).ToArray());
            }
        }
Exemplo n.º 2
0
 internal static string[] GetPrecompiledAssemblyNames(IPrecompiledAssemblyProvider precompiledAssemblyProvider)
 {
     return(precompiledAssemblyProvider.GetPrecompiledAssemblies(true, EditorUserBuildSettings.activeBuildTargetGroup, EditorUserBuildSettings.activeBuildTarget)
            .Where(x => (x.Flags & sc.AssemblyFlags.UserAssembly) == sc.AssemblyFlags.UserAssembly)
            .Select(x => AssetPath.GetFileName(x.Path))
            .ToArray());
 }
        private void DrawPrecompiledReferenceListElement(Rect rect, int index, bool isactive, bool isfocused)
        {
            var precompiledReference = m_PrecompiledReferencesList.serializedProperty.GetArrayElementAtIndex(index);
            var nameProp             = precompiledReference.FindPropertyRelative("name");
            var pathProp             = precompiledReference.FindPropertyRelative("path");
            var fileNameProp         = precompiledReference.FindPropertyRelative("fileName");

            rect.height -= EditorGUIUtility.standardVerticalSpacing;
            GUIContent label = GUIContent.Temp(nameProp.stringValue);

            bool mixed = nameProp.hasMultipleDifferentValues;

            EditorGUI.showMixedValue = mixed;

            bool hasValue = !string.IsNullOrEmpty(pathProp.stringValue);

            if (!hasValue)
            {
                m_PrecompileReferenceListEntry.Insert(0, L10n.Tr("None"));

                if (m_PrecompileReferenceListEntry.Count == 1)
                {
                    label = EditorGUIUtility.TrTempContent("No possible references");
                }
                else
                {
                    label = EditorGUIUtility.TrTempContent("None");
                }
            }
            else
            {
                m_PrecompileReferenceListEntry.Insert(0, fileNameProp.stringValue);
            }

            int currentlySelectedIndex = 0;

            EditorGUI.BeginDisabled(!hasValue && !string.IsNullOrEmpty(nameProp.stringValue));
            int selectedIndex = EditorGUI.Popup(rect, label, currentlySelectedIndex, m_PrecompileReferenceListEntry.ToArray());

            EditorGUI.EndDisabled();


            if (selectedIndex > 0)
            {
                var selectedAssemblyName = m_PrecompileReferenceListEntry[selectedIndex];
                var assembly             = m_AssemblyProvider.GetPrecompiledAssemblies(
                    EditorScriptCompilationOptions.BuildingForEditor | EditorScriptCompilationOptions.BuildingWithAsserts,
                    EditorUserBuildSettings.activeBuildTargetGroup,
                    EditorUserBuildSettings.activeBuildTarget)
                                           .First(x => AssetPath.GetFileName(x.Path) == selectedAssemblyName);
                nameProp.stringValue     = selectedAssemblyName;
                pathProp.stringValue     = assembly.Path;
                fileNameProp.stringValue = AssetPath.GetFileName(assembly.Path);
            }

            m_PrecompileReferenceListEntry.RemoveAt(0);

            EditorGUI.showMixedValue = false;
        }
Exemplo n.º 4
0
 internal static string[] GetPrecompiledAssemblyNames(EditorCompilation editorCompilation)
 {
     return(editorCompilation.GetAllPrecompiledAssemblies()
            .Where(x => (x.Flags & sc.AssemblyFlags.UserAssembly) == sc.AssemblyFlags.UserAssembly)
            .Select(x => AssetPath.GetFileName(x.Path))
            .Distinct()
            .ToArray());
 }
 internal static string[] GetPrecompiledAssemblyNames(PrecompiledAssemblyProviderBase precompiledAssemblyProvider)
 {
     return(precompiledAssemblyProvider.GetPrecompiledAssemblies(
                EditorScriptCompilationOptions.BuildingForEditor | EditorScriptCompilationOptions.BuildingWithAsserts,
                EditorUserBuildSettings.activeBuildTargetGroup,
                EditorUserBuildSettings.activeBuildTarget)
            .Where(x => (x.Flags & sc.AssemblyFlags.UserAssembly) == sc.AssemblyFlags.UserAssembly)
            .Select(x => AssetPath.GetFileName(x.Path))
            .ToArray());
 }
Exemplo n.º 6
0
        private LuaArgs DoFile(LuaArgs args)
        {
            var path = args.GetString(0);

            if (Assets.Exists <LuaScript>(path))
            {
                var script = LuaScript.Get(path);
                return(m_machine.DoString(script.Code, "@" + AssetPath.GetFileName(path)));
            }
            throw new LuaError("Script not found: " + path);
        }
Exemplo n.º 7
0
        internal static string GetPrecompiledAssemblyPathFromAssemblyName(string assemblyName, EditorCompilation editorCompilation)
        {
            var precompiledAssembliesWithName = editorCompilation.GetAllPrecompiledAssemblies()
                                                .Where(x => AssetPath.GetFileName(x.Path) == assemblyName && (x.Flags & sc.AssemblyFlags.UserAssembly) == sc.AssemblyFlags.UserAssembly);

            if (precompiledAssembliesWithName.Any())
            {
                return(precompiledAssembliesWithName.Single().Path);
            }
            return(null);
        }
Exemplo n.º 8
0
        private void DrawPrecompiledReferenceListElement(Rect rect, int index, bool isactive, bool isfocused)
        {
            var list = m_PrecompiledReferencesList.list;
            var precompiledReference = list[index] as PrecompiledReference;

            rect.height -= EditorGUIUtility.standardVerticalSpacing;
            GUIContent label = precompiledReference.precompiled.HasValue ? GUIContent.Temp(precompiledReference.name) : EditorGUIUtility.TrTempContent("(Missing Reference)");

            bool mixed = precompiledReference.displayValue == MixedBool.Mixed;

            EditorGUI.showMixedValue = mixed;

            var currentSelectedPrecompiledReferences = m_State.precompiledReferences.Select(x => x.name);

            var precompiledAssemblyNames = CompilationPipeline.GetPrecompiledAssemblyNames()
                                           .Where(x => !currentSelectedPrecompiledReferences.Contains(x));

            var contextList = precompiledAssemblyNames
                              .OrderBy(x => x).ToList();

            if (!precompiledReference.precompiled.HasValue)
            {
                contextList.Insert(0, L10n.Tr("None"));

                if (!precompiledAssemblyNames.Any())
                {
                    label = EditorGUIUtility.TrTempContent("No possible references");
                }
            }
            else
            {
                contextList.Insert(0, precompiledReference.name);
            }

            int currentlySelectedIndex = 0;

            if (precompiledReference.precompiled.HasValue)
            {
                currentlySelectedIndex = Array.IndexOf(contextList.ToArray(), precompiledReference.name);
            }

            int selectedIndex = EditorGUI.Popup(rect, label, currentlySelectedIndex, contextList.ToArray());

            if (selectedIndex > 0)
            {
                var selectedAssemblyName = contextList[selectedIndex];
                precompiledReference.precompiled = EditorCompilationInterface.Instance.GetAllPrecompiledAssemblies()
                                                   .Single(x => AssetPath.GetFileName(x.Path) == selectedAssemblyName);
            }

            EditorGUI.showMixedValue = false;
        }
Exemplo n.º 9
0
    private static MonoIsland CreateMonoIsland(SupportedLanguage language)
    {
        const string kInputFilePath     = "Packages/com.unity.inputsystem/InputSystem";
        var          outputAssemblyPath = Path.GetTempFileName();

        var options          = EditorScriptCompilationOptions.BuildingForEditor;
        var buildTarget      = UnityEditor.EditorUserBuildSettings.activeBuildTarget;
        var buildTargetGroup = UnityEditor.EditorUserBuildSettings.activeBuildTargetGroup;
        var defines          = ieu.GetCompilationDefines(options, buildTargetGroup, buildTarget);

        var references = new List <string>();

        references.Add(ieu.GetEngineAssemblyPath());
        references.Add(ieu.GetEngineCoreModuleAssemblyPath());
        references.Add(ieu.GetEditorAssemblyPath());
        references.AddRange(ModuleUtils.GetAdditionalReferencesForUserScripts());
#if UNITY_EDITOR_OSX
        references.Add(Path.Combine(EditorApplication.applicationContentsPath, "UnityExtensions/Unity/GUISystem/UnityEngine.UI.dll"));
#elif UNITY_EDITOR_WIN
        references.Add(Path.Combine(Path.GetDirectoryName(EditorApplication.applicationPath), "Data/UnityExtensions/Unity/GUISystem/UnityEngine.UI.dll"));
#endif
        var unityAssemblies = InternalEditorUtility.GetUnityAssemblies(true, buildTargetGroup, buildTarget);
        foreach (var asm in unityAssemblies)
        {
            references.Add(asm.Path);
        }

        var apiCompatibilityLevel = PlayerSettings.GetApiCompatibilityLevel(EditorUserBuildSettings.activeBuildTargetGroup);

        // Hopefully the churn on these mono library helpers is over, this is going to be a bit a pain to
        // always chase.
#if UNITY_2018_3_OR_NEWER && !(UNITY_2019_1_OR_NEWER)
        var scriptAssembly = new ScriptAssembly
        {
            Filename = AssetPath.GetFileName(outputAssemblyPath),
            Flags    = AssemblyFlags.None
        };
        references.AddRange(MonoLibraryHelpers.GetSystemLibraryReferences(apiCompatibilityLevel, buildTarget, language, true, scriptAssembly));
#elif UNITY_2019_1_OR_NEWER
        references.AddRange(MonoLibraryHelpers.GetSystemLibraryReferences(apiCompatibilityLevel, buildTarget, language));
#endif

        var sources = new List <string>();
        sources.AddRange(Directory.GetFiles(kInputFilePath, "*.cs", SearchOption.AllDirectories));

        var island = new MonoIsland(buildTarget, apiCompatibilityLevel, true, sources.ToArray(),
                                    references.ToArray(), defines, outputAssemblyPath);

        return(island);
    }
Exemplo n.º 10
0
        private string Preprocess(IFileStore store, string path, string[] defines)
        {
            var builder = new StringBuilder();

            if (defines != null)
            {
                for (int i = 0; i < defines.Length; ++i)
                {
                    builder.AppendLine("#define " + defines[i] + " 1");
                }
            }
            Preprocess(builder, store, AssetPath.GetDirectoryName(path), AssetPath.GetFileName(path), 0);
            return(builder.ToString());
        }
Exemplo n.º 11
0
 private static void Load(LuaScript script)
 {
     if (!s_loadedAnims.ContainsKey(script.Path))
     {
         s_loadedAnims.Add(script.Path, new LuaAnimation(script.Path));
         try
         {
             s_install_animation.Call(new LuaArgs(script.Path, script.Code, AssetPath.GetFileName(script.Path)));
         }
         catch (LuaError e)
         {
             App.Log("Lua Error: {0}", e.Message);
         }
     }
 }
        public IEnumerable <string> ListFiles(string path)
        {
            // Iterate all files, identify those in the given path
            int count = SteamRemoteStorage.GetFileCount();

            for (int i = 0; i < count; ++i)
            {
                int    size;
                string file = SteamRemoteStorage.GetFileNameAndSize(i, out size);
                if (AssetPath.GetDirectoryName(file) == path)
                {
                    yield return(AssetPath.GetFileName(file));
                }
            }
        }
        public static Error[] ValidateAssemblyDefinitionFiles()
        {
            var customScriptAssemblies = EditorCompilationInterface.Instance.GetCustomScriptAssemblies();

            if (customScriptAssemblies.Length == 0)
            {
                return(null);
            }

            var pluginImporters = PluginImporter.GetAllImporters();

            if (pluginImporters == null || pluginImporters.Length == 0)
            {
                return(null);
            }

            var pluginFilenameToAssetPath = new Dictionary <string, string>();

            foreach (var pluginImporter in pluginImporters)
            {
                var pluginAssetPath     = pluginImporter.assetPath;
                var lowerPluginFilename = AssetPath.GetFileName(pluginAssetPath).ToLower(CultureInfo.InvariantCulture);
                pluginFilenameToAssetPath[lowerPluginFilename] = pluginAssetPath;
            }

            var errors = new List <Error>();

            foreach (var customScriptAssembly in customScriptAssemblies)
            {
                var lowerAsmdefFilename = $"{customScriptAssembly.Name.ToLower(CultureInfo.InvariantCulture)}.dll";

                string pluginPath;

                if (pluginFilenameToAssetPath.TryGetValue(lowerAsmdefFilename, out pluginPath))
                {
                    var error = new Error()
                    {
                        message      = $"Plugin '{pluginPath}' has the same filename as Assembly Definition File '{customScriptAssembly.FilePath}'. Rename the assemblies to avoid hard to diagnose issues and crashes.",
                        flags        = ErrorFlags.AsmdefPluginConflict,
                        assemblyPath = pluginPath
                    };

                    errors.Add(error);
                }
            }

            return(errors.ToArray());
        }
        internal static string GenerateResponseFile(ScriptAssembly assembly, string tempBuildDirectory)
        {
            var assemblyOutputPath = PrepareFileName(AssetPath.Combine(tempBuildDirectory, assembly.Filename));

            var arguments = new List <string>
            {
                "/target:library",
                "/nowarn:0169",
                "/out:" + assemblyOutputPath
            };

            if (assembly.CompilerOptions.AllowUnsafeCode)
            {
                arguments.Add("/unsafe");
            }

            if (assembly.CompilerOptions.UseDeterministicCompilation)
            {
                arguments.Add("/deterministic");
            }

            arguments.Add("/debug:portable");

            if (assembly.CompilerOptions.CodeOptimization == CodeOptimization.Release)
            {
                arguments.Add("/optimize+");
            }
            else
            {
                arguments.Add("/optimize-");
            }

            FillCompilerOptions(arguments, assembly.BuildTarget);

            string[] scriptAssemblyReferences = new string[assembly.ScriptAssemblyReferences.Length];
            for (var index = 0; index < assembly.ScriptAssemblyReferences.Length; index++)
            {
                var reference = assembly.ScriptAssemblyReferences[index];
                scriptAssemblyReferences[index] = "/reference:" +
                                                  PrepareFileName(AssetPath.Combine(assembly.OutputDirectory,
                                                                                    reference.Filename));
            }
            Array.Sort(scriptAssemblyReferences, StringComparer.Ordinal);
            arguments.AddRange(scriptAssemblyReferences);

            Array.Sort(assembly.References, StringComparer.Ordinal);
            foreach (var reference in assembly.References)
            {
                arguments.Add("/reference:" + PrepareFileName(reference));
            }

            var defines = assembly.Defines.Distinct().ToArray();

            Array.Sort(defines, StringComparer.Ordinal);
            foreach (var define in defines)
            {
                arguments.Add("/define:" + define);
            }

            Array.Sort(assembly.Files, StringComparer.Ordinal);
            foreach (var source in assembly.Files)
            {
                var f = PrepareFileName(source);
                f = Paths.UnifyDirectorySeparator(f);
                arguments.Add(f);
            }

            var responseFileProvider       = assembly.Language?.CreateResponseFileProvider();
            var responseFilesList          = responseFileProvider?.Get(assembly.OriginPath) ?? new List <string>();
            HashSet <string> responseFiles = new HashSet <string>(responseFilesList);

            string obsoleteResponseFile = responseFiles.SingleOrDefault(
                x => CompilerSpecificResponseFiles.MicrosoftCSharpCompilerObsolete.Contains(AssetPath.GetFileName(x)));

            if (!string.IsNullOrEmpty(obsoleteResponseFile))
            {
                Debug.LogWarning($"Using obsolete custom response file '{AssetPath.GetFileName(obsoleteResponseFile)}'. Please use '{CompilerSpecificResponseFiles.MicrosoftCSharpCompiler}' instead.");
            }

            foreach (var file in responseFiles)
            {
                AddResponseFileToArguments(arguments, file, assembly.CompilerOptions.ApiCompatibilityLevel);
            }

            var responseFile = CommandLineFormatter.GenerateResponseFile(arguments);

            return(responseFile);
        }
Exemplo n.º 15
0
        private static void Init()
        {
            if (s_animMachine == null)
            {
                s_animMachine = new LuaMachine();
                s_animMachine.AllowByteCodeLoading = false;
                s_animMachine.EnforceTimeLimits    = true;
                s_animMachine.RemoveUnsafeGlobals();

                s_animMachine.SetGlobal("print", (LuaCFunction) delegate(LuaArgs args)
                {
                    var output = new StringBuilder();
                    for (int i = 0; i < args.Length; ++i)
                    {
                        output.Append(args.ToString(i));
                        if (i < args.Length - 1)
                        {
                            output.Append(", ");
                        }
                    }
                    App.UserLog(output.ToString());
                    return(LuaArgs.Empty);
                });

                s_animMachine.SetGlobal("dofile", (LuaCFunction) delegate(LuaArgs args)
                {
                    var path = args.GetString(0);
                    if (Assets.Assets.Exists <LuaScript>(path))
                    {
                        var script = LuaScript.Get(path);
                        return(s_animMachine.DoString(script.Code, "@" + AssetPath.GetFileName(path)));
                    }
                    throw new LuaError("Script not found: " + path);
                });
                s_animMachine.DoString(
                    @"do
                        function expect( value, sExpectedType, nArg )
                            local sFoundType = type( value )
                            if sFoundType ~= sExpectedType then
                                error( ""Expected "" .. sExpectedType .. "" at argument "" .. nArg .. "", got "" .. sFoundType, 3 )
                            end
                        end

                        local tResults = {}
                        function require( s )
                            expect( s, ""string"", 1 )
                            if tResults[s] == nil then
                                local ok, result = pcall( dofile, ""scripts/"" .. s .. "".lua"" )
                                if not ok then
                                    error( result, 0 )
                                elseif result == nil then
                                    tResults[s] = true
                                else
                                    tResults[s] = result
                                end
                            end
                            return tResults[s]
                        end

                        abs = math.abs
                        floor = math.floor
                        ceil = math.ceil
                        min = math.min
                        max = math.max
                        pow = math.pow
                        sqrt = math.sqrt
                        pi = math.pi

                        function clamp( x, low, hi )
                            expect( x, ""number"", 1 )
                            expect( low, ""number"", 2 )
                            expect( hi, ""number"", 3 )
                            if x < low then
                                return low
                            elseif x > hi then
                                return hi
                            else
                                return x
                            end
                        end
                        
                        local math_rad, math_deg = math.rad, math.deg
                        local math_sin, math_cos, math_tan = math.sin, math.cos, math.tan
                        local math_asin, math_acos, math_atan = math.asin, math.acos, math.atan

                        function sin( x )
                            expect( x, ""number"", 1 )
                            return math_sin( math_rad( x ) )
                        end

                        function cos( x )
                            expect( x, ""number"", 1 )
                            return math_cos( math_rad( x ) )
                        end

                        function tan( x )
                            expect( x, ""number"", 1 )
                            return math_tan( math_rad( x ) )
                        end

                        function asin( x )
                            expect( x, ""number"", 1 )
                            return math_deg( math_asin( x ) )
                        end

                        function acos( x )
                            expect( x, ""number"", 1 )
                            return math_deg( math_acos( x ) )
                        end

                        function atan( x )
                            expect( x, ""number"", 1 )
                            return math_deg( math_atan( x ) )
                        end

                        function atan2( y, x )
                            expect( y, ""number"", 1 )
                            expect( x, ""number"", 2 )
                            return math_deg( math_atan( y, x ) )
                        end

                        function ease( f )
                            expect( f, ""number"", 1 )
                            f = clamp( f, 0.0, 1.0 )
                            return (3 - 2*f) * f * f
                        end

                        function lerp( a, b, f )
                            expect( a, ""number"", 1 )
                            expect( b, ""number"", 2 )
                            expect( f, ""number"", 3 )
                            return a + (b-a) * f
                        end

                        function lerp3( x0, y0, z0, x1, y1, z1, f )
                            expect( x0, ""number"", 1 )
                            expect( y0, ""number"", 2 )
                            expect( z0, ""number"", 3 )
                            expect( x1, ""number"", 4 )
                            expect( y1, ""number"", 5 )
                            expect( z1, ""number"", 6 )
                            expect( f, ""number"", 7 )
	                        return lerp(x0, x1, f), lerp(y0, y1, f), lerp(z0, z1, f)
                        end

                        function step( a, x )
                            expect( a, ""number"", 1 )
                            expect( x, ""number"", 2 )
                            return (x >= a) and 1 or 0
                        end

                        function smoothstep( a, b, x )
                            expect( a, ""number"", 1 )
                            expect( b, ""number"", 2 )
                            expect( x, ""number"", 3 )
                            local f = clamp( (x - a) / (b - a), 0, 1 )
                            return ease(f)
                        end

                        function rot2D( x, y, a, xo, yo )
                            expect( x, ""number"", 1 )
                            expect( y, ""number"", 2 )
                            expect( a, ""number"", 3 )
                            if xo then
                                expect( xo, ""number"", 4 )
                            end
                            if yo then
                                expect( yo, ""number"", 5 )
                            end
                            xo = xo or 0
                            yo = yo or 0
                            local ar = -math_rad(a)
                            local ca, sa = math_cos(ar), math_sin(ar)
                            return
                                xo + (x - xo) * ca - (y - yo) * sa,
                                yo + (x - xo) * sa + (y - yo) * ca
                        end

                        function setpos( part, x, y, z )
                            expect( part, ""table"", 1 )
                            expect( x, ""number"", 2 )
                            expect( y, ""number"", 3 )
                            expect( z, ""number"", 4 )
                            part.x = x
                            part.y = y
                            part.z = z
                        end

                        function lookat( part, x, y, z )
                            expect( part, ""table"", 1 )
                            expect( x, ""number"", 2 )
                            expect( y, ""number"", 3 )
                            expect( z, ""number"", 4 )
	                        local dx = x - part.x
	                        local dy = y - part.y
	                        local dz = z - part.z
	                        local dxz = sqrt( dx*dx + dz*dz )
	                        part.ry = -atan2( dx, -dz )
	                        part.rx = atan2( dy, dxz )
	                        part.rz = 0
                        end

                        local tAnimations = {}
                        function install_animation( sAnimName, sAnimCode, sChunkName )
                            local tAnimEnv = {}
                            setmetatable( tAnimEnv, { __index = _ENV } )

                            local fnAnim, sError = load( sAnimCode, sChunkName, ""t"", tAnimEnv )
                            if fnAnim then
                                local ok, sError = pcall( fnAnim )
                                if ok then
                                    tAnimations[ sAnimName ] = tAnimEnv.animate
                                else
                                    tAnimations[ sAnimName ] = nil
                                    error( sError, 0 )
                                end
                            else
                                tAnimations[ sAnimName ] = nil
                                error( sError, 0 )
                            end
                        end

                        local tPart = {}
                        function call_animation( sAnimName, sPartName, nTime )
                            tPart.name = sPartName
                            tPart.hide = false
                            tPart.x, tPart.y, tPart.z = 0,0,0
                            tPart.rx, tPart.ry, tPart.rz = 0,0,0
                            tPart.sx, tPart.sy, tPart.sz = 1,1,1
                            tPart.u, tPart.v = 0,0
                            tPart.su, tPart.sv = 1,1
                            tPart.r, tPart.g, tPart.b, tPart.a = 1,1,1,1
                            tPart.fov = nil
                            local fnAnimate = tAnimations[sAnimName]
                            if fnAnimate then
                                fnAnimate( tPart, nTime )
                            end
                            return
                                tPart.hide,
                                tPart.x, tPart.y, tPart.z,
                                tPart.rx, tPart.ry, tPart.rz,
                                tPart.sx, tPart.sy, tPart.sz,
                                tPart.u, tPart.v,
                                tPart.su, tPart.sv,
                                tPart.r, tPart.g, tPart.b, tPart.a,
                                tPart.fov
                        end
                    end",
                    "=LuaAnimation.Init"
                    );

                s_install_animation = s_animMachine.GetGlobal("install_animation").GetFunction();
                s_call_animation    = s_animMachine.GetGlobal("call_animation").GetFunction();
            }
        }
        static void LoadAssemblyDefintionState(AssemblyDefinitionState state, string path)
        {
            var asset = AssetDatabase.LoadAssetAtPath <AssemblyDefinitionAsset>(path);

            if (asset == null)
            {
                return;
            }

            var data = CustomScriptAssemblyData.FromJsonNoFieldValidation(asset.text);

            if (data == null)
            {
                return;
            }

            try
            {
                data.ValidateFields();
            }
            catch (Exception e)
            {
                Debug.LogException(e, asset);
            }

            state.asset                 = asset;
            state.assemblyName          = data.name;
            state.references            = new List <AssemblyDefinitionReference>();
            state.precompiledReferences = new List <PrecompiledReference>();
            state.defineConstraints     = new List <DefineConstraint>();
            state.versionDefines        = new List <VersionDefine>();
            state.autoReferenced        = data.autoReferenced;
            state.allowUnsafeCode       = data.allowUnsafeCode;
            state.overrideReferences    = data.overrideReferences;

            // If the .asmdef has no references (true for newly created .asmdef), then use GUIDs.
            // Otherwise do not use GUIDs. This value might be changed below if any reference is a GUID.
            state.useGUIDs = (data.references == null || data.references.Length == 0);

            if (data.versionDefines != null)
            {
                foreach (var versionDefine in data.versionDefines)
                {
                    if (!SymbolNameRestrictions.IsValid(versionDefine.define))
                    {
                        var exception = new AssemblyDefinitionException($"Invalid version define {versionDefine.define}", path);
                        Debug.LogException(exception, asset);
                    }
                    else
                    {
                        state.versionDefines.Add(new VersionDefine
                        {
                            name       = versionDefine.name,
                            expression = versionDefine.expression,
                            define     = versionDefine.define,
                        });
                    }
                }
            }

            if (data.defineConstraints != null)
            {
                foreach (var defineConstraint in data.defineConstraints)
                {
                    var symbolName = defineConstraint.StartsWith(DefineConstraintsHelper.Not) ? defineConstraint.Substring(1) : defineConstraint;
                    if (!SymbolNameRestrictions.IsValid(symbolName))
                    {
                        var exception = new AssemblyDefinitionException($"Invalid define constraint {symbolName}", path);
                        Debug.LogException(exception, asset);
                    }
                    else
                    {
                        state.defineConstraints.Add(new DefineConstraint
                        {
                            name = defineConstraint,
                        });
                    }
                }
            }

            if (data.references != null)
            {
                foreach (var reference in data.references)
                {
                    try
                    {
                        var assemblyDefinitionFile = new AssemblyDefinitionReference
                        {
                            name = reference,
                            serializedReference = reference
                        };

                        // If any references is a GUID, use GUIDs.
                        var isGuid = CompilationPipeline.GetAssemblyDefinitionReferenceType(reference) == AssemblyDefinitionReferenceType.Guid;
                        if (isGuid)
                        {
                            state.useGUIDs = true;
                        }

                        assemblyDefinitionFile.Load(reference, isGuid);
                        state.references.Add(assemblyDefinitionFile);
                    }
                    catch (AssemblyDefinitionException e)
                    {
                        UnityEngine.Debug.LogException(e, asset);
                        state.references.Add(new AssemblyDefinitionReference());
                    }
                }
            }

            var nameToPrecompiledReference = EditorCompilationInterface.Instance.GetAllPrecompiledAssemblies()
                                             .Where(x => (x.Flags & AssemblyFlags.UserAssembly) == AssemblyFlags.UserAssembly)
                                             .ToDictionary(x => AssetPath.GetFileName(x.Path), x => x);

            foreach (var precompiledReferenceName in data.precompiledReferences ?? Enumerable.Empty <String>())
            {
                try
                {
                    var precompiledReference = new PrecompiledReference
                    {
                        name = precompiledReferenceName,
                    };

                    PrecompiledAssembly assembly;
                    if (nameToPrecompiledReference.TryGetValue(precompiledReferenceName, out assembly))
                    {
                        precompiledReference.path     = assembly.Path;
                        precompiledReference.fileName = AssetPath.GetFileName(assembly.Path);
                    }
                    state.precompiledReferences.Add(precompiledReference);
                }
                catch (AssemblyDefinitionException e)
                {
                    Debug.LogException(e, asset);
                    state.precompiledReferences.Add(new PrecompiledReference());
                }
            }

            var platforms = CompilationPipeline.GetAssemblyDefinitionPlatforms();

            state.platformCompatibility = new bool[platforms.Length];

            state.compatibleWithAnyPlatform = true;
            string[] dataPlatforms = null;

            if (data.includePlatforms != null && data.includePlatforms.Length > 0)
            {
                state.compatibleWithAnyPlatform = false;
                dataPlatforms = data.includePlatforms;
            }
            else if (data.excludePlatforms != null && data.excludePlatforms.Length > 0)
            {
                state.compatibleWithAnyPlatform = true;
                dataPlatforms = data.excludePlatforms;
            }

            if (dataPlatforms != null)
            {
                foreach (var platform in dataPlatforms)
                {
                    var platformIndex = GetPlatformIndex(platforms, platform);
                    state.platformCompatibility[platformIndex] = true;
                }
            }
        }
        internal static string GenerateResponseFile(ScriptAssembly assembly, EditorScriptCompilationOptions options, string tempBuildDirectory)
        {
            bool buildingForEditor = (options & EditorScriptCompilationOptions.BuildingForEditor) == EditorScriptCompilationOptions.BuildingForEditor;
            bool developmentBuild  = (options & EditorScriptCompilationOptions.BuildingDevelopmentBuild) == EditorScriptCompilationOptions.BuildingDevelopmentBuild;

            var assemblyOutputPath = PrepareFileName(AssetPath.Combine(tempBuildDirectory, assembly.Filename));

            var arguments = new List <string>
            {
                "/target:library",
                "/nowarn:0169",
                "/out:" + assemblyOutputPath
            };

            if (assembly.CompilerOptions.AllowUnsafeCode)
            {
                arguments.Add("/unsafe");
            }

            arguments.Add("/debug:portable");

            var disableOptimizations = developmentBuild || (buildingForEditor && EditorPrefs.GetBool("AllowAttachedDebuggingOfEditor", true));

            if (!disableOptimizations)
            {
                arguments.Add("/optimize+");
            }
            else
            {
                arguments.Add("/optimize-");
            }

            FillCompilerOptions(arguments, buildingForEditor, assembly.BuildTarget);

            foreach (var reference in assembly.ScriptAssemblyReferences)
            {
                arguments.Add("/reference:" + PrepareFileName(AssetPath.Combine(assembly.OutputDirectory, reference.Filename)));
            }

            foreach (var reference in assembly.References)
            {
                arguments.Add("/reference:" + PrepareFileName(reference));
            }

            foreach (var define in assembly.Defines.Distinct())
            {
                arguments.Add("/define:" + define);
            }

            foreach (var source in assembly.Files)
            {
                var f = PrepareFileName(source);
                f = Paths.UnifyDirectorySeparator(f);
                arguments.Add(f);
            }

            var responseFileProvider       = assembly.Language?.CreateResponseFileProvider();
            var responseFilesList          = responseFileProvider?.Get(assembly.OriginPath) ?? new List <string>();
            HashSet <string> responseFiles = new HashSet <string>(responseFilesList);

            string obsoleteResponseFile = responseFiles.SingleOrDefault(
                x => CompilerSpecificResponseFiles.MicrosoftCSharpCompilerObsolete.Contains(AssetPath.GetFileName(x)));

            if (!string.IsNullOrEmpty(obsoleteResponseFile))
            {
                Debug.LogWarning($"Using obsolete custom response file '{AssetPath.GetFileName(obsoleteResponseFile)}'. Please use '{CompilerSpecificResponseFiles.MicrosoftCSharpCompiler}' instead.");
            }

            foreach (var file in responseFiles)
            {
                AddResponseFileToArguments(arguments, file, assembly.CompilerOptions.ApiCompatibilityLevel);
            }

            var responseFile = CommandLineFormatter.GenerateResponseFile(arguments);

            return(responseFile);
        }
Exemplo n.º 18
0
        public ScriptController(LevelState state)
        {
            m_state   = state;
            m_machine = new LuaMachine();
            m_machine.AllowByteCodeLoading = false;
            m_machine.EnforceTimeLimits    = true;
            m_machine.RemoveUnsafeGlobals();

            m_activeCoroutines = new List <LuaCoroutine>();

            // Install APIs and Globals
            m_machine.SetGlobal("io", new IOAPI(m_state).ToTable());
            m_machine.SetGlobal("level", new LevelAPI(m_state).ToTable());
            if (m_state is InGameState)
            {
                m_machine.SetGlobal("game", new GameAPI((InGameState)m_state).ToTable());
                m_machine.SetGlobal("campaign", new CampaignAPI(m_state).ToTable());

                m_machine.DoString(@"do
                    local game_showDialogue = game.showDialogue
                    function game.showDialogue( character, text, modal, returnImmediately )
                        -- Create dialog
                        game_showDialogue( character, text, modal )
                        if modal ~= false and returnImmediately ~= true then
                            while not game.isDialogueReadyToContinue() do
                                yield()
                            end
                        end
                    end

                    local game_hideDialogue = game.hideDialogue
                    function game.hideDialogue()
                        -- Create dialog
                        game_hideDialogue()
                        while game.isDialogueVisible() do
                            yield()
                        end
                    end
                end", "=ScriptController.ctor");
            }
            else if (m_state is CutsceneState)
            {
                m_machine.SetGlobal("cutscene", new CutsceneAPI((CutsceneState)m_state).ToTable());
                m_machine.SetGlobal("campaign", new CampaignAPI(m_state).ToTable());
            }

            m_machine.SetGlobal("dofile", (LuaCFunction)DoFile);
            m_machine.DoString(@"do
                function expect( value, sExpectedType, nArg )
                    local sFoundType = type( value )
                    if sFoundType ~= sExpectedType then
                        error( ""Expected "" .. sExpectedType .. "" at argument "" .. nArg .. "", got "" .. sFoundType, 3 )
                    end
                end

                local tResults = {}
                function require( s )
                    expect( s, ""string"", 1 )
                    if tResults[s] == nil then
                        local ok, result = pcall( dofile, ""scripts/"" .. s .. "".lua"" )
                        if not ok then
                            error( result, 0 )
                        elseif result == nil then
                            tResults[s] = true
                        else
                            tResults[s] = result
                        end
                    end
                    return tResults[s]
                end

				print = io.print
				yield = coroutine.yield

				function sleep( t )
	                expect( t, ""number"", 1 )
	                local l = io.getTime() + t
	                repeat
	                    yield()
	                until io.getTime() >= l
	            end				
            end", "=ScriptController.ctor");

            // Start the main script
            m_scriptPath = m_state.Level.Info.ScriptPath;
            if (m_scriptPath != null)
            {
                if (Assets.Exists <LuaScript>(m_scriptPath))
                {
                    try
                    {
                        var script = LuaScript.Get(m_scriptPath);
                        m_machine.DoString(script.Code, "@" + AssetPath.GetFileName(m_scriptPath));
                    }
                    catch (LuaError e)
                    {
                        App.Log("Lua Error: {0}", e.Message);
                    }
                }
                else
                {
                    App.Log("Error: Script {0} not found", m_scriptPath);
                }
            }
        }
Exemplo n.º 19
0
        static AssemblyDefintionState LoadAssemblyDefintionState(string path)
        {
            var asset = AssetDatabase.LoadAssetAtPath <AssemblyDefinitionAsset>(path);

            if (asset == null)
            {
                return(null);
            }

            var data = CustomScriptAssemblyData.FromJson(asset.text);

            if (data == null)
            {
                return(null);
            }

            var state = new AssemblyDefintionState();

            state.asset                 = asset;
            state.name                  = data.name;
            state.references            = new List <AssemblyDefinitionReference>();
            state.precompiledReferences = new List <PrecompiledReference>();
            state.defineConstraints     = new List <DefineConstraint>();
            state.autoReferenced        = ToMixedBool(data.autoReferenced);
            state.allowUnsafeCode       = ToMixedBool(data.allowUnsafeCode);
            state.overrideReferences    = ToMixedBool(data.overrideReferences);

            if (data.defineConstraints != null)
            {
                foreach (var defineConstaint in data.defineConstraints)
                {
                    try
                    {
                        var symbolName = defineConstaint.StartsWith(DefineConstraintsHelper.Not) ? defineConstaint.Substring(1) : defineConstaint;
                        if (!SymbolNameRestrictions.IsValid(symbolName))
                        {
                            throw new AssemblyDefinitionException($"Invalid define constraint {symbolName}", path);
                        }

                        state.defineConstraints.Add(new DefineConstraint
                        {
                            name         = defineConstaint,
                            displayValue = MixedBool.False,
                        });
                    }
                    catch (AssemblyDefinitionException e)
                    {
                        Debug.LogException(e, asset);
                        state.modified = true;
                    }
                }
            }

            if (data.references != null)
            {
                foreach (var reference in data.references)
                {
                    try
                    {
                        var assemblyDefinitionFile = new AssemblyDefinitionReference();
                        var referencePath          = Compilation.CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(reference);

                        if (string.IsNullOrEmpty(referencePath))
                        {
                            throw new AssemblyDefinitionException(string.Format("Could not find assembly reference '{0}'", reference), path);
                        }

                        assemblyDefinitionFile.asset = AssetDatabase.LoadAssetAtPath <AssemblyDefinitionAsset>(referencePath);

                        if (assemblyDefinitionFile.asset == null)
                        {
                            throw new AssemblyDefinitionException(string.Format("Reference assembly definition file '{0}' not found", referencePath), path);
                        }

                        assemblyDefinitionFile.data         = CustomScriptAssemblyData.FromJson(assemblyDefinitionFile.asset.text);
                        assemblyDefinitionFile.displayValue = MixedBool.False;
                        state.references.Add(assemblyDefinitionFile);
                    }
                    catch (AssemblyDefinitionException e)
                    {
                        UnityEngine.Debug.LogException(e, asset);
                        state.references.Add(new AssemblyDefinitionReference());
                        state.modified = true;
                    }
                }
            }

            var nameToPrecompiledReference = EditorCompilationInterface.Instance.GetAllPrecompiledAssemblies()
                                             .Where(x => (x.Flags & AssemblyFlags.UserAssembly) == AssemblyFlags.UserAssembly)
                                             .ToDictionary(x => AssetPath.GetFileName(x.Path), x => x);

            foreach (var precompiledReferenceName in data.precompiledReferences ?? Enumerable.Empty <String>())
            {
                try
                {
                    var precompiledReference = new PrecompiledReference();

                    var precompiledAssemblyPossibleReference = nameToPrecompiledReference.ContainsKey(precompiledReferenceName);
                    if (!precompiledAssemblyPossibleReference && !data.overrideReferences)
                    {
                        throw new AssemblyDefinitionException(string.Format("Referenced precompiled assembly '{0}' not found", precompiledReferenceName), path);
                    }

                    precompiledReference.precompiled  = nameToPrecompiledReference[precompiledReferenceName];
                    precompiledReference.displayValue = MixedBool.True;
                    state.precompiledReferences.Add(precompiledReference);
                }
                catch (AssemblyDefinitionException e)
                {
                    Debug.LogException(e, asset);
                    state.precompiledReferences.Add(new PrecompiledReference());
                    state.modified = true;
                }
            }

            var platforms = CompilationPipeline.GetAssemblyDefinitionPlatforms();

            state.platformCompatibility = new MixedBool[platforms.Length];

            var OptinalUnityAssemblies = CustomScriptAssembly.OptinalUnityAssemblies;

            state.optionalUnityReferences = new MixedBool[OptinalUnityAssemblies.Length];

            if (data.optionalUnityReferences != null)
            {
                for (int i = 0; i < OptinalUnityAssemblies.Length; i++)
                {
                    var optionalUnityReferences = OptinalUnityAssemblies[i].OptionalUnityReferences.ToString();
                    var any = data.optionalUnityReferences.Any(x => x == optionalUnityReferences);
                    if (any)
                    {
                        state.optionalUnityReferences[i] = MixedBool.True;
                    }
                }
            }

            state.compatibleWithAnyPlatform = MixedBool.True;
            string[] dataPlatforms = null;

            if (data.includePlatforms != null && data.includePlatforms.Length > 0)
            {
                state.compatibleWithAnyPlatform = MixedBool.False;
                dataPlatforms = data.includePlatforms;
            }
            else if (data.excludePlatforms != null && data.excludePlatforms.Length > 0)
            {
                state.compatibleWithAnyPlatform = MixedBool.True;
                dataPlatforms = data.excludePlatforms;
            }

            if (dataPlatforms != null)
            {
                foreach (var platform in dataPlatforms)
                {
                    var platformIndex = GetPlatformIndex(platforms, platform);
                    state.platformCompatibility[platformIndex] = MixedBool.True;
                }
            }

            return(state);
        }
        internal static string GetPrecompiledAssemblyPathFromAssemblyName(string assemblyName, PrecompiledAssemblyProviderBase precompiledAssemblyProvider, string[] extraScriptingDefines = null)
        {
            var precompiledAssemblies = precompiledAssemblyProvider.GetPrecompiledAssemblies(
                EditorScriptCompilationOptions.BuildingForEditor | EditorScriptCompilationOptions.BuildingWithAsserts,
                EditorUserBuildSettings.activeBuildTargetGroup,
                EditorUserBuildSettings.activeBuildTarget,
                extraScriptingDefines);

            foreach (var assembly in precompiledAssemblies)
            {
                if ((assembly.Flags & sc.AssemblyFlags.UserAssembly) == sc.AssemblyFlags.UserAssembly && AssetPath.GetFileName(assembly.Path) == assemblyName)
                {
                    return(assembly.Path);
                }
            }
            return(null);
        }
Exemplo n.º 21
0
        internal static string GetPrecompiledAssemblyPathFromAssemblyName(string assemblyName, IPrecompiledAssemblyProvider precompiledAssemblyProvider)
        {
            var precompiledAssemblies = precompiledAssemblyProvider.GetPrecompiledAssemblies(true, EditorUserBuildSettings.activeBuildTargetGroup, EditorUserBuildSettings.activeBuildTarget);

            foreach (var assembly in precompiledAssemblies)
            {
                if ((assembly.Flags & sc.AssemblyFlags.UserAssembly) == sc.AssemblyFlags.UserAssembly && AssetPath.GetFileName(assembly.Path) == assemblyName)
                {
                    return(assembly.Path);
                }
            }
            return(null);
        }
    static string GenerateResponseFileEdited(
        ScriptAssembly assembly,
        EditorScriptCompilationOptions options,
        string tempBuildDirectory)
    {
        bool          buildingForEditor = (options & EditorScriptCompilationOptions.BuildingForEditor) == EditorScriptCompilationOptions.BuildingForEditor;
        bool          flag      = (options & EditorScriptCompilationOptions.BuildingDevelopmentBuild) == EditorScriptCompilationOptions.BuildingDevelopmentBuild;
        List <string> arguments = new List <string>()
        {
            "-target:library",
            "-nowarn:0169",
            "-out:" + PrepareFileName(AssetPath.Combine(tempBuildDirectory, assembly.Filename))
        };

        // added
        arguments.Add("-define:__UNITY_PROCESSID__" + Process.GetCurrentProcess().Id);

        if (assembly.CompilerOptions.AllowUnsafeCode)
        {
            arguments.Add("-unsafe");
        }
        arguments.Add("-debug:portable");
        if (!flag && (!buildingForEditor || !EditorPrefs.GetBool("AllowAttachedDebuggingOfEditor", true)))
        {
            arguments.Add("-optimize+");
        }
        else
        {
            arguments.Add("-optimize-");
        }
        FillCompilerOptionsEdited(arguments, buildingForEditor, assembly.BuildTarget);
        foreach (ScriptAssembly assemblyReference in assembly.ScriptAssemblyReferences)
        {
            arguments.Add("-reference:" + ScriptCompilerBase.PrepareFileName(AssetPath.Combine(assembly.OutputDirectory, assemblyReference.Filename)));
        }
        foreach (string reference in assembly.References)
        {
            arguments.Add("-reference:" + ScriptCompilerBase.PrepareFileName(reference));
        }
        foreach (string str in ((IEnumerable <string>)assembly.Defines).Distinct <string>())
        {
            arguments.Add("-define:" + str);
        }
        foreach (string file in assembly.Files)
        {
            string str = Paths.UnifyDirectorySeparator(ScriptCompilerBase.PrepareFileName(file));
            arguments.Add(str);
        }
        HashSet <string> source = new HashSet <string>((IEnumerable <string>)(assembly.Language?.CreateResponseFileProvider()?.Get(assembly.OriginPath) ?? new List <string>()));
        string           path   = source.SingleOrDefault <string>((Func <string, bool>)(x => ((IEnumerable <string>)CompilerSpecificResponseFiles.MicrosoftCSharpCompilerObsolete).Contains <string>(AssetPath.GetFileName(x))));

        if (!string.IsNullOrEmpty(path))
        {
            UnityEngine.Debug.LogWarning((object)("Using obsolete custom response file '" + AssetPath.GetFileName(path) + "'. Please use 'csc.rsp' instead."));
        }

        // Assembly-CSharp has null OriginPath
        if (assembly.OriginPath?.StartsWith("Assets", StringComparison.Ordinal) ?? true)
        {
            // excludes unity packages
            var rspPath = "Assets/assets-csc.rsp";
            if (File.Exists(rspPath))
            {
                source.Add(rspPath);
            }
        }

        foreach (string responseFileName in source)
        {
            ScriptCompilerBase.AddResponseFileToArguments(arguments, responseFileName, assembly.CompilerOptions.ApiCompatibilityLevel);
        }
        return(CommandLineFormatter.GenerateResponseFile((IEnumerable <string>)arguments));
    }