Example #1
0
        public static List <int> GetContentIdList(SiteInfo siteInfo, ChannelInfo channelInfo, int?onlyAdminId, int offset, int limit)
        {
            var list = ListCache.GetContentIdList(channelInfo.Id, onlyAdminId);

            if (list.Count >= offset + limit)
            {
                return(list.Skip(offset).Take(limit).ToList());
            }

            var tableName = ChannelManager.GetTableName(siteInfo, channelInfo);

            if (list.Count == offset)
            {
                var dict = ContentCache.GetContentDict(channelInfo.Id);

                var pageContentInfoList = DataProvider.ContentDao.GetContentInfoList(tableName, DataProvider.ContentDao.GetCacheWhereString(siteInfo, channelInfo, onlyAdminId),
                                                                                     DataProvider.ContentDao.GetOrderString(channelInfo, string.Empty), offset, limit);

                foreach (var contentInfo in pageContentInfoList)
                {
                    dict[contentInfo.Id] = contentInfo;
                }

                var pageContentIdList = pageContentInfoList.Select(x => x.Id).ToList();
                list.AddRange(pageContentIdList);
                return(pageContentIdList);
            }

            return(DataProvider.ContentDao.GetCacheContentIdList(tableName, DataProvider.ContentDao.GetCacheWhereString(siteInfo, channelInfo, onlyAdminId),
                                                                 DataProvider.ContentDao.GetOrderString(channelInfo, string.Empty), offset, limit));
        }
            public string SetCached(string key, string content, DateTime expiryUtc, DateTime retrievedUtc)
            {
                var item = new ContentItem(new HtmlString(content), expiryUtc, Crypto.Hash(content), retrievedUtc);

                ContentCache.AddOrSet(key, item);
                return(item.ContentId);
            }
Example #3
0
        public Mesh(vec3[] points, vec2[] source, vec3[] normals, ivec3[] vertices, ushort[] indices, string texture,
                    ivec2[] boneIndexes = null, vec2[] boneWeights = null)
        {
            float minX   = points.Min(p => p.x);
            float maxX   = points.Max(p => p.x);
            float minY   = points.Min(p => p.y);
            float maxY   = points.Max(p => p.y);
            float minZ   = points.Min(p => p.z);
            float maxZ   = points.Max(p => p.z);
            float width  = maxX - minX;
            float height = maxY - minY;
            float depth  = maxZ - minZ;

            Points      = points;
            Source      = source;
            Normals     = normals;
            Vertices    = vertices;
            Indices     = indices;
            MaxIndex    = indices.Max();
            Bounds      = new vec3(width, height, depth);
            Origin      = new vec3(minX, minY, minZ);
            BoneIndexes = boneIndexes;
            BoneWeights = boneWeights;
            Texture     = ContentCache.GetTexture(texture ?? "Grey.png");
        }
Example #4
0
        public string Render(Stack <string> placeHolderStack, out bool pageOutputCached)
        {
            string cachePath;

            if (pageCode != null && pageCode != "")
            {
                cachePath = "$pagecode[" + PageCode + "]";
            }
            else if (pageID != null)
            {
                cachePath = "$pageID[" + PageID + "]";
            }
            else
            {
                cachePath = path;
            }

            string output = null;

            if (ContentCache.IsContentCached(cachePath))
            {
                output = ContentCache.ReadCache(cachePath);
            }

            if (output != null)
            {
                pageOutputCached = true;
                return(output);
            }

            XmlDocument content = new XmlDocument();

            if (contentFile.Length > 0)
            {
                content = LoadContentDocument();
                if (content == null)
                {
                    pageOutputCached = false;
                    return("[Unable to load the content file " + contentFile + "]");
                }
            }

            bool cacheable = true;

            output = Template.Text;
            foreach (PlaceHolder placeholder in Template.PlaceHolders)
            {
                bool returnValueCacheable;
                output    = output.Replace(placeholder.RawText, placeholder.Render(this, content, placeHolderStack, out returnValueCacheable));
                cacheable = cacheable && returnValueCacheable;
            }

            pageOutputCached = cacheable;
            if (cacheable)
            {
                ContentCache.CacheContent(cachePath, output);
            }

            return(output);
        }
Example #5
0
 public Sprite(string filename, ivec2 origin, TextureWraps wrap = TextureWraps.Repeat,
               TextureFilters filter = TextureFilters.Nearest) :
     this(ContentCache.GetTexture(filename, false, true, wrap, filter), new SourceRect(),
          Alignments.Custom)
 {
     this.origin = origin;
 }
Example #6
0
        public static void UpdateCache(SiteInfo siteInfo, ChannelInfo channelInfo, ContentInfo contentInfoToUpdate)
        {
            var dict = ContentCache.GetContentDict(channelInfo.Id);

            var contentInfo = GetContentInfo(siteInfo, channelInfo, contentInfoToUpdate.Id);

            if (contentInfo != null)
            {
                if (ListCache.IsChanged(channelInfo, contentInfo, contentInfoToUpdate))
                {
                    ListCache.Remove(channelInfo.Id);
                }

                if (CountCache.IsChanged(contentInfo, contentInfoToUpdate))
                {
                    var tableName = ChannelManager.GetTableName(siteInfo, channelInfo);
                    CountCache.Remove(tableName, contentInfo);
                    CountCache.Add(tableName, contentInfoToUpdate);
                }
            }

            dict[contentInfoToUpdate.Id] = contentInfoToUpdate;

            StlContentCache.ClearCache();
        }
Example #7
0
        public static void Initialize()
        {
            Directory.CreateDirectory(Path =
#if ENV_ANDROID
#if Survivalcraft
                                          //ModsManager.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "Survivalcraft/Mods"))
                                          //ModsManager.Combine(((AndroidSdCardExternalContentProvider)ExternalContentManager.m_providers).m_rootDirectory, "Survivalcraft/Mods"))
                                          //ModsManager.Combine(Storage.GetDirectoryName(Window.Activity.GetExternalFilesDir(Environment.DirectoryPictures).AbsolutePath), "Survivalcraft/Mods"))
                                          "/sdcard/Survivalcraft/Mods"
#elif Bugs
                                          "/sdcard/Bugs/Mods"
#else
                                          "/sdcard/RuthlessConquest/Mods"
#endif
#elif USE_DATA_PATH
                                          Storage.GetSystemPath("data:Mods")
#else
                                          "Mods"
#endif
                                      );
            ModsManager.Initialize();
            ContentCache.AddPackage(Storage.OpenFile("app:Content.pak", OpenFileMode.Read));
            for (var enumerator = ModsManager.GetEntries(".pak").GetEnumerator(); enumerator.MoveNext();)
            {
                ContentCache.AddPackage(enumerator.Current.Stream);
            }
        }
Example #8
0
        public Terminal()
        {
            colors      = new Color[4];
            commands    = new Dictionary <string, CommandProcessor>();
            font        = ContentCache.GetFont("Terminal");
            currentLine = new SpriteText(font);
            lines       = new List <SpriteText>();
            oldCommands = new List <string>();
            charWidth   = font.Measure("A").x;
            storedIndex = -1;

            var accessor = Properties.Access(this);

            padding              = accessor.GetInt("terminal.padding", this, false);
            textProcessor        = new TextProcessor();
            textProcessor.Submit = Submit;

            AddDefaultCommands();

            MessageSystem.Subscribe(this, CoreMessageTypes.ResizeWindow, (messageType, data, dt) =>
            {
                // The terminal is always resized to fit the window width.
                Width = ((ivec2)data).x;
            });

            MessageSystem.Subscribe(this, CoreMessageTypes.Keyboard, (messageType, data, dt) =>
            {
                ProcessKeyboard((KeyboardData)data);
            });
        }
Example #9
0
 public static void RemoveCache(string tableName, int channelId)
 {
     ListCache.Remove(channelId);
     ContentCache.Remove(channelId);
     CountCache.Clear(tableName);
     StlContentCache.ClearCache();
 }
Example #10
0
        public static List <int> GetContentIdList(SiteInfo siteInfo, ChannelInfo channelInfo, int offset, int limit)
        {
            var list = ListCache.GetContentIdList(channelInfo.Id);

            if (list.Count >= offset + limit)
            {
                return(list.Skip(offset).Take(limit).ToList());
            }

            if (list.Count == offset)
            {
                var dict = ContentCache.GetContentDict(channelInfo.Id);
                var pageContentInfoList = DataProvider.ContentDao.GetCacheContentInfoList(siteInfo, channelInfo, offset, limit);
                foreach (var contentInfo in pageContentInfoList)
                {
                    dict[contentInfo.Id] = contentInfo;
                }

                var pageContentIdList = pageContentInfoList.Select(x => x.Id).ToList();
                list.AddRange(pageContentIdList);
                return(pageContentIdList);
            }

            return(DataProvider.ContentDao.GetCacheContentIdList(siteInfo, channelInfo, offset, limit));
        }
Example #11
0
        public static void UpdateCache(SiteInfo siteInfo, ChannelInfo channelInfo, IContentInfo contentInfoToUpdate)
        {
            var dict = ContentCache.GetContentDict(channelInfo.Id);

            var contentInfo = GetContentInfo(siteInfo, channelInfo, contentInfoToUpdate.Id);

            if (contentInfo != null)
            {
                var isClearCache = contentInfo.IsTop != contentInfoToUpdate.IsTop;

                if (!isClearCache)
                {
                    var orderAttributeName =
                        ETaxisTypeUtils.GetContentOrderAttributeName(
                            ETaxisTypeUtils.GetEnumType(channelInfo.Additional.DefaultTaxisType));
                    if (contentInfo.Get(orderAttributeName) != contentInfoToUpdate.Get(orderAttributeName))
                    {
                        isClearCache = true;
                    }
                }

                if (isClearCache)
                {
                    ListCache.Remove(channelInfo.Id);
                }
            }


            dict[contentInfoToUpdate.Id] = (ContentInfo)contentInfoToUpdate;

            StlContentCache.ClearCache();
        }
Example #12
0
 public static void RemoveCache(int siteId, int channelId, string tableName)
 {
     RemoveListCache(siteId, channelId);
     ContentCache.Remove(channelId);
     CountCache.Clear(tableName);
     StlContentCache.ClearCache();
 }
Example #13
0
        public ModelBatch(int bufferSize, int indexBufferSize)
        {
            const int ShadowMapSize = 2048;

            GLUtilities.AllocateBuffers(bufferSize, indexBufferSize, out bufferId, out indexBufferId, GL_STATIC_DRAW);

            modelShader = new Shader();
            modelShader.Attach(ShaderTypes.Vertex, "ModelShadow.vert");
            modelShader.Attach(ShaderTypes.Fragment, "ModelShadow.frag");
            modelShader.AddAttribute <float>(3, GL_FLOAT);
            modelShader.AddAttribute <float>(2, GL_FLOAT);
            modelShader.AddAttribute <float>(3, GL_FLOAT);
            modelShader.CreateProgram();
            modelShader.Bind(bufferId, indexBufferId);
            modelShader.Use();
            modelShader.SetUniform("shadowSampler", 0);
            modelShader.SetUniform("textureSampler", 1);

            shadowMapShader = new Shader();
            shadowMapShader.Attach(ShaderTypes.Vertex, "ShadowMap.vert");
            shadowMapShader.Attach(ShaderTypes.Fragment, "ShadowMap.frag");
            shadowMapShader.AddAttribute <float>(3, GL_FLOAT, false, false, sizeof(float) * 5);
            shadowMapShader.CreateProgram();
            shadowMapShader.Bind(bufferId, indexBufferId);

            shadowMapTarget = new RenderTarget(ShadowMapSize, ShadowMapSize, RenderTargetFlags.Depth);
            defaultTexture  = ContentCache.GetTexture("Grey.png");
            handles         = new List <ModelHandle>();

            // These default values are arbitrary, just to make sure something shows up.
            LightDirection   = vec3.UnitX;
            LightColor       = Color.White;
            AmbientIntensity = 0.1f;
        }
Example #14
0
        public Mesh(vec3[] points, vec2[] sources, vec3[] normals, ivec4[] vertices, ushort[] indices,
                    string[] textures, Material[] materials, ivec2[] boneIndexes = null, vec2[] boneWeights = null)
        {
            var minX   = points.Min(p => p.x);
            var maxX   = points.Max(p => p.x);
            var minY   = points.Min(p => p.y);
            var maxY   = points.Max(p => p.y);
            var minZ   = points.Min(p => p.z);
            var maxZ   = points.Max(p => p.z);
            var width  = maxX - minX;
            var height = maxY - minY;
            var depth  = maxZ - minZ;

            Points   = points;
            Sources  = sources;
            Normals  = normals;
            Vertices = vertices;
            Indices  = indices;
            MaxIndex = indices.Max();

            // TODO: Once meshes are finalized, bounds could be pre-computed.
            Bounds      = new vec3(width, height, depth);
            Origin      = new vec3(minX, minY, minZ);
            BoneIndexes = boneIndexes;
            BoneWeights = boneWeights;

            Textures = textures == null
                                ? new [] { defaultTexture }
                                : textures.Select(t => ContentCache.GetTexture(t)).ToArray();

            Materials = materials;
        }
Example #15
0
        public async Task <IReadOnlyList <IEnrichedContentEntity> > GetReferencedContentsAsync(IJsonValue value, TimeSpan cacheDuration,
                                                                                               CancellationToken ct)
        {
            var ids = ParseIds(value);

            if (ids == null)
            {
                return(EmptyContents);
            }

            async Task <IReadOnlyList <IEnrichedContentEntity> > LoadAsync(IEnumerable <DomainId> ids)
            {
                var result = await GetContentsLoader().LoadAsync(ids).GetResultAsync(ct);

                return(result?.NotNull().ToList() ?? EmptyContents);
            }

            if (cacheDuration > TimeSpan.Zero)
            {
                var contents = await ContentCache.CacheOrQueryAsync(ids, async pendingIds =>
                {
                    return(await LoadAsync(pendingIds));
                }, cacheDuration);

                return(contents.ToList());
            }

            return(await LoadAsync(ids));
        }
Example #16
0
 public DebugView()
 {
     font       = ContentCache.GetFont("Debug");
     rawGroups  = new Dictionary <string, List <string> >();
     textGroups = new Dictionary <string, List <SpriteText> >();
     groupOrder = new List <string>();
 }
Example #17
0
 public DialogueBox()
 {
     font       = ContentCache.GetFont("Default");
     lines      = new List <SpriteText>();
     Anchor     = Alignments.Bottom;
     Offset     = new ivec2(0, 100);
     IsCentered = true;
 }
Example #18
0
        public static SpriteFont Load(string name, bool shouldCache = true)
        {
            var texture = ContentCache.GetTexture(name + "_0.png", false, shouldCache, TextureWraps.Repeat,
                                                  TextureFilters.Nearest, "Fonts/");
            var lines = File.ReadAllLines(Paths.Fonts + name + ".fnt");
            var first = lines[0];

            // Size is in the form "size=[value]";
            var index1 = first.IndexOf("size", StringComparison.CurrentCulture) + 5;
            var index2 = first.IndexOf(' ', index1);
            var size   = int.Parse(first.Substring(index1, index2 - index1));

            // Character count (the fourth line) looks like "chars count=[value]".
            var count  = int.Parse(lines[3].Substring(12));
            var glyphs = new Glyph[CharacterRange];

            for (int i = 0; i < count; i++)
            {
                int ParseValue(string s)
                {
                    var index = s.IndexOf('=') + 1;

                    return(int.Parse(s.Substring(index)));
                }

                var line   = lines[i + 4];
                var tokens = line.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                // The first token is just "char", so it can be ignored.
                var id      = ParseValue(tokens[1]);
                var x       = ParseValue(tokens[2]);
                var y       = ParseValue(tokens[3]);
                var width   = ParseValue(tokens[4]);
                var height  = ParseValue(tokens[5]);
                var offsetX = ParseValue(tokens[6]);
                var offsetY = ParseValue(tokens[7]);
                var advance = ParseValue(tokens[8]);
                var w       = texture.Width;
                var h       = texture.Height;

                vec2[] source =
                {
                    new vec2(x,         y),
                    new vec2(x,         y + height),
                    new vec2(x + width, y),
                    new vec2(x + width, y + height)
                };

                for (int j = 0; j < 4; j++)
                {
                    source[j] /= new vec2(w, h);
                }

                glyphs[id] = new Glyph(width, height, advance, new ivec2(offsetX, offsetY), source);
            }

            return(new SpriteFont(glyphs, size, texture.Id));
        }
            public ContentItem GetCached(string key)
            {
                ContentItem item;

                if (!ContentCache.TryGetValue(key, out item))
                {
                    return(null);
                }
                return(item);
            }
Example #20
0
 public static void RemoveCacheBySiteId(string tableName, int siteId)
 {
     foreach (var channelId in ChannelManager.GetChannelIdList(siteId))
     {
         ListCache.Remove(channelId);
         ContentCache.Remove(channelId);
     }
     CountCache.Clear(tableName);
     StlContentCache.ClearCache();
 }
Example #21
0
        public static List <(int ChannelId, int ContentId)> GetChannelContentIdList(SiteInfo siteInfo, ChannelInfo channelInfo, int adminId, bool isAllContents, int offset, int limit)
        {
            var tableName = ChannelManager.GetTableName(siteInfo, channelInfo);

            var channelContentIdList = new List <(int ChannelId, int ContentId)>();

            foreach (var contentId in ListCache.GetContentIdList(channelInfo.Id, adminId))
            {
                channelContentIdList.Add((channelInfo.Id, contentId));
            }
            if (isAllContents)
            {
                var channelIdList = ChannelManager.GetChannelIdList(channelInfo, EScopeType.Descendant);
                foreach (var contentChannelId in channelIdList)
                {
                    var contentChannelInfo = ChannelManager.GetChannelInfo(siteInfo.Id, contentChannelId);
                    var channelTableName   = ChannelManager.GetTableName(siteInfo, contentChannelInfo);
                    if (!StringUtils.EqualsIgnoreCase(tableName, channelTableName))
                    {
                        continue;
                    }

                    foreach (var contentId in ListCache.GetContentIdList(contentChannelId, adminId))
                    {
                        channelContentIdList.Add((contentChannelId, contentId));
                    }
                }
            }

            if (channelContentIdList.Count >= offset + limit)
            {
                return(channelContentIdList.Skip(offset).Take(limit).ToList());
            }

            if (channelContentIdList.Count == offset)
            {
                var dict = ContentCache.GetContentDict(channelInfo.Id);

                var pageContentInfoList = DataProvider.ContentDao.GetContentInfoList(tableName, DataProvider.ContentDao.GetCacheWhereString(siteInfo, channelInfo, adminId, isAllContents),
                                                                                     DataProvider.ContentDao.GetOrderString(channelInfo, string.Empty, isAllContents), offset, limit);

                foreach (var contentInfo in pageContentInfoList)
                {
                    ListCache.Set(contentInfo);
                    dict[contentInfo.Id] = contentInfo;
                }

                var pageContentIdList = pageContentInfoList.Select(x => (x.ChannelId, x.Id)).ToList();
                channelContentIdList.AddRange(pageContentIdList);
                return(pageContentIdList);
            }

            return(DataProvider.ContentDao.GetCacheChannelContentIdList(tableName, DataProvider.ContentDao.GetCacheWhereString(siteInfo, channelInfo, adminId, isAllContents),
                                                                        DataProvider.ContentDao.GetOrderString(channelInfo, string.Empty, isAllContents), offset, limit));
        }
Example #22
0
        public TentacleTester(Scene scene)
        {
            this.scene = scene;

            var mesh     = ContentCache.GetMesh("Tentacle.obj");
            var points   = mesh.Points;
            var vertices = mesh.Vertices;

            ivec2[] boneIndexes = new ivec2[vertices.Length];
            vec2[]  boneWeights = new vec2[vertices.Length];

            float halfRange     = (points.Max(p => p.x) - points.Min(p => p.x)) / 2;
            float segmentLength = halfRange * 2 / (Bones - 1);

            // Compute bone indexes and weights.
            for (int i = 0; i < vertices.Length; i++)
            {
                float x      = points[vertices[i].x].x;
                float weight = 1 - ((x + halfRange) % segmentLength) / segmentLength;

                // Each segment spans two bones.
                int index = (int)Math.Floor((x + halfRange) / segmentLength);

                boneIndexes[i] = new ivec2(index, Math.Min(index + 1, Bones - 1));
                boneWeights[i] = new vec2(weight, 1 - weight);
            }

            mesh.BoneIndexes = boneIndexes;
            mesh.BoneWeights = boneWeights;

            curve = new Curve3D();

            // Compute the default pose.
            vec3[] defaultPose = new vec3[Bones];

            for (int i = 0; i < Bones; i++)
            {
                defaultPose[i] = new vec3(-halfRange + segmentLength * i, 0, 0);
            }

            // Initialize springs.
            vec3 target = scene.GetEntities(EntityGroups.Player)[0].Position;

            vec3[] springPoints =
            {
                new vec3(halfRange * 2, HoverHeight, 0),
                new vec3(halfRange,     HoverHeight, 0),
                new vec3(target.x,      HoverHeight, target.z)
            };

            springs  = springPoints.Select(p => new SpringPoint3D(p, 0.85f, 0.85f)).ToArray();
            skeleton = new Skeleton(mesh, defaultPose);
            scene.Renderer.Add(skeleton);
        }
        public ActionResult DeleteConfirmed(int id)
        {
            var content = new Content {
                ContentId = id
            };

            db.Entry(content).State = EntityState.Deleted;
            db.SaveChanges();
            ContentCache.Remove(id);
            ShowGenericSavedMessage();
            return(RedirectToAction("Index"));
        }
Example #24
0
 public Mesh(vec3[] points, vec2[] source, vec3[] normals, ivec3[] vertices, ushort[] indices, string texture,
             ivec2[] boneIndexes = null, vec2[] boneWeights = null)
 {
     Points      = points;
     Source      = source;
     Normals     = normals;
     Vertices    = vertices;
     Indices     = indices;
     MaxIndex    = indices.Max();
     BoneIndexes = boneIndexes;
     BoneWeights = boneWeights;
     Texture     = ContentCache.GetTexture(texture ?? "Grey.png");
 }
Example #25
0
        /*********
        ** Public methods
        *********/
        /****
        ** Constructor
        ****/
        /// <summary>Construct an instance.</summary>
        /// <param name="serviceProvider">The service provider to use to locate services.</param>
        /// <param name="rootDirectory">The root directory to search for content.</param>
        /// <param name="currentCulture">The current culture for which to localise content.</param>
        /// <param name="monitor">Encapsulates monitoring and logging.</param>
        /// <param name="reflection">Simplifies access to private code.</param>
        public ContentCore(IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, IMonitor monitor, Reflector reflection)
        {
            // init
            this.Monitor          = monitor ?? throw new ArgumentNullException(nameof(monitor));
            this.Content          = new LocalizedContentManager(serviceProvider, rootDirectory, currentCulture);
            this.Cache            = new ContentCache(this.Content, reflection);
            this.ModContentPrefix = this.GetAssetNameFromFilePath(Constants.ModPath);

            // get asset data
            this.CoreAssets          = new CoreAssetPropagator(this.NormaliseAssetName, reflection);
            this.LanguageCodes       = this.GetKeyLocales().ToDictionary(p => p.Value, p => p.Key, StringComparer.InvariantCultureIgnoreCase);
            this.IsLocalisableLookup = reflection.GetField <IDictionary <string, bool> >(this.Content, "_localizedAsset").GetValue();
        }
Example #26
0
        /*********
        ** Public methods
        *********/
        /****
        ** Constructor
        ****/
        /// <summary>Construct an instance.</summary>
        /// <param name="serviceProvider">The service provider to use to locate services.</param>
        /// <param name="rootDirectory">The root directory to search for content.</param>
        /// <param name="currentCulture">The current culture for which to localise content.</param>
        /// <param name="languageCodeOverride">The current language code for which to localise content.</param>
        /// <param name="monitor">Encapsulates monitoring and logging.</param>
        /// <param name="reflection">Simplifies access to private code.</param>
        public SContentManager(IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, string languageCodeOverride, IMonitor monitor, Reflector reflection)
            : base(serviceProvider, rootDirectory, currentCulture, languageCodeOverride)
        {
            // init
            this.Monitor          = monitor ?? throw new ArgumentNullException(nameof(monitor));
            this.Cache            = new ContentCache(this, reflection);
            this.GetKeyLocale     = reflection.GetMethod(this, "languageCode");
            this.ModContentPrefix = this.GetAssetNameFromFilePath(Constants.ModPath);

            // get asset data
            this.CoreAssets = new CoreAssets(this.NormaliseAssetName);
            this.KeyLocales = this.GetKeyLocales(reflection);
        }
Example #27
0
        // TODO: Load texture data (then clear the texture).
        public TimeOfDay()
        {
            // TODO: Pull property.
            // Day duration is listed in minutes in the property file.
            //dayDuration = Properties.GetInt("day.duration") * 60;

            var texture = ContentCache.GetTexture("Horizon.png", true, false);

            horizon = texture.Data;

            LightColor     = Color.White;
            LightDirection = Utilities.Normalize(new vec3(-1, -0.4f, 0));
        }
Example #28
0
        /*********
        ** Public methods
        *********/
        /// <summary>Construct an instance.</summary>
        /// <param name="name">A name for the mod manager. Not guaranteed to be unique.</param>
        /// <param name="serviceProvider">The service provider to use to locate services.</param>
        /// <param name="rootDirectory">The root directory to search for content.</param>
        /// <param name="currentCulture">The current culture for which to localise content.</param>
        /// <param name="coordinator">The central coordinator which manages content managers.</param>
        /// <param name="monitor">Encapsulates monitoring and logging.</param>
        /// <param name="reflection">Simplifies access to private code.</param>
        /// <param name="onDisposing">A callback to invoke when the content manager is being disposed.</param>
        /// <param name="isModFolder">Whether this content manager is for a mod folder.</param>
        protected BaseContentManager(string name, IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, Action <BaseContentManager> onDisposing, bool isModFolder)
            : base(serviceProvider, rootDirectory, currentCulture)
        {
            // init
            this.Name                = name;
            this.Coordinator         = coordinator ?? throw new ArgumentNullException(nameof(coordinator));
            this.Cache               = new ContentCache(this, reflection);
            this.Monitor             = monitor ?? throw new ArgumentNullException(nameof(monitor));
            this.OnDisposing         = onDisposing;
            this.IsModContentManager = isModFolder;

            // get asset data
            this.LanguageCodes = this.GetKeyLocales().ToDictionary(p => p.Value, p => p.Key, StringComparer.InvariantCultureIgnoreCase);
        }
Example #29
0
        public SaveSlotUI()
        {
            Anchor   = Alignments.None;
            saveSlot = new SaveSlot(null);

            SpriteFont font = ContentCache.GetFont("Debug");

            percentage = new SpriteText(font);

            if (saveSlot.ShowPercentage)
            {
                percentage.Value = $"{saveSlot.Progression.ComputePercentage():F2}%";
            }
        }
Example #30
0
        /*********
        ** Public methods
        *********/
        /// <summary>Construct an instance.</summary>
        /// <param name="name">A name for the mod manager. Not guaranteed to be unique.</param>
        /// <param name="serviceProvider">The service provider to use to locate services.</param>
        /// <param name="rootDirectory">The root directory to search for content.</param>
        /// <param name="currentCulture">The current culture for which to localize content.</param>
        /// <param name="coordinator">The central coordinator which manages content managers.</param>
        /// <param name="monitor">Encapsulates monitoring and logging.</param>
        /// <param name="reflection">Simplifies access to private code.</param>
        /// <param name="onDisposing">A callback to invoke when the content manager is being disposed.</param>
        /// <param name="isNamespaced">Whether this content manager handles managed asset keys (e.g. to load assets from a mod folder).</param>
        protected BaseContentManager(string name, IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, Action <BaseContentManager> onDisposing, bool isNamespaced)
            : base(serviceProvider, rootDirectory, currentCulture)
        {
            // init
            this.Name         = name;
            this.Coordinator  = coordinator ?? throw new ArgumentNullException(nameof(coordinator));
            this.Cache        = new ContentCache(this, reflection);
            this.Monitor      = monitor ?? throw new ArgumentNullException(nameof(monitor));
            this.OnDisposing  = onDisposing;
            this.IsNamespaced = isNamespaced;

            // get asset data
            this.LanguageCodes            = this.GetKeyLocales().ToDictionary(p => p.Value, p => p.Key, StringComparer.OrdinalIgnoreCase);
            this.BaseDisposableReferences = reflection.GetField <List <IDisposable> >(this, "disposableAssets").GetValue();
        }
Example #31
0
        public void Load(ContentCache cache)
        {
            Log.Write(this, "Loading texture resource for video sprite.");

            cache.Load(resource, out texture);

            pixelData = new Color[texture.Width * texture.Height];
            texture.GetData<Color>(pixelData);

            Loaded = true;
        }
Example #32
0
        public virtual void Unload(ContentCache cache)
        {
            Log.Write(this, "Unloading game bloom.");

            resolveTarget.Dispose();
            renderTarget1.Dispose();
            renderTarget2.Dispose();

            Loaded = false;
        }
Example #33
0
        public virtual void Load(ContentCache cache)
        {
            Log.Write(this, "Loading game bloom.");

            spriteBatch = new SpriteBatch(Game.GraphicsDevice);

            bloomExtractEffect = Game.Content.Load<Effect>(@"Effects\bloomextract");
            bloomCombineEffect = Game.Content.Load<Effect>(@"Effects\bloomcombine");
            gaussianBlurEffect = Game.Content.Load<Effect>(@"Effects\gaussianblur");

            // Look up the resolution and format of our main backbuffer.
            PresentationParameters pp = Game.GraphicsDevice.PresentationParameters;

            int width = pp.BackBufferWidth;
            int height = pp.BackBufferHeight;

            SurfaceFormat format = pp.BackBufferFormat;

            // Create a texture for reading back the backbuffer contents.
            resolveTarget = new RenderTarget2D(Game.GraphicsDevice, width, height, true, format, DepthFormat.Depth24);

            // Create two rendertargets for the bloom processing. These are half the
            // size of the backbuffer, in order to minimize fillrate costs. Reducing
            // the resolution in this way doesn't hurt quality, because we are going
            // to be blurring the bloom images in any case.
            width /= 2;
            height /= 2;

            renderTarget1 = new RenderTarget2D(Game.GraphicsDevice, width, height, true, format, DepthFormat.Depth24);
            renderTarget2 = new RenderTarget2D(Game.GraphicsDevice, width, height, true, format, DepthFormat.Depth24);

            Loaded = true;
        }
Example #34
0
 public void Unload(ContentCache cache)
 {
     Loaded = false;
 }
Example #35
0
        public virtual void Load(ContentCache cache)
        {
            cache.Load(resource, out texture);

            foreach (VideoEffect effect in effects)
            {
                effect.Load(cache);
            }

            Loaded = true;
        }
Example #36
0
        public void Unload(ContentCache cache)
        {
            cache.Unload(@"Models\skydome", out dome);
            cache.Unload(@"Effects\atmosphere", out effect);

            cache.Unload(@"Textures\daysky", out day);
            cache.Unload(@"Textures\sunset", out sunset);
            cache.Unload(@"Textures\nightsky", out night);
        }
Example #37
0
        public virtual void Unload(ContentCache cache)
        {
            Log.Write(this, "Unloading game sky.");

            cache.Unload(resource, out model);

            Loaded = false;
        }
Example #38
0
        public void Unload(ContentCache cache)
        {
            Log.Write(this, "Unloading texture resource for video sprite.");

            cache.Unload(resource, out texture);

            pixelData = null;

            Loaded = false;
        }
Example #39
0
        /// <summary>
        /// Loads graphics for the particle system.
        /// </summary>
        public void Load(ContentCache cache)
        {
            Log.Write(this, "Loading effect resource for the video particle effect.");

            cache.Load(resource, out config);

            particles = new Particle[config.MaxParticles];

            InitializeParticleEffect();

            vertexDeclaration = new VertexDeclaration(Manager.Game.GraphicsDevice,
                                                      Particle.VertexElements);

            // Create a dynamic vertex buffer.
            int size = Particle.SizeInBytes * particles.Length;

            vertexBuffer = new DynamicVertexBuffer(Manager.Game.GraphicsDevice, size,
                                                   BufferUsage.WriteOnly |
                                                   BufferUsage.Points);

            Loaded = true;
        }
Example #40
0
        public virtual void Unload(ContentCache cache)
        {
            Log.Write(this, "Unloading game terrain.");

            cache.Unload(resource, out model);
            heightMap = null;

            Loaded = false;
        }
Example #41
0
        public virtual void Load(ContentCache cache)
        {
            Log.Write(this, "Loading game terrain.");

            cache.Load(resource, out model);

            if (model != null)
            {
                heightMap = model.Tag as TerrainContent;

                if (heightMap == null)
                {
                    string message = "The terrain model did not have a TerrainMap " +
                    "object attached. Are you sure you are using the " +
                    "TerrainProcessor?";
                    throw new InvalidOperationException(message);
                }
            }

            Loaded = true;
        }
Example #42
0
        public virtual void Load(ContentCache cache)
        {
            Log.Write(this, "Loading game sky.");

            cache.Load(resource, out model);

            Loaded = true;
        }
Example #43
0
        public void Unload(ContentCache cache)
        {
            Log.Write(this, "Unloading effect resource for the video particle effect.");

            cache.Unload(resource, out config);
            config = null;
            particles = null;
            vertexDeclaration = null;
            vertexBuffer = null;

            Loaded = false;
        }
Example #44
0
 public void Load(ContentCache cache)
 {
     Loaded = true;
 }
Example #45
0
        public virtual void Unload(ContentCache cache)
        {
            cache.Unload(resource, out texture);

            Loaded = false;
        }
Example #46
0
        public override void Unload(ContentCache cache)
        {
            Log.Write(this, "Unloading model resource for video model.");

            cache.Unload(resource, out model);
        }
Example #47
0
        public void Load(ContentCache cache)
        {
            cache.Load(resource, out font);

            Loaded = true;
        }
Example #48
0
        public void Unload(ContentCache cache)
        {
            cache.Unload(resource, out font);

            Loaded = false;
        }
Example #49
0
        public virtual void Unload(ContentCache cache)
        {
            Log.Write(this, "Unloading game terrain.");

            cache.Unload(modelResource, out model);
            cache.Unload(textureResource, out texture);
            cache.Unload(effectResource, out effect);

            heightMap = null;

            Loaded = false;
        }
Example #50
0
        /// <summary>
        /// Loads the scene's entities into memory.
        /// </summary>
        public void Load(ContentCache cache)
        {
            Log.Write(this, "Loading...");

            foreach (IEngineSprite entity in spriteList)
            {
                game.Sprites.Attach(entity);
                entity.Load(cache);
            }

            foreach (IEngineModel entity in modelList)
            {
                game.Models.Attach(entity);
                entity.Load(cache);
            }

            foreach (IEngineParticle entity in particleList)
            {
                game.Particles.Attach(entity);
                entity.Load(cache);
            }

            // Add all the necessary components to the game engine for drawining the scene.

            if (Sky != null)
            {
                Sky.Load(cache);
                game.Components.Add(Sky);
            }

            if (Terrain != null)
            {
                Terrain.Load(cache);
                game.Components.Add(Terrain);
            }

            game.Components.Add(game.Models);
            game.Components.Add(game.Particles);
            game.Components.Add(game.Sprites);

            if (Bloom != null)
            {
                Bloom.Load(cache);
                game.Components.Add(Bloom);
            }

            Loaded = true;
        }
Example #51
0
        public void Load(ContentCache cache)
        {
            cache.Load (@"Models\skydome", out dome);
            cache.Load (@"Effects\atmosphere", out effect);

            cache.Load (@"Textures\daysky", out day);
            cache.Load (@"Textures\sunset", out sunset);
            cache.Load (@"Textures\nightsky", out night);

            effect.CurrentTechnique = effect.Techniques["SkyDome"];

            foreach (ModelMesh mesh in dome.Meshes)
            {
                foreach (ModelMeshPart part in mesh.MeshParts)
                {
                    part.Effect = effect;
                }
            }

            realTime = true;
        }
Example #52
0
        /// <summary>
        /// Unloads all resources used by this scene's entities.
        /// </summary>
        public void Unload(ContentCache cache)
        {
            Log.Write(this, "Unloading...");

            foreach (IEngineSprite entity in spriteList)
            {
                entity.Unload(cache);
                game.Sprites.Detatch(entity);
            }

            foreach (IEngineModel entity in modelList)
            {
                entity.Unload(cache);
                game.Models.Detatch(entity);
            }

            foreach (IEngineParticle entity in particleList)
            {
                entity.Unload(cache);
                game.Particles.Detatch(entity);
            }

            game.Components.Remove(game.Models);
            game.Components.Remove(game.Particles);
            game.Components.Remove(game.Sprites);

            if (Terrain != null)
            {
                Terrain.Unload(cache);
                game.Components.Remove(Terrain);
            }

            if (Sky != null)
            {
                Sky.Unload(cache);
                game.Components.Remove(Sky);
            }

            if (Bloom != null)
            {
                Bloom.Unload(cache);
                game.Components.Remove(Bloom);
            }

            Loaded = false;
        }
Example #53
0
        public virtual void Load(ContentCache cache)
        {
            Log.Write(this, "Loading game terrain.");

            cache.Load(modelResource, out model);
            cache.Load(textureResource, out texture);
            cache.Load(effectResource, out effect);

            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (ModelMeshPart part in mesh.MeshParts)
                {
                    part.Effect = effect;
                }
            }

            Loaded = true;
        }