Example #1
0
        public GameObject Instantiate(Transform parent, bool stayWorldPosition)
        {
            GameObject go;

            if (m_pool == null)
            {
                go = Object.Instantiate(UnityObject, parent, stayWorldPosition) as GameObject;
                var direct = go.AddComponent <DirectDestroyGO>();
                direct.PrefabAsset = this;
                direct.Instantiated();
            }
            else
            {
                go = m_pool.Get(parent, stayWorldPosition);
                var cached = go.GetComponent <PoolCacheGO>();
                cached.Instantiated();
            }

            if (m_autoRecyclePrefab)
            {
                var autoRecycle = go.GetComponent <AutoRecycle>();
                autoRecycle.ResetAll();
            }

            StatService.Get().Increase(StatService.StatName.IN_USE_GO, 1);
#if UNITY_EDITOR
            StatService.Get().LogStat("Instantiate", UnityObject.name, m_transformCount);
#endif

#if UNITY_DEBUG
            var service = CSharpServiceManager.Get <AssetFullStatService>(CSharpServiceManager.ServiceType.ASSET_FULL_STAT);
            service.OnInstantiateGameObject(go);
#endif
            return(go);
        }
        private void SetupDependencies(string[] dependencies)
        {
            if (dependencies == null || dependencies.Length == 0)
            {
                return;
            }

            if (dependencies.Length > 63)
            {
                throw new Exception($"{ABPath} dependencies count > 64.");
            }

            m_dependencies = new AssetBundleInstance[dependencies.Length];
            var service = CSharpServiceManager.Get <AssetService>(CSharpServiceManager.ServiceType.ASSET_SERVICE);

            for (int i = 0; i < m_dependencies.Length; i++)
            {
                var hash = GenerateHash(dependencies[i]);

                if (!(service.Container.TryGetAsset(hash) is AssetBundleInstance dep))
                {
                    dep = new AssetBundleInstance(dependencies[i]);
                }

                dep.IncRef();
                m_dependencies[i] = dep;
            }
        }
Example #3
0
        private void Awake()
        {
            if (string.IsNullOrEmpty(LuaFile))
            {
                return;
            }
            var luaVM = CSharpServiceManager.Get <LuaVM>(CSharpServiceManager.ServiceType.LUA_SERVICE);
            var ret   = luaVM.LoadFileAtPath(LuaFile);

            if (!(ret[0] is LuaTable klass))
            {
                return;
            }
            LuaClass    = klass;
            CachedClass = luaVM.GetLuaClass(klass);

            var constructor = CachedClass.GetLuaMethod <LuaBindingClassNew>("new");
            var luaInstance = constructor?.Invoke(gameObject);

            luaInstance.SetInPath("name", Path.GetFileName(LuaFile.Substring(LuaFile.LastIndexOf('.') + 1)));
            luaInstance.SetInPath("fullname", LuaFile);
            Bind(luaInstance);

            var awake = CachedClass.GetLuaMethod <LuaUnityEventFunction>("awake");

            awake?.Invoke(luaInstance);
        }
Example #4
0
        private static byte[] LoadFile(ref string filename, string extension)
        {
#if UNITY_EDITOR
            filename = filename.Replace('.', '/') + extension;
            var path = $"{Application.dataPath}/../Lua/{filename}";
            if (File.Exists(path))
            {
                var text = File.ReadAllText(path);
                return(Encoding.UTF8.GetBytes(text));
            }

            return(null);
#else
            filename = filename.Replace('.', '/') + extension;
            var hotfix = $"{LUA_DEBUG_DIRECTORY}{filename}";
            if (File.Exists(hotfix))
            {
                Debug.LogWarning("HOTFIX FILE : " + hotfix);
                filename += extension;
                return(File.ReadAllBytes(hotfix));
            }

            var service  = CSharpServiceManager.Get <AssetService>(CSharpServiceManager.ServiceType.ASSET_SERVICE);
            var assetRef = service.Load($"Lua/{filename}", typeof(TextAsset));
            if (assetRef.AssetStatus != AssetRefObject.AssetStatus.DONE)
            {
                return(null);
            }
            return(assetRef.GetTextAsset().bytes);
#endif
        }
Example #5
0
        private void Awake()
        {
            var txt         = GetComponent <TextMeshProUGUI>();
            var i18NService = CSharpServiceManager.Get <I18nService>(CSharpServiceManager.ServiceType.I18N);

            txt.text = i18NService.GetText(m_key);
        }
Example #6
0
        public void Initialize()
        {
            var luaVM          = CSharpServiceManager.Get <LuaVM>(CSharpServiceManager.ServiceType.LUA_SERVICE);
            var luaGetService  = luaVM.Global.GetInPath <GetLuaService>("_ServiceManager.GetService");
            var luaTickService = luaGetService(2);

            m_tick = luaTickService.Get <Action <float> >("Tick");
        }
Example #7
0
        public static string LogCallStack()
        {
            var luaVm = CSharpServiceManager.Get <LuaVM>(CSharpServiceManager.ServiceType.LUA_SERVICE);
            var msg   = luaVm.Default.Global.GetInPath <Func <string> >("debug.traceback");
            var str   = "lua stack : " + msg.Invoke();

            Debug.Log(str);

            return(str);
        }
        private void OnDestroy()
        {
            if (!CSharpServiceManager.Initialized)
            {
                return;
            }
            var service = CSharpServiceManager.Get <AssetFullStatService>(CSharpServiceManager.ServiceType.ASSET_FULL_STAT);

            service.OnDestroyGameObject(gameObject);
        }
Example #9
0
        private static LuaTable ConvertStringArrayToLua(string[] values)
        {
            var luaVM  = CSharpServiceManager.Get <LuaVM>(CSharpServiceManager.ServiceType.LUA_SERVICE);
            var luaArr = luaVM.NewTable();

            for (var i = 0; i < values.Length; i++)
            {
                luaArr.Set(i + 1, values[i]);
            }

            return(luaArr);
        }
Example #10
0
        private static void _ExecuteAttach()
        {
            if (_isAttached)
            {
                return;
            }

            _isAttached = true;

            const string script = @"
			local LuaProfiler = CS.Extend.DebugUtil.LuaProfiler
			local debug = debug
			local _cache = {}
			local _id_generator = 0
			local _ignore_count = 0
			local function lua_profiler_hook (event, line)
			    if event == 'call' then
			        local func = debug.getinfo (2, 'f').func
			        local id = _cache[func]
			        if id then
			            LuaProfiler.BeginSample (id)
			        else
			            local ar = debug.getinfo (2, 'Sn')
			            local method_name = ar.name
			            local linedefined = ar.linedefined
			            if linedefined ~= -1 or (method_name and method_name ~= '__index')  then
			                local short_src = ar.short_src
			                method_name = method_name or '[unknown]'
			                local index = short_src:match ('^.*()[/\\]')
			                local filename  = index and short_src:sub (index + 1) or short_src
			                local show_name = filename .. ':' .. method_name .. ' '.. linedefined
			                local id = _id_generator + 1
			                _id_generator = id
			                _cache[func] = id
			                LuaProfiler.BeginSample (id, show_name)
			            else
			                _ignore_count = _ignore_count + 1
			            end
			        end
			    elseif event == 'return' then
			        if _ignore_count == 0 then
			            LuaProfiler.EndSample ()
			        else
			            _ignore_count = _ignore_count - 1
			        end
			    end
			end
			debug.sethook (lua_profiler_hook, 'cr', 0)"            ;

            var luaVM = CSharpServiceManager.Get <LuaVM>(CSharpServiceManager.ServiceType.LUA_SERVICE);

            luaVM.DoString(script, "@LoadLuaProfiler");
        }
        public override void ApplyToLuaInstance(LuaTable instance)
        {
            var luaVM         = CSharpServiceManager.Get <LuaVM>(CSharpServiceManager.ServiceType.LUA_SERVICE);
            var arrayLuaTable = luaVM.NewTable();

            for (var i = 0; i < Data.Length; i++)
            {
                arrayLuaTable.Set(i + 1, Data[i]);
            }

            instance.Set(FieldName, arrayLuaTable);
        }
Example #12
0
        public static LuaFunction GenerateTempFunction(ref string script)
        {
            var key = script.GetHashCode();

            if (!m_cachedLuaFunctions.TryGetValue(key, out var tempFunc))
            {
                var luaVM = CSharpServiceManager.Get <LuaVM>(CSharpServiceManager.ServiceType.LUA_SERVICE);
                tempFunc = luaVM.DoString(string.Format(LUA_TEMPLATE, script))[0] as LuaFunction;
                m_cachedLuaFunctions.Add(key, tempFunc);
            }

            return(tempFunc);
        }
Example #13
0
        private static void _ExecuteDetach()
        {
            if (!_isAttached)
            {
                return;
            }

            _isAttached = false;
            const string script = "debug.sethook (nil)";
            var          luaVM  = CSharpServiceManager.Get <LuaVM>(CSharpServiceManager.ServiceType.LUA_SERVICE);

            luaVM.DoString(script, "@UnloadLuaProfiler");
        }
        private static LuaTable FindInLuaBinding(LuaTable classMeta, IEnumerable <LuaBinding> bindings)
        {
            var luaVm = CSharpServiceManager.Get <LuaVM>(CSharpServiceManager.ServiceType.LUA_SERVICE);

            // ReSharper disable once LoopCanBeConvertedToQuery
            foreach (var binding in bindings)
            {
                if (Equals(classMeta, binding.LuaClass) || luaVm.LuaClassCache.IsSubClassOf(binding.LuaClass, classMeta))
                {
                    return(binding.LuaInstance);
                }
            }

            return(null);
        }
Example #15
0
        /// <summary>
        /// 只用于加载场景
        /// </summary>
        /// <param name="path">路径名(usage:Assets/Demos/CriWareDemo.unity)</param>
        public void LoadScene(string path, bool add)
        {
#if UNITY_DEBUG
            var ticks = m_stopwatch.ElapsedTicks;
            m_stopwatch.Start();
#endif
            path = m_provider.FormatScenePath(path);
            m_provider.ProvideScene(path, Container, add);
#if UNITY_DEBUG
            var time = m_stopwatch.ElapsedTicks - ticks;
            m_stopwatch.Stop();
            var statService = CSharpServiceManager.Get <StatService>(CSharpServiceManager.ServiceType.STAT);
            statService.LogStat("AssetLoad", path, (time / 10000.0f).ToString("0.000"));
#endif
        }
Example #16
0
        public override void Destroy()
        {
            if (Status == AssetStatus.DONE)
            {
                StatService.Get().Increase(StatService.StatName.ASSET_COUNT, -1);
#if UNITY_DEBUG
                var service = CSharpServiceManager.Get <AssetFullStatService>(CSharpServiceManager.ServiceType.ASSET_FULL_STAT);
                service.OnAssetUnloaded(this);
#endif
            }
            Status      = AssetStatus.DESTROYED;
            UnityObject = null;
            RefAssetBundle?.Release();
            RefAssetBundle = null;
        }
Example #17
0
        internal AssetInstance LoadAssetWithGUID <T>(string guid) where T : Object
        {
#if UNITY_DEBUG
            var ticks = m_stopwatch.ElapsedTicks;
            m_stopwatch.Start();
#endif
            var assetRef = m_provider.ProvideAssetWithGUID <T>(guid, Container, out var path);
#if UNITY_DEBUG
            var time = m_stopwatch.ElapsedTicks - ticks;
            m_stopwatch.Stop();
            var statService = CSharpServiceManager.Get <StatService>(CSharpServiceManager.ServiceType.STAT);
            statService.LogStat("AssetLoad", path, (time / 10000.0f).ToString("0.000"));
#endif
            return(assetRef);
        }
Example #18
0
        public static LuaTable LoadConfigFile(string filename)
        {
            var service = CSharpServiceManager.Get <AssetService>(CSharpServiceManager.ServiceType.ASSET_SERVICE);
            var path    = CONFIG_PATH_PREFIX + filename;

            if (!service.Exist(path))
            {
                return(null);
            }
            var assetRef = service.Load(CONFIG_PATH_PREFIX + filename, typeof(TextAsset));
            var asset    = assetRef.GetTextAsset();

            using (var reader = new StringReader(asset.text)) {
                var keys  = reader.ReadLine();
                var types = reader.ReadLine();

                var luaVM    = CSharpServiceManager.Get <LuaVM>(CSharpServiceManager.ServiceType.LUA_SERVICE);
                var LuaTable = luaVM.NewTable();
                var keyArr   = keys.Split('\t');
                var typeArr  = types.Split('\t');
                Assert.IsTrue(keyArr.Length == typeArr.Length, $"Table {filename} key count {keyArr.Length} != type count {typeArr.Length}");

                LuaTable.Set("keys", ConvertStringArrayToLua(keyArr));
                LuaTable.Set("types", ConvertStringArrayToLua(typeArr));

                var dataTable = luaVM.NewTable();
                LuaTable.Set("rows", dataTable);

                var dataIndex = 1;
                while (true)
                {
                    var row = reader.ReadLine();
                    if (string.IsNullOrEmpty(row))
                    {
                        break;
                    }

                    var rowDataArr = row.Split('\t');
                    Assert.IsTrue(keyArr.Length == rowDataArr.Length, $"Table {filename} key count {keyArr.Length} != data count {rowDataArr.Length}");
                    dataTable.Set(dataIndex, ConvertStringArrayToLua(rowDataArr));
                    dataIndex++;
                }

                assetRef.Dispose();
                return(LuaTable);
            }
        }
        private static LuaTable FindInComponents(LuaTable classMeta, LuaBinding[] bindings)
        {
            var luaVm = CSharpServiceManager.Get <LuaVM>(CSharpServiceManager.ServiceType.LUA_SERVICE);
            var t     = luaVm.NewTable();
            var index = 1;

            foreach (var binding in bindings)
            {
                if (Equals(binding.LuaClass, classMeta) || luaVm.LuaClassCache.IsSubClassOf(binding.LuaClass, classMeta))
                {
                    t.Set(index, binding.LuaInstance);
                    ++index;
                }
            }

            return(t);
        }
        private static void OnLoad()
        {
            LuaVM.OnPreRequestLoaded += () => {
                var luaVm               = CSharpServiceManager.Get <LuaVM>(CSharpServiceManager.ServiceType.LUA_SERVICE);
                var getLuaService       = luaVm.Global.GetInPath <GetLuaService>("_ServiceManager.GetService");
                var eventBindingService = getLuaService(8);
                m_dispatch    = eventBindingService.GetInPath <BindingEventDispatch>("Dispatch");
                m_bindEvent   = eventBindingService.GetInPath <BindEvent>("AddEventListener");
                m_unbindEvent = eventBindingService.GetInPath <BindEvent>("RemoveEventListener");
            };

            LuaVM.OnVMQuiting += () => {
                m_bindEvent   = null;
                m_unbindEvent = null;
                m_dispatch    = null;
            };
        }
Example #21
0
        public AssetReference Load(string path, Type typ)
        {
#if UNITY_DEBUG
            var ticks = m_stopwatch.ElapsedTicks;
            m_stopwatch.Start();
#endif
#if ASSET_LOG
            Debug.LogWarning($"Sync Load Asset {path}");
#endif
            path = m_provider.FormatAssetPath(path);
            var assetRef = m_provider.Provide(path, Container, typ);
#if UNITY_DEBUG
            var time = m_stopwatch.ElapsedTicks - ticks;
            m_stopwatch.Stop();
            var statService = CSharpServiceManager.Get <StatService>(CSharpServiceManager.ServiceType.STAT);
            statService.LogStat("AssetLoad", path, (time / 10000.0f).ToString("0.000"));
#endif
            return(assetRef);
        }
Example #22
0
        public virtual void SetAsset(Object unityObj, AssetBundleInstance refAssetBundle)
        {
            UnityObject = unityObj;
            if (refAssetBundle != null)
            {
                RefAssetBundle = refAssetBundle;
                RefAssetBundle.IncRef();
            }
            Status = UnityObject ? AssetStatus.DONE : AssetStatus.FAIL;
            if (Status == AssetStatus.DONE)
            {
                StatService.Get().Increase(StatService.StatName.ASSET_COUNT, 1);
                CreateTime = Time.realtimeSinceStartup;
#if UNITY_DEBUG
                var service = CSharpServiceManager.Get <AssetFullStatService>(CSharpServiceManager.ServiceType.ASSET_FULL_STAT);
                service.OnAssetLoaded(this);
#endif
            }
        }
Example #23
0
        private static void Hotfix()
        {
            if (!Application.isPlaying)
            {
                return;
            }

            var luaVm        = CSharpServiceManager.Get <LuaVM>(CSharpServiceManager.ServiceType.LUA_SERVICE);
            var hotfixModule = luaVm.LoadFileAtPath("hotfix.hotfix")[0] as LuaTable;
            var func         = hotfixModule.Get <Action <string> >("hotfix_module");

            lock ( modifiedModules ) {
                foreach (var module in modifiedModules)
                {
                    func(module);
                }

                modifiedModules.Clear();
            }
        }
Example #24
0
        public override void OnImportAsset(UnityEditor.AssetImporters.AssetImportContext ctx)
        {
            var text  = File.ReadAllText(ctx.assetPath);
            var asset = new TextAsset(text);

            ctx.AddObjectToAsset("main obj", asset);
            ctx.SetMainObject(asset);

            if (!Application.isPlaying)
            {
                return;
            }

            var luaVm         = CSharpServiceManager.Get <LuaVM>(CSharpServiceManager.ServiceType.LUA_SERVICE);
            var get           = luaVm.Global.GetInPath <GetLuaService>("_ServiceManager.GetService");
            var configService = get(1);
            var reloadFunc    = configService.Get <LuaFunction>("Reload");

            reloadFunc.Call(Path.GetFileNameWithoutExtension(ctx.assetPath));
        }
Example #25
0
        private void OnDestroy()
        {
            if (!CSharpServiceManager.Initialized)
            {
                return;
            }
            var destroy = CachedClass.GetLuaMethod <LuaUnityEventFunction>("destroy");

            destroy?.Invoke(LuaInstance);
#if UNITY_DEBUG
            var luaVm = CSharpServiceManager.Get <LuaVM>(CSharpServiceManager.ServiceType.LUA_SERVICE);
            LuaInstance.SetMetaTable(luaVm.DestroyedTableMeta);
#endif
            LuaInstance?.Dispose();
            LuaInstance = null;

            foreach (var binding in LuaData)
            {
                binding.Destroy();
            }
        }
        public override void Destroy()
        {
            if (Status != AssetStatus.DONE)
            {
                return;
            }

            if (m_dependencies != null)
            {
                foreach (var dependency in m_dependencies)
                {
                    dependency.Release();
                }
            }

            AB.Unload(false);
            Object.Destroy(AB);
            var statService = CSharpServiceManager.Get <StatService>(CSharpServiceManager.ServiceType.STAT);

            statService.Increase(StatService.StatName.ASSET_BUNDLE_COUNT, -1);
        }
        public static void OnSceneLoaded()
        {
            CSharpServiceManager.Register(new NetworkService());

            var mode = GameSystem.Get().SystemSetting.GetString("GAME", "Mode");

            if (mode != "Shipping")
            {
                using (var assetRef = AssetService.Get().Load("Console", typeof(GameObject))) {
                    var go = assetRef.Instantiate();
                    CSharpServiceManager.Register(go.GetComponent <InGameConsole>());
                }
            }

            Application.targetFrameRate = 30;
            var maxInstantiateDuration = GameSystem.Get().SystemSetting.GetDouble("GAME", "MaxInstantiateDuration");

            AssetService.Get().AfterSceneLoaded((float)maxInstantiateDuration);
            var lua = CSharpServiceManager.Get <LuaVM>(CSharpServiceManager.ServiceType.LUA_SERVICE);

            lua.StartUp();
        }
        public static void OnInit()
        {
            Application.runInBackground = true;
            DOTween.Init(false, true, LogBehaviour.Default);

            CSharpServiceManager.Initialize();
            CSharpServiceManager.Register(new ErrorLogToFile());
            CSharpServiceManager.Register(new GlobalCoroutineRunnerService());
            CSharpServiceManager.Register(new StatService());
#if UNITY_DEBUG
            CSharpServiceManager.Register(new AssetFullStatService());
#endif
            CSharpServiceManager.Register(new AssetService());
            CSharpServiceManager.Register(new GameSystem());
            CSharpServiceManager.Register(new RenderFeatureService());
            CSharpServiceManager.Register(new SpriteAssetService());
            CSharpServiceManager.Register(new I18nService());
            CSharpServiceManager.Register(new LuaVM());
            CSharpServiceManager.Register(new TickService());

#if !UNITY_EDITOR
            var builder = new StringBuilder(2048);
            builder.AppendLine($"Unity: {Application.unityVersion}");
            builder.AppendLine($"App : {Application.identifier}:{Application.version} {Application.platform}");
            builder.AppendLine($"Device : {SystemInfo.deviceModel}, {SystemInfo.deviceName}, {SystemInfo.deviceType}");
            builder.AppendLine($"Battery : {SystemInfo.batteryStatus}, {SystemInfo.batteryLevel:0.00}");
            builder.AppendLine($"Processor : {SystemInfo.processorType}, {SystemInfo.processorCount}, {SystemInfo.processorFrequency}");
            builder.AppendLine($"Graphics : {SystemInfo.graphicsDeviceName}, {SystemInfo.graphicsDeviceType}, " +
                               $"{SystemInfo.graphicsDeviceVendor}, {SystemInfo.graphicsDeviceVersion}, " +
                               $"GMEM : {SystemInfo.graphicsMemorySize}, SM{SystemInfo.graphicsShaderLevel}");

            builder.AppendLine($"OS : {SystemInfo.operatingSystem}, MEM : {SystemInfo.systemMemorySize}, {SystemInfo.operatingSystemFamily}");
            builder.AppendLine("UsesReversedZBuffer : " + SystemInfo.usesReversedZBuffer);
            builder.Append($"NPOT : {SystemInfo.npotSupport}, INSTANCING : {SystemInfo.supportsInstancing}, Texture Size : {SystemInfo.maxTextureSize}, " +
                           $"Compute : {SystemInfo.supportsComputeShaders}");
            Debug.LogWarning(builder.ToString());
#endif
        }
Example #29
0
        public void Execute(Type typ)
        {
            var hashCode = AssetInstance.GenerateHash(Location);

            Asset = Container.TryGetAsset(hashCode) as AssetInstance;
            if (Asset == null)
            {
                Asset = typ == typeof(GameObject) ? new PrefabAssetInstance(Location) : new AssetInstance(Location);
            }
            else if (Asset.IsFinished)
            {
                var service = CSharpServiceManager.Get <GlobalCoroutineRunnerService>(CSharpServiceManager.ServiceType.COROUTINE_SERVICE);
                service.StartCoroutine(AsyncLoadedAssetCallback());
                return;
            }

            Asset.OnStatusChanged += OnAssetReady;
            if (Asset.Status == AssetRefObject.AssetStatus.ASYNC_LOADING)
            {
                return;
            }
            Asset.Status = AssetRefObject.AssetStatus.ASYNC_LOADING;
            Provider.ProvideAsync(this, typ);
        }
Example #30
0
        private void RefreshLanguageText()
        {
            var assetService = CSharpServiceManager.Get <AssetService>(CSharpServiceManager.ServiceType.ASSET_SERVICE);

            using (var assetRef = assetService.Load("Config/static-i18n", typeof(TextAsset))) {
                var doc = new XmlDocument();
                doc.LoadXml(assetRef.GetTextAsset().text);
                var rootElement = doc.DocumentElement;
                if (m_supportedLang == null)
                {
                    var supportLangAttr = rootElement.Attributes["support-lang"];
                    m_supportedLang = supportLangAttr.Value.Split(';');
                    if (string.IsNullOrEmpty(m_currentLangName))
                    {
                        m_currentLangName = m_supportedLang[0];
                        m_currentLang     = 0;
                    }
                    else
                    {
                        m_currentLang = Array.IndexOf(m_supportedLang, m_currentLangName);
                    }
                }

                foreach (XmlNode node in rootElement.ChildNodes)
                {
                    if (node.NodeType != XmlNodeType.Element)
                    {
                        continue;
                    }

                    var key = node.Attributes["guid"].Value;
                    var val = node.Attributes[m_currentLang].Value;
                    m_languageText.Add(key, val);
                }
            }
        }