Exemple #1
0
        /// <summary>
        /// 读取资源的缓存策略
        /// </summary>
        void ReadResourceCacheConfig()
        {
            string    cachePath            = "Config/CacheConfig/need_cache_list";
            TextAsset needCacheListAsset   = XResource.LoadAsset <TextAsset>(cachePath);
            TextAsset needPersistListAsset = XResource.LoadAsset <TextAsset>("Config/CacheConfig/need_persist_list");

            if (needCacheListAsset != null)
            {
                string configText = StringUtility.UTF8BytesToString(needCacheListAsset.bytes);
                if (!LoadCacheAndTimeConfig(configText))
                {
                    BLogger.Warning("-------------LoadCacheAndTimeConfig failed: {0}", cachePath);
                }
            }
            else
            {
                BLogger.Error("read need cache resource list config failed");
            }

            if (needPersistListAsset != null)
            {
                List <string> needPersistList = AssetBundleUtil.ReadTextStringList(needPersistListAsset.bytes);
                if (needPersistList != null)
                {
                    XResource.RegPersistResPath(needPersistList);
                    BLogger.Info("-------------register need persist res list: {0}", needPersistList.Count);
                }
            }
            else
            {
                BLogger.Error("read need persist resource list config failed");
            }
        }
Exemple #2
0
        bool LoadCacheAndTimeConfig(string configText)
        {
            try
            {
                var allConfigList = MiniJSON.Json.Deserialize(configText) as List <object>;
                if (null == allConfigList)
                {
                    BLogger.Error("parse depends json error");
                    return(false);
                }

                for (int i = 0; i < allConfigList.Count; i++)
                {
                    Dictionary <string, object> dictItem = allConfigList[i] as Dictionary <string, object>;
                    string assetPath = AssetBundleUtil.ReadJsonKey <string>(dictItem, "asset");
                    int    cacheTime = (int)AssetBundleUtil.ReadJsonKey <Int64>(dictItem, "time");
                    int    poolCnt   = (int)AssetBundleUtil.ReadJsonKey <Int64>(dictItem, "poolcnt");
                    XResource.RegCacheResPath(assetPath, cacheTime, poolCnt);

                    BLogger.Info("[{0}]cache resource[{1}] cache time: {2} pool max count:{3}", i, assetPath, cacheTime, poolCnt);
                }

                return(true);
            }
            catch (Exception e)
            {
                BLogger.Error("LoadCacheAndTimeConfig failed: " + e.ToString());
                return(false);
            }
        }
Exemple #3
0
        private void Init(
            Func <string, string> beforeItem,
            Func <string, string> beforeTest,
            Func <string, string> beforeManifest)
        {
            var manifestFile = _packageFolder
                               .GetFiles("imsmanifest.xml", SearchOption.AllDirectories)
                               .FirstOrDefault();

            if (manifestFile != null)
            {
                _packageFolder = manifestFile.Directory;
                Manifest       = new Manifest(manifestFile.Directory, Version, beforeManifest);
                Items          = Manifest.Items.Select(itemRef => new XItem(Path.Combine(_packageFolder.FullName, itemRef.Href), itemRef.Identifier, beforeItem)).ToList();
                Test           = new XResource(Path.Combine(_packageFolder.FullName, Manifest.Test.Href), Manifest.Test.Identifier, beforeTest);
            }
            else
            {
                Items = new List <XItem>();

                foreach (var filePath in Directory.GetFileSystemEntries(_packageFolder.FullName, "*.xml", SearchOption.AllDirectories))
                {
                    if (File.ReadAllText(filePath).IndexOf("assessmentItem", StringComparison.Ordinal) != -1)
                    {
                        Items.Add(new XItem(Path.Combine(filePath), $"ITM-{Path.GetFileNameWithoutExtension(filePath).Replace(".", "_")}", beforeItem));
                    }
                }
            }
        }
        protected override void InitializeResources()
        {
            XResource.InitializeDeviceGdiCompatible(Handle, Size.Width, Size.Height);

            OnCreateDeviceResources();
            OnCreateDeviceSizeResources();
        }
Exemple #5
0
        protected virtual void InitializeResources()
        {
            XResource.InitializeDevice(Handle);

            OnCreateDeviceResources();
            OnCreateDeviceSizeResources();
        }
        public static void ConvertTest(XResource test)
        {
            XNamespace xNamespace = "http://www.imsglobal.org/xsd/imsqtiasi_v3p0";

            foreach (var element in test.Content.Descendants())
            {
                var tagName      = element.Name.LocalName;
                var kebabTagName = tagName.ToKebabCase();
                element.Name = xNamespace + $"qti-{kebabTagName}";
            }

            // fix attributes
            foreach (var element in test.Content.Descendants())
            {
                var attributesToRemove = new List <XAttribute>();
                var attributesToAdd    = new List <XAttribute>();
                foreach (var attribute in element.Attributes()
                         .Where(attr => !attr.IsNamespaceDeclaration && string.IsNullOrEmpty(attr.Name.NamespaceName)))
                {
                    var attributeName      = attribute.Name.LocalName;
                    var kebabAttributeName = attributeName.ToKebabCase();
                    if (attributeName != kebabAttributeName)
                    {
                        var newAttr = new XAttribute($"{kebabAttributeName}", attribute.Value);
                        attributesToRemove.Add(attribute);
                        attributesToAdd.Add(newAttr);
                    }
                }
                attributesToRemove.ForEach(a => a.Remove());
                attributesToAdd.ForEach(a => element.Add(a));
            }
            test.Save();
        }
Exemple #7
0
 public void DestroyObject(UnityEngine.Object go, float delayTime)
 {
     if (go is GameObject)
     {
         XResource.FreeGameObject(go as GameObject, delayTime);
     }
     else
     {
         Object.Destroy(go, delayTime);
     }
 }
Exemple #8
0
 public void DestroyObject(UnityEngine.Object go)
 {
     if (go is GameObject)
     {
         XResource.FreeGameObject(go as GameObject);
     }
     else
     {
         Object.Destroy(go);
     }
 }
Exemple #9
0
        public UnityEngine.Object LoadResourceAsset(string path, Type type, bool logNotFound)
        {
            if (type == null)
            {
                BLogger.Fatal("Invalid asset type");
                return(null);
            }

            LoadFromType loadFromType;

            return(XResource.LoadAsset(path, type, out loadFromType, logNotFound));
        }
Exemple #10
0
        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);

            if (WindowState != FormWindowState.Minimized && XResource.DeviceAvailable)
            {
                OnReleaseDeviceSizeResources();

                XResource.Resize();

                OnCreateDeviceSizeResources();
            }
        }
Exemple #11
0
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                OnReleaseDeviceSizeResources();

                OnReleaseDeviceResources();

                XResource.Dispose();
            }

            base.Dispose(disposing);
        }
Exemple #12
0
 protected override void OnDraw(DeviceContext renderTarget)
 {
     base.OnDraw(renderTarget);
     if (!Context.GameOver && Context.CurrentPrize != null)
     {
         renderTarget.Transform = GlobalTransform;
         renderTarget.DrawText(
             $"{Context.WinPersons.Count}/{Context.CurrentPrize.Count}",
             XResource.TextFormats[24.0f],
             new RectangleF(1672.0f, 1957.0f, 100.0f, 30.0f),
             XResource.GetColor(Color.Yellow));
     }
 }
Exemple #13
0
        private void DrawDiagnostics(DeviceContext renderTarget)
        {
            renderTarget.Transform = Matrix3x2.Identity;
            Matrix3x2 wt = GlobalTransform;

            wt.Invert();
            var worldPos = Matrix3x2.TransformPoint(wt, MouseClientPosition);

            renderTarget.DrawText(
                $"FPS: {RenderTimer.FramesPerSecond:0}\r\nFrameTime: {RenderTimer.DurationSinceLastFrame}\r\n({worldPos.X:0}, {worldPos.Y:0})",
                XResource.TextFormats[11],
                new RectangleF(0, 0, 100, 30),
                XResource.GetColor(Color.White));
        }
 public JsonSpriteWatcher(string path, XResource xResource)
 {
     _path      = path;
     _xResource = xResource;
     _watcher   = new FileSystemWatcher(Path.GetDirectoryName(path), Path.GetFileName(path));
     _watcher.EnableRaisingEvents = true;
     _watcher.NotifyFilter        =
         NotifyFilters.Security |
         NotifyFilters.CreationTime |
         NotifyFilters.LastAccess |
         NotifyFilters.LastWrite |
         NotifyFilters.Size |
         NotifyFilters.Attributes |
         NotifyFilters.DirectoryName |
         NotifyFilters.FileName;
     _watcher.Changed += Changed;
 }
Exemple #15
0
        static void Main()
        {
            using (var window = new LayeredRenderWindow()
            {
                Text = "Hello World", DragMoveEnabled = true
            })
            {
                var bottomRightFont = new DWrite.TextFormat(window.XResource.DWriteFactory, "Consolas", 16.0f)
                {
                    FlowDirection = DWrite.FlowDirection.BottomToTop,
                    TextAlignment = DWrite.TextAlignment.Trailing,
                };
                var bottomLeftFont = new DWrite.TextFormat(window.XResource.DWriteFactory, "Consolas",
                                                           DWrite.FontWeight.Normal, DWrite.FontStyle.Italic, 24.0f)
                {
                    FlowDirection = DWrite.FlowDirection.BottomToTop,
                    TextAlignment = DWrite.TextAlignment.Leading,
                };

                window.Draw += Draw;
                RenderLoop.Run(window, () => window.Render(1, 0));

                void Draw(RenderWindow _, Direct2D.DeviceContext target)
                {
                    XResource res = window.XResource;

                    target.Clear(Color.Transparent);
                    RectangleF rectangle = new RectangleF(0, 0, target.Size.Width, target.Size.Height);

                    target.DrawRectangle(
                        rectangle,
                        res.GetColor(Color.Blue));

                    target.DrawText("😀😁😂🤣😃😄😅😆😉😊😋😎",
                                    res.TextFormats[36], rectangle, res.GetColor(Color.Blue),
                                    Direct2D.DrawTextOptions.EnableColorFont);

                    target.DrawText($"{window.XResource.DurationSinceStart:mm':'ss'.'ff}\nFPS: {window.RenderTimer.FramesPerSecond:F1}",
                                    bottomRightFont, rectangle, res.GetColor(Color.Red));

                    target.DrawText("Hello World",
                                    bottomLeftFont, rectangle, res.GetColor(Color.Purple));
                }
            }
        }
Exemple #16
0
        protected override void OnDraw(ID2D1DeviceContext renderTarget)
        {
            base.OnDraw(renderTarget);

            renderTarget.Clear(ClearColor);
            renderTarget.Transform = GlobalTransform;
            foreach (var sprite in Sprites.Values)
            {
                sprite.Draw(renderTarget);
            }

            renderTarget.Transform = Matrix3x2.Identity;
            if (ShowFPS)
            {
                renderTarget.DrawText($"FPS: {RenderTimer.FramesPerSecond:F1}",
                                      XResource.TextFormats[12.0f],
                                      new RectangleF(0, 0, renderTarget.Size.Width, renderTarget.Size.Height),
                                      XResource.GetColor(Color4.DimGray));
            }
        }
Exemple #17
0
    /// <summary>
    /// 读取ab缓存的配置
    /// </summary>
    /// <returns></returns>
    private bool LoadAbCacheConfig()
    {
        TextAsset needPersistAsset = XResource.LoadAsset <TextAsset>("Config/AbConfig/need_persist_assetbundle");

        if (needPersistAsset == null)
        {
            BLogger.Error("read resource failed: {0}", "need_persist_assetbundle");
            return(false);
        }

        List <string> listAbPath  = AssetBundleUtil.ReadTextStringList(needPersistAsset.bytes);
        List <string> listMd5Path = new List <string>();

        foreach (string abPath in listAbPath)
        {
            listMd5Path.Add(AssetBundleUtil.GetPathHash(abPath));
        }

        AssetBundlePool.Instance.RegPersistAssetBundlePath(listMd5Path);
        //Logger.Error("regist persist assetbundle count: {0}", listMd5Path.Count);
        return(true);
    }
Exemple #18
0
        private void RenderCore(int syncInterval, PresentFlags presentFlags, float lastFrameTimeInSecond)
        {
            try
            {
                // Freeze logic when render time is slow
                if (lastFrameTimeInSecond < 0.2f)
                {
                    XResource.UpdateLogic(RenderTimer.DurationSinceLastFrame);
                    OnUpdateLogic(lastFrameTimeInSecond);
                }

                XResource.RenderTarget.BeginDraw();
                {
                    OnDraw(XResource.RenderTarget);
                    OnPostDraw();
                }
                XResource.RenderTarget.EndDraw();

                XResource.SwapChain.Present(syncInterval, presentFlags);
            }
            catch (SharpGenException e)
            {
                unchecked
                {
                    const int DeviceRemoved = (int)0x887a0005;
                    const int DeviceReset   = (int)0x887A0007;
                    if (e.ResultCode == DeviceRemoved || e.ResultCode == DeviceReset)
                    {
                        OnReleaseDeviceSizeResources();
                        OnReleaseDeviceResources();
                        XResource.ReleaseDeviceResources();
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
Exemple #19
0
 public int GetFreedDelayCount()
 {
     return(XResource.GetFreedDelayCount());
 }
Exemple #20
0
 public void ClearAllDelayDestroy()
 {
     XResource.ClearAllDelayDestroy();
 }
Exemple #21
0
 /// <summary>
 /// 获取缓存资源的个数
 /// </summary>
 /// <returns></returns>
 public int GetCacheResourceCount()
 {
     return(XResource.GetCacheResourceCount());
 }
Exemple #22
0
        static void Main()
        {
            using (var res = new XResource())
                using (var form = new Form()
                {
                    Text = "Hello World"
                })
                {
                    var timer           = new RenderTimer();
                    var bottomRightFont = new DWrite.TextFormat(res.DWriteFactory, "Consolas", 16.0f)
                    {
                        FlowDirection = DWrite.FlowDirection.BottomToTop,
                        TextAlignment = DWrite.TextAlignment.Trailing,
                    };
                    var bottomLeftFont = new DWrite.TextFormat(res.DWriteFactory, "Consolas",
                                                               DWrite.FontWeight.Normal, DWrite.FontStyle.Italic, 24.0f)
                    {
                        FlowDirection = DWrite.FlowDirection.BottomToTop,
                        TextAlignment = DWrite.TextAlignment.Leading,
                    };

                    form.Resize += (o, e) =>
                    {
                        if (form.WindowState != FormWindowState.Minimized && res.DeviceAvailable)
                        {
                            res.Resize();
                        }
                    };

                    RenderLoop.Run(form, () => Render());

                    void Render()
                    {
                        if (!res.DeviceAvailable)
                        {
                            res.InitializeDevice(form.Handle);
                        }

                        var target = res.RenderTarget;

                        timer.BeginFrame();
                        target.BeginDraw();
                        Draw(target);
                        target.EndDraw();
                        res.SwapChain.Present(1, 0);
                        timer.EndFrame();
                    }

                    void Draw(DeviceContext target)
                    {
                        target.Clear(Color.CornflowerBlue.ToColor4());
                        RectangleF rectangle = new RectangleF(0, 0, target.Size.Width, target.Size.Height);

                        target.DrawRectangle(
                            new RectangleF(10, 10, target.Size.Width - 20, target.Size.Height - 20),
                            res.GetColor(Color.Blue));

                        target.DrawText("😀😁😂🤣😃😄😅😆😉😊😋😎",
                                        res.TextFormats[36], rectangle, res.GetColor(Color.Blue),
                                        DrawTextOptions.EnableColorFont);

                        target.DrawText("FPS: " + timer.FramesPerSecond.ToString("F1"),
                                        bottomRightFont, rectangle, res.GetColor(Color.Red));

                        target.DrawText("Hello World",
                                        bottomLeftFont, rectangle, res.GetColor(Color.Purple));
                    }
                }
        }
Exemple #23
0
 /// <summary>
 /// 清除所有的缓存和对象
 /// </summary>
 public void FreeCacheAndPool()
 {
     XResource.FreeAllCacheAndGo();
 }
Exemple #24
0
 /// <summary>
 /// 设置允许同时异步载入的资源个数
 /// </summary>
 /// <param name="maxLoadNum"></param>
 public void SetMaxResourceLoadNum(int maxLoadNum)
 {
     XResource.SetMaxResourceAsyncLoadNum(maxLoadNum);
 }
Exemple #25
0
 public int GetDelayFreeObjectCount()
 {
     return(XResource.GetDelayDestroyCount());
 }
Exemple #26
0
 /// <summary>
 /// 恢复所遇的缓存行为
 /// </summary>
 public void ResumeAllCache()
 {
     XResource.ResumeAllCache();
 }
Exemple #27
0
 private void ChangeValue(XResource resource, float value) {
     if (value == Constants.ZeroF) {
         resources.Remove(resource);
         return;
     }
     if (resources.ContainsKey(resource)) {
         resources[resource].Value = value;
         return;
     }
     resources.Add(resource, new XResourceValuePair(resource, value));
 }
Exemple #28
0
 public XYield(XResource xResource, float value)
     : this(new XResourceValuePair(xResource, value)) { }
Exemple #29
0
 public XResourceValuePair(XResource xResource, float value) {
     Resource = xResource;
     Value = value;
 }
Exemple #30
0
 /// <summary>
 /// Sets the yield of the indicated resource. Setting a yield of zero removes the resource.
 /// </summary>
 /// <param name="xResource">The executable resource.</param>
 /// <param name="value">The value.</param>
 /// <exception cref="System.NotImplementedException"></exception>
 public void SetYield(XResource xResource, float value) {
     switch (xResource) {
         case XResource.Special_1:
             Special_1 = value;
             break;
         case XResource.Special_2:
             Special_2 = value;
             break;
         case XResource.Special_3:
             Special_3 = value;
             break;
         case XResource.None:
         default:
             throw new NotImplementedException(ErrorMessages.UnanticipatedSwitchValue.Inject(xResource));
     }
 }
Exemple #31
0
 /// <summary>
 /// 下载配置的资源,这个资源一般是立刻卸载的
 /// </summary>
 /// <param name="resPath"></param>
 public void UnloadBinResource(string resPath)
 {
     XResource.UnloadResource(resPath);
     XResource.UnloadBinAssetBundle(resPath);
 }
Exemple #32
0
 public void StartAssetBundleAutoExpire()
 {
     XResource.StartAssetBundleAutoExpire();
 }
Exemple #33
0
 /// <summary>
 /// 暂停所有的缓存行为,一般是用在载入场景的过程中
 /// </summary>
 public void PauseAllCache()
 {
     XResource.PauseAllCache();
 }
Exemple #34
0
 public float GetYield(XResource xResource) {
     XResourceValuePair valuePair;
     if (resources.TryGetValue(xResource, out valuePair)) {
         return valuePair.Value;
     }
     D.Warn("{0} {1} is not present. Value of 0 returned.", typeof(XResource), xResource);
     return Constants.ZeroF;
 }
Exemple #35
0
 /// <summary>
 /// 卸载不使用的assetbundle
 /// </summary>
 public void UnloadUnusedAb(bool unloadNeverExpireAb)
 {
     XResource.UnloadUnusedAb(unloadNeverExpireAb);
 }