public async Task SetItemAsync <tt>(CachedEntry <tt> item)
 {
     SetItem(item);
 }
 public async Task SetItemAsync(Type type, CachedEntry <object> item)
 {
     SetItem(type, item);
 }
示例#3
0
 void RefreshCache(string inPath)
 {
     m_CacheRoot    = CacheFolder(inPath);
     m_IsCacheDirty = false;
 }
示例#4
0
        CachedEntry CacheFolder(string path)
        {
            List <CachedEntry> contents   = new List <CachedEntry>();
            string             buildLabel = null;

            bool isExpanded = m_FoldedOutHash.Contains(path);
            int  numFolders = 0;

            foreach (string folder in Directory.EnumerateDirectories(path))
            {
                if (isExpanded)
                {
                    CachedEntry entry = CacheFolder(folder);
                    if (entry.status != CachedEntryStatus.Ignored)
                    {
                        contents.Add(entry);
                    }
                }
                numFolders++;
            }

            int numMsgs = 0;
            int numSrvs = 0;

            foreach (string file in Directory.EnumerateFiles(path))
            {
                CachedEntryStatus status = GetFileStatus(file);
                if (status == CachedEntryStatus.Ignored)
                {
                    continue;
                }

                string type = "";
                if (status == CachedEntryStatus.BuiltSrvFile || status == CachedEntryStatus.UnbuiltSrvFile)
                {
                    numSrvs++;
                    type = "srv";
                }
                else
                {
                    numMsgs++;
                    type = "msg";
                }

                if (isExpanded)
                {
                    if (status == CachedEntryStatus.BuiltMsgFile || status == CachedEntryStatus.BuiltSrvFile)
                    {
                        buildLabel = "Rebuild " + type;
                    }
                    else
                    {
                        buildLabel = "Build " + type;
                    }

                    contents.Add(new CachedEntry()
                    {
                        path       = file,
                        status     = status,
                        buildLabel = buildLabel,
                    });
                }
            }

            if (numMsgs > 0 && numSrvs > 0)
            {
                buildLabel = "Build " + numMsgs + " msg" + (numMsgs > 1 ? "s" : "") + ", " + numSrvs + " srv" + (numSrvs > 1 ? "s" : "");
            }
            else if (numMsgs > 0)
            {
                buildLabel = "Build " + numMsgs + " msg" + (numMsgs > 1 ? "s" : "");
            }
            else if (numSrvs > 0)
            {
                buildLabel = "Build " + numSrvs + " srv" + (numSrvs > 1 ? "s" : "");
            }

            return(new CachedEntry()
            {
                path = path,
                contents = contents,
                status = (numMsgs + numSrvs + numFolders == 0) ? CachedEntryStatus.Ignored : CachedEntryStatus.Folder,
                buildLabel = buildLabel,
            });
        }
示例#5
0
 protected void Free(CachedEntry ce)
 {
     // Nothing to do for this implementation here, as the atlas is reconstructed each frame, instead of keeping state across frames
 }
示例#6
0
        void ShowCachedEntry(CachedEntry entry)
        {
            if (entry.status == CachedEntryStatus.Ignored)
            {
                return;
            }
            else if (entry.status != CachedEntryStatus.Folder)
            {
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField(entry.label);

                if (entry.hasBuildButton && GUILayout.Button(entry.buildLabel, GUILayout.Width(BUTTON_WIDTH)))
                {
                    // build this msg/srv file
                    switch (entry.status)
                    {
                    case CachedEntryStatus.BuiltMsgFile:
                    case CachedEntryStatus.UnbuiltMsgFile:
                        MessageAutoGen.GenerateSingleMessage(entry.path, MessageGenBrowserSettings.Get().outputPath);
                        break;

                    case CachedEntryStatus.BuiltSrvFile:
                    case CachedEntryStatus.UnbuiltSrvFile:
                        ServiceAutoGen.GenerateSingleService(entry.path, MessageGenBrowserSettings.Get().outputPath);
                        break;
                    }
                    AssetDatabase.Refresh();
                    m_IsCacheDirty = true;
                }
                EditorGUILayout.EndHorizontal();
            }
            else
            {
                bool isFoldedOut = m_FoldedOutHash.Contains(entry.path);

                EditorGUILayout.BeginHorizontal();
                bool shouldBeFoldedOut = EditorGUILayout.Foldout(isFoldedOut, entry.label, true, EditorStyles.foldout);
                if (entry.hasBuildButton && GUILayout.Button(entry.buildLabel, GUILayout.Width(BUTTON_WIDTH)))
                {
                    // build this directory
                    MessageAutoGen.GenerateDirectoryMessages(entry.path, MessageGenBrowserSettings.Get().outputPath);
                    ServiceAutoGen.GenerateDirectoryServices(entry.path, MessageGenBrowserSettings.Get().outputPath);
                    AssetDatabase.Refresh();
                    m_IsCacheDirty = true;
                }
                EditorGUILayout.EndHorizontal();

                if (isFoldedOut)
                {
                    EditorGUI.indentLevel++;
                    foreach (CachedEntry subEntry in entry.contents)
                    {
                        ShowCachedEntry(subEntry);
                    }
                    EditorGUI.indentLevel--;
                }

                if (shouldBeFoldedOut != isFoldedOut)
                {
                    m_IsCacheDirty = true;

                    if (shouldBeFoldedOut)
                    {
                        m_FoldedOutHash.Add(entry.path);
                    }
                    else
                    {
                        m_FoldedOutHash.Remove(entry.path);
                    }
                }
            }
        }
示例#7
0
 private async Task SaveItemAsync <tt>(CachedEntry <tt> entry)
 {
     await _dataSource.SetItemAsync(entry);
 }
示例#8
0
            override public bool Reserve(FrameId frameId, ref ShadowData shadowData, ShadowRequest sr, uint[] widths, uint[] heights, ref VectorArray <ShadowData> entries, ref VectorArray <ShadowPayload> payload, VisibleLight[] lights)
            {
                ShadowData sd    = shadowData;
                ShadowData dummy = new ShadowData();

                if (sr.shadowType != GPUShadowType.Point && sr.shadowType != GPUShadowType.Spot && sr.shadowType != GPUShadowType.Directional)
                {
                    return(false);
                }

                if (sr.shadowType == GPUShadowType.Directional)
                {
                    for (uint i = 0; i < k_MaxCascadesInShader; ++i)
                    {
                        m_TmpSplits[i].Set(0.0f, 0.0f, 0.0f, float.NegativeInfinity);
                    }
                }

                Key key;

                key.id            = sr.instanceId;
                key.faceIdx       = 0;
                key.visibleIdx    = (int)sr.index;
                key.shadowDataIdx = entries.Count();

                uint originalEntryCount    = entries.Count();
                uint originalPayloadCount  = payload.Count();
                uint originalActiveEntries = m_ActiveEntriesCount;

                uint facecnt  = sr.facecount;
                uint facemask = sr.facemask;
                uint bit      = 1;
                int  resIdx   = 0;

                entries.Reserve(6);

                float nearPlaneOffset = QualitySettings.shadowNearPlaneOffset;

                while (facecnt > 0)
                {
                    if ((bit & facemask) != 0)
                    {
                        uint width  = widths[resIdx];
                        uint height = heights[resIdx];
                        uint ceIdx;
                        if (!Alloc(frameId, key, width, height, out ceIdx, payload))
                        {
                            entries.Purge(entries.Count() - originalEntryCount);
                            payload.Purge(payload.Count() - originalPayloadCount);
                            uint added = m_ActiveEntriesCount - originalActiveEntries;
                            for (uint i = originalActiveEntries; i < m_ActiveEntriesCount; ++i)
                            {
                                m_EntryCache.Swap(i, m_EntryCache.Count() - i - 1);
                            }
                            m_EntryCache.Purge(added, Free);
                            m_ActiveEntriesCount = originalActiveEntries;
                            return(false);
                        }

                        // read
                        CachedEntry ce = m_EntryCache[ceIdx];
                        // modify
                        Matrix4x4 vp;
                        if (sr.shadowType == GPUShadowType.Point)
                        {
                            vp = ShadowUtils.ExtractPointLightMatrix(lights[sr.index], key.faceIdx, 2.0f, out ce.current.view, out ce.current.proj, out ce.current.lightDir, out ce.current.splitData, m_CullResults, (int)sr.index);
                        }
                        else if (sr.shadowType == GPUShadowType.Spot)
                        {
                            vp = ShadowUtils.ExtractSpotLightMatrix(lights[sr.index], out ce.current.view, out ce.current.proj, out ce.current.lightDir, out ce.current.splitData);
                        }
                        else if (sr.shadowType == GPUShadowType.Directional)
                        {
                            vp = ShadowUtils.ExtractDirectionalLightMatrix(lights[sr.index], key.faceIdx, m_CascadeCount, m_CascadeRatios, nearPlaneOffset, width, height, out ce.current.view, out ce.current.proj, out ce.current.lightDir, out ce.current.splitData, m_CullResults, (int)sr.index);
                            m_TmpSplits[key.faceIdx]    = ce.current.splitData.cullingSphere;
                            m_TmpSplits[key.faceIdx].w *= ce.current.splitData.cullingSphere.w;
                        }
                        else
                        {
                            vp = Matrix4x4.identity; // should never happen, though
                        }
                        // write :(
                        m_EntryCache[ceIdx] = ce;

                        sd.worldToShadow = vp.transpose; // apparently we need to transpose matrices that are sent to HLSL
                        sd.scaleOffset   = new Vector4(ce.current.viewport.width * m_WidthRcp, ce.current.viewport.height * m_HeightRcp, ce.current.viewport.x, ce.current.viewport.y);
                        sd.texelSizeRcp  = new Vector2(m_WidthRcp, m_HeightRcp);
                        sd.PackShadowmapId(m_TexSlot, m_SampSlot, ce.current.slice);
                        sd.shadowType    = sr.shadowType;
                        sd.payloadOffset = payload.Count();
                        entries.AddUnchecked(sd);

                        resIdx++;
                        facecnt--;
                        key.shadowDataIdx++;
                    }
                    else
                    {
                        // we push a dummy face in, otherwise we'd need a mapping from face index to shadowData in the shader as well
                        entries.AddUnchecked(dummy);
                    }
                    key.faceIdx++;
                    bit <<= 1;
                }

                if (sr.shadowType == GPUShadowType.Directional)
                {
                    ShadowPayload sp = new ShadowPayload();
                    payload.Reserve(k_MaxCascadesInShader);
                    for (uint i = 0; i < k_MaxCascadesInShader; i++)
                    {
                        sp.Set(m_TmpSplits[i]);
                        payload.AddUnchecked(sp);
                    }
                }

                return(true);
            }
示例#9
0
 //private CachedEntry<object> LoadItem(string name, Type type, double? lifeSpanSeconds = null)
 //{
 //    var entry = _dataSource.GetItem(name, type);
 //    if (entry == null || (entry.TimeOut.HasValue && entry.TimeOut.Value < DateTime.Now))
 //    {
 //        entry = new CachedEntry<object>()
 //        {
 //            Name = name,
 //            Changed = DateTime.Now,
 //            Created = DateTime.Now
 //        };
 //        if (lifeSpanSeconds.HasValue)
 //        {
 //            entry.TimeOut = DateTime.Now.AddSeconds(lifeSpanSeconds.Value);
 //        }
 //    }
 //    return entry;
 //}
 //private async Task<CachedEntry<object>> LoadItemAsync(string name, Type type, double? lifeSpanSeconds = null)
 //{
 //    var entry = await _dataSource.GetItemAsync(name, type);
 //    if (entry == null || (entry.TimeOut.HasValue && entry.TimeOut.Value < DateTime.Now))
 //    {
 //        entry = new CachedEntry<object>()
 //        {
 //            Name = name,
 //            Changed = DateTime.Now,
 //            Created = DateTime.Now
 //        };
 //        if (lifeSpanSeconds.HasValue)
 //        {
 //            entry.TimeOut = DateTime.Now.AddSeconds(lifeSpanSeconds.Value);
 //        }
 //    }
 //    return entry;
 //}
 private void SaveItem <tt>(CachedEntry <tt> entry)
 {
     _dataSource.SetItem(entry);
 }
        public void SetItem <tt>(CachedEntry <tt> item)
        {
            if (item == null)
            {
                throw new ArgumentNullException();
            }
            if (!Names.ContainsKey(item.Name.ToUpper()))
            {
                Names.Add(item.Name.ToUpper(), "");
            }
            object comp  = item.Item;
            object empty = default(tt);

            if (comp != empty)
            {
                if (item.TimeOut.HasValue && item.TimeOut.Value.Subtract(DateTime.Now).TotalSeconds > 0)
                {
                    var lifeSpanSeconds = item.TimeOut.Value.Subtract(DateTime.Now).TotalSeconds;

                    int totSeconds = (int)lifeSpanSeconds;
                    int ms         = (int)((lifeSpanSeconds - (1.0 * totSeconds)) * 1000.0);
                    try
                    {
                        lock (_memoryCache)
                        {
                            try
                            {
                                _memoryCache.Remove(item.Name.ToUpper());
                            }
                            catch (Exception)
                            {
                            }
                            _memoryCache.Set(item.Name.ToUpper(), item, new TimeSpan(0, 0, 0, totSeconds, ms));
                        }
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                }
                else
                {
                    lock (_memoryCache)
                    {
                        try
                        {
                            _memoryCache.Remove(item.Name.ToUpper());
                        }
                        catch (Exception)
                        {
                        }
                        _memoryCache.Set(item.Name.ToUpper(), item);
                    }
                }
            }
            else
            {
                lock (_memoryCache)
                {
                    try
                    {
                        _memoryCache.Remove(item.Name.ToUpper());
                    }
                    catch (Exception)
                    {
                    }
                }
                //_memoryCache.Remove(item.Name.ToUpper());
                //HttpRuntime.Cache.Remove(item.Name.ToUpper());
            }
        }
        public void SetItem(Type type, CachedEntry <object> item)
        {
            if (item == null)
            {
                throw new ArgumentNullException();
            }
            if (!Names.ContainsKey(item.Name.ToUpper()))
            {
                Names.Add(item.Name.ToUpper(), "");
            }
            object comp  = item.Item;
            object empty = null;

            if (comp != empty)
            {
                if (item.TimeOut.HasValue)
                {
                    var lifeSpanSeconds = item.TimeOut.Value.Subtract(DateTime.Now).TotalSeconds;
                    int totSeconds      = (int)lifeSpanSeconds;
                    int ms = (int)((lifeSpanSeconds - (1.0 * totSeconds)) * 1000.0);

                    lock (_memoryCache)
                    {
                        try
                        {
                            _memoryCache.Remove(item.Name.ToUpper());
                        }
                        catch (Exception)
                        {
                        }
                        _memoryCache.Set(item.Name.ToUpper(), item, new TimeSpan(0, 0, 0, totSeconds, ms));
                    }
                    //HttpRuntime.Cache.Insert(item.Name.ToUpper(), item, null,
                    //    System.Web.Caching.Cache.NoAbsoluteExpiration,
                    //    new TimeSpan(0, 0, 0, totSeconds, ms),
                    //    CacheItemPriority.Default, null);
                }
                else
                {
                    lock (_memoryCache)
                    {
                        try
                        {
                            _memoryCache.Remove(item.Name.ToUpper());
                        }
                        catch (Exception)
                        {
                        }
                        _memoryCache.Set(item.Name.ToUpper(), item);
                        //HttpRuntime.Cache[item.Name.ToUpper()] = item;
                    }
                }
            }
            else
            {
                lock (_memoryCache)
                {
                    try
                    {
                        _memoryCache.Remove(item.Name.ToUpper());
                    }
                    catch (Exception)
                    {
                    }
                }
                // _memoryCache.Remove(item.Name.ToUpper());
                //HttpRuntime.Cache.Remove(item.Name.ToUpper());
            }
        }
示例#12
0
        /// <summary>
        /// Чтение модели с диска, если она не закеширована
        /// </summary>
        /// <param name="fname">Имя файла</param>
        /// <returns>Кешированная модель</returns>
        static CachedEntry ReadModel(string fname)
        {
            // Открытие файла
            byte[]       data = FileSystem.Read(fname);
            BinaryReader f    = new BinaryReader(new MemoryStream(data));

            // Чтение заголовка
            string fourcc  = new string(f.ReadChars(4));
            int    version = f.ReadInt32();

            if (fourcc != "IDP3" || version != 15)
            {
                f.Close();
                return(null);
            }

            // Пропуск имени модели и флагов
            f.BaseStream.Position += 72;

            // Значения количества
            int tagNum     = f.ReadInt32();
            int surfaceNum = f.ReadInt32();

            // Пропуск скинов
            f.BaseStream.Position += 8;

            // Отступы в файле
            int tagOffset     = f.ReadInt32();
            int surfaceOffset = f.ReadInt32();

            // Кешированная запись
            CachedEntry entry = new CachedEntry();

            // Массивы мешей
            entry.Surfaces = new MorphMeshComponent[surfaceNum];

            // Чтение поверхностей
            f.BaseStream.Position = surfaceOffset;
            for (int surfIndex = 0; surfIndex < surfaceNum; surfIndex++)
            {
                // Пропуск ненужных данных
                f.BaseStream.Position += 72;

                // Чтение размеров
                int frameNum    = f.ReadInt32();
                int shaderNum   = f.ReadInt32();
                int vertexNum   = f.ReadInt32();
                int triangleNum = f.ReadInt32();

                // Пропуск отступов и шейдеров
                f.BaseStream.Position += 20;
                f.BaseStream.Position += 68 * shaderNum;

                // Индексы
                ushort[] indices = new ushort[triangleNum * 3];
                for (int i = 0; i < indices.Length; i++)
                {
                    indices[i] = (ushort)f.ReadInt32();
                }

                // Текстурные координаты
                Vec2[] texCoords = new Vec2[vertexNum];
                for (int i = 0; i < texCoords.Length; i++)
                {
                    texCoords[i].X = f.ReadSingle();
                    texCoords[i].Y = f.ReadSingle();
                }

                // Кадры
                MorphMeshComponent.MorphFrame[] frames = new MorphMeshComponent.MorphFrame[frameNum];
                for (int frameIndex = 0; frameIndex < frameNum; frameIndex++)
                {
                    // Необходимые массивы
                    Vec3[] verts = new Vec3[vertexNum];
                    Vec3[] norms = new Vec3[vertexNum];

                    // Чтение вершин и нормалей
                    for (int i = 0; i < vertexNum; i++)
                    {
                        // Позиция
                        float px, py, pz, nx, ny, nz;
                        px       = (float)f.ReadInt16() * VERTEX_SCALE;
                        py       = (float)f.ReadInt16() * VERTEX_SCALE;
                        pz       = (float)f.ReadInt16() * VERTEX_SCALE;
                        verts[i] = new Vec3(-py, pz, px);

                        // Нормаль
                        float lng = (float)f.ReadByte() * NORMAL_MULT;
                        float lat = (float)f.ReadByte() * NORMAL_MULT;
                        nx       = (float)(Math.Cos(lat) * Math.Sin(lng));
                        ny       = (float)(Math.Sin(lat) * Math.Sin(lng));
                        nz       = (float)(Math.Cos(lng));
                        norms[i] = new Vec3(-ny, nz, nx);
                    }

                    // Сохранение кадра
                    MorphMeshComponent.MorphFrame frame = new MorphMeshComponent.MorphFrame();
                    frame.Time         = frameIndex;
                    frame.Vertices     = verts;
                    frame.Normals      = norms;
                    frames[frameIndex] = frame;
                }

                // Поверхность
                MorphMeshComponent surface = new MorphMeshComponent();
                surface.Frames            = frames;
                surface.TexCoords         = texCoords;
                surface.Indices           = indices;
                entry.Surfaces[surfIndex] = surface;
            }

            return(entry);
        }
示例#13
0
        /// <summary>
        /// Handles the caching for a log entry.
        /// </summary>
        /// <param name="extension">Extended log entry information or (<c>null</c>).</param>
        /// <param name="entryType">The log entry type.</param>
        /// <param name="message">The log message (or <c>null</c>).</param>
        /// <param name="e">The logged exception (or <c>null</c>).</param>
        /// <returns><c>true</c> if the entry is in the cache and should not be logged.</returns>
        private static bool IsCached(ISysLogEntryExtension extension, SysLogEntryType entryType, string message, Exception e)
        {
            lock (cache)
            {
                if (cacheTime == TimeSpan.Zero)
                {
                    return(false);
                }

                switch (entryType)
                {
                case SysLogEntryType.Trace:

                    if (!SysLog.CacheDebug)
                    {
                        return(false);
                    }

                    break;

                case SysLogEntryType.Error:

                    if (!SysLog.CacheErrors)
                    {
                        return(false);
                    }

                    break;

                case SysLogEntryType.Exception:

                    if (!SysLog.CacheExceptions)
                    {
                        return(false);
                    }

                    break;

                case SysLogEntryType.Information:

                    if (!SysLog.CacheInformation)
                    {
                        return(false);
                    }

                    break;

                case SysLogEntryType.SecurityFailure:
                case SysLogEntryType.SecuritySuccess:

                    if (!SysLog.CacheSecurity)
                    {
                        return(false);
                    }

                    break;

                case SysLogEntryType.Warning:

                    if (!SysLog.CacheWarnings)
                    {
                        return(false);
                    }

                    break;

                default:

                    Debug.WriteLine("Unexpected log entry type.");
                    break;
                }

                MD5Key      key = ComputeMD5Hash(extension, entryType, message, e);
                CachedEntry entry;

                if (cache.TryGetValue(key, out entry))
                {
                    entry.Count++;
                    entry.LastTime = DateTime.UtcNow;
                    return(true);
                }

                entry = new CachedEntry(extension, entryType, message, e);
                cache.Add(key, entry);
                return(false);
            }
        }