Example #1
0
        /// <summary>
        /// On scene load.
        /// </summary>
        protected override void Load()
        {
            // set assets root and load config
            if (IsFirstScene)
            {
                Assets.AssetsRoot = "../../../../TestAssets";
                Game.LoadConfig("config.ini");
            }

            // load assets
            _cursor    = Assets.LoadImage("gfx/cursor.png", ImageFilterMode.Nearest);
            _treeImage = Assets.LoadImage("gfx/tree.png", ImageFilterMode.Nearest);
            _dirtImage = Assets.LoadImage("gfx/dirt.png", ImageFilterMode.Nearest);
            _font      = Assets.LoadFont("gfx/OpenSans-Regular.ttf", 22, false);
            _fontBig   = Assets.LoadFont("gfx/OpenSans-Regular.ttf", 42, false);

            // get window size
            _windowSize = Gfx.WindowSize;

            // create empty texture to draw on
            _targetTexture = Assets.CreateEmptyImage(_windowSize);

            // create trees
            for (var i = 0; i < 55; ++i)
            {
                CreateTestSprite();
            }

            // sort trees by y position so it will look like there's depth
            _sprites.Sort((Sprite a, Sprite b) => (int)(a.Position.Y - b.Position.Y));
        }
Example #2
0
 public void Draw()
 {
     if (!IsVisible)
     {
         return;
     }
     DX.DrawBox(X - 1, Y - 1, X + Width + 1, Y + Height + 1, WindowBaseColor, DX.TRUE);
     DX.DrawBox(X - 1, Y - 1, X + Width + 1, Y + Height + 1, WindowFrameColor, DX.FALSE);
     ReloadButton.Draw();
     CloseButton.Draw();
     if (!IsHaveInfo)
     {
         FontAsset.Draw(TextFont, "Please Reload",
                        X + Width / 2 - FontAsset.GetDrawTextWidth(TextFont, "Please Reload") / 2,
                        Y + 60, TextColor
                        );
     }
     else if (IsReloading)
     {
         FontAsset.Draw(TextFont, "Loading...",
                        X + Width / 2 - FontAsset.GetDrawTextWidth(TextFont, "Loading...") / 2,
                        Y + 60, TextColor
                        );
     }
     else
     {
         foreach (var button in MatchesListButtons)
         {
             button.Draw();
             button.DrawText();
         }
     }
 }
        internal static void InitializeFontAssetResourceChangeCallBacks()
        {
            FontAsset.RegisterResourceForUpdate   += TextEditorResourceManager.RegisterResourceForUpdate;
            FontAsset.RegisterResourceForReimport += TextEditorResourceManager.RegisterResourceForReimport;
            FontAsset.OnFontAssetTextureChanged   += TextEditorResourceManager.AddTextureToAsset;
            FontAsset.SetAtlasTextureIsReadable   += FontEngineEditorUtilities.SetAtlasTextureIsReadable;
            FontAsset.GetSourceFontRef            += TextEditorResourceManager.GetSourceFontRef;
            FontAsset.SetSourceFontGUID           += TextEditorResourceManager.SetSourceFontGUID;

            // Callback to handle clearing dynamic font asset data when closing the Editor
            EditorApplication.quitting += () =>
            {
                // Find all font assets in the project
                string   searchPattern  = "t:FontAsset";
                string[] fontAssetGUIDs = AssetDatabase.FindAssets(searchPattern);

                for (int i = 0; i < fontAssetGUIDs.Length; i++)
                {
                    string    fontAssetPath = AssetDatabase.GUIDToAssetPath(fontAssetGUIDs[i]);
                    FontAsset fontAsset     = AssetDatabase.LoadAssetAtPath <FontAsset>(fontAssetPath);

                    if (fontAsset != null && (fontAsset.atlasPopulationMode == AtlasPopulationMode.Dynamic || fontAsset.atlasPopulationMode == AtlasPopulationMode.DynamicOS) && fontAsset.clearDynamicDataOnBuild && fontAsset.atlasTexture.width != 0)
                    {
                        fontAsset.ClearFontAssetDataInternal();
                    }
                }
            };
        }
 public void RenderText(IRenderContext context, IEffect effect, IEffectParameterSet effectParameterSet, Matrix matrix,
     string text, FontAsset font, HorizontalAlignment horizontalAlignment = HorizontalAlignment.Left,
     VerticalAlignment verticalAlignment = VerticalAlignment.Top, Color? textColor = null, bool renderShadow = true,
     Color? shadowColor = null)
 {
     throw new NotSupportedException();
 }
        public void OnPreprocessBuild(BuildReport report)
        {
            // Find all font assets in the project
            string searchPattern = "t:FontAsset";

            string[] fontAssetGUIDs = AssetDatabase.FindAssets(searchPattern);

            for (int i = 0; i < fontAssetGUIDs.Length; i++)
            {
                string assetPath = AssetDatabase.GUIDToAssetPath(fontAssetGUIDs[i]);

                // Exclude assets not located in the project.
                if (!assetPath.StartsWith("Assets/", System.StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                FontAsset fontAsset = AssetDatabase.LoadAssetAtPath <FontAsset>(assetPath);

                if (fontAsset != null && (fontAsset.atlasPopulationMode == AtlasPopulationMode.Dynamic || fontAsset.atlasPopulationMode == AtlasPopulationMode.DynamicOS) && fontAsset.clearDynamicDataOnBuild && fontAsset.atlasTexture.width != 0)
                {
                    fontAsset.ClearFontAssetDataInternal();
                }
            }
        }
Example #6
0
        static void ExtractAtlas(MenuCommand command)
        {
            FontAsset font = command.context as FontAsset;

            string fontPath = AssetDatabase.GetAssetPath(font);
            string texPath  = Path.GetDirectoryName(fontPath) + "/" + Path.GetFileNameWithoutExtension(fontPath) + " Atlas.png";

            // Create a Serialized Object of the texture to allow us to make it readable.
            SerializedObject texprop = new SerializedObject(font.material.GetTexture(TextShaderUtilities.ID_MainTex));

            texprop.FindProperty("m_IsReadable").boolValue = true;
            texprop.ApplyModifiedProperties();

            // Create a copy of the texture.
            Texture2D tex = Instantiate(font.material.GetTexture(TextShaderUtilities.ID_MainTex)) as Texture2D;

            // Set the texture to not readable again.
            texprop.FindProperty("m_IsReadable").boolValue = false;
            texprop.ApplyModifiedProperties();

            Debug.Log(texPath);
            // Saving File for Debug
            var pngData = tex.EncodeToPNG();

            File.WriteAllBytes(texPath, pngData);

            AssetDatabase.Refresh();
            DestroyImmediate(tex);
        }
Example #7
0
        public static int AddMaterialReference(Material material, FontAsset fontAsset, MaterialReference[] materialReferences, Dictionary <int, int> materialReferenceIndexLookup)
        {
            int  instanceID = material.GetInstanceID();
            int  count;
            bool flag = materialReferenceIndexLookup.TryGetValue(instanceID, out count);
            int  result;

            if (flag)
            {
                result = count;
            }
            else
            {
                count = materialReferenceIndexLookup.Count;
                materialReferenceIndexLookup[instanceID]    = count;
                materialReferences[count].index             = count;
                materialReferences[count].fontAsset         = fontAsset;
                materialReferences[count].spriteAsset       = null;
                materialReferences[count].material          = material;
                materialReferences[count].isDefaultMaterial = (instanceID == fontAsset.material.GetInstanceID());
                materialReferences[count].referenceCount    = 0;
                result = count;
            }
            return(result);
        }
        /// <summary>
        /// Loads a font asset.
        /// </summary>
        /// <param name="path">Font track path.</param>
        /// <param name="fontSize">Font native size to load.</param>
        /// <param name="useCache">Should we use cache for this asset to make future loadings faster?</param>
        /// <param name="useAssetsRoot">If true, path will be relative to 'AssetsRoot'. If false, will be relative to working directory.</param>
        /// <returns>Loaded font asset.</returns>
        public FontAsset LoadFont(string path, int fontSize, bool useCache = true, bool useAssetsRoot = true)
        {
            var ret = new FontAsset(_BonEngineBind.BON_Assets_LoadFont(ToAssetsPath(path, true, useAssetsRoot), fontSize, useCache));

            ret.Path = path;
            return(ret);
        }
Example #9
0
        /// <summary>
        /// Get the estimated bounding box of a text rendering.
        /// </summary>
        /// <param name="font">Font to use.</param>
        /// <param name="text">Text to draw.</param>
        /// <param name="position">Text position.</param>
        /// <param name="fontSize">Font size.</param>
        /// <param name="maxWidth">Max line width.</param>
        /// <param name="origin">Text origin.</param>
        /// <param name="rotation">Text rotation.</param>
        /// <returns>Estimated text drawing bounding box.</returns>
        public RectangleI GetTextBoundingBox(FontAsset font, string text, PointF position, int fontSize, int maxWidth, PointF origin, float rotation)
        {
            RectangleI ret = new RectangleI();

            _BonEngineBind.BON_Gfx_GetTextBoundingBox(font._handle, text, position.X, position.Y, fontSize, maxWidth, origin.X, origin.Y, rotation, ref ret.X, ref ret.Y, ref ret.Width, ref ret.Height);
            return(ret);
        }
Example #10
0
        public DetectorEntity(WebcamEntity webcamEntity, IAssetManager assetManager, I2DRenderUtilities renderUtilities)
        {
            _webcamEntity    = webcamEntity;
            _assetManager    = assetManager;
            _renderUtilities = renderUtilities;
            _defaultFont     = _assetManager.Get <FontAsset>("font.Default");

            _colorsToDetect = new List <ColorToDetect>
            {
                new ColorToDetect {
                    Color = new Color(1f, 0f, 0f), Name = "Red"
                },
                new ColorToDetect {
                    Color = new Color(0f, 1f, 0f), Name = "Green"
                },
                new ColorToDetect {
                    Color = new Color(0f, 0f, 1f), Name = "Blue"
                },
                new ColorToDetect {
                    Color = new Color(1f, 1f, 0f), Name = "Yellow"
                }
            };

            _currentIndex = 0;
            _currentColor = _colorsToDetect[_currentIndex];

            GlobalSensitivity = 1 / 10000000f * 25f;

            _thread = new Thread(ProcessorThread);
            _thread.IsBackground = true;
            _thread.Start();
        }
        private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
        {
            bool textureImported = false;
            foreach (var asset in importedAssets)
            {
                // Return if imported asset path is outside of the project.
                if (asset.StartsWith("Assets/", StringComparison.OrdinalIgnoreCase) == false)
                    continue;

                Type assetType = AssetDatabase.GetMainAssetTypeAtPath(asset);
                if (assetType == typeof(FontAsset))
                {
                    FontAsset fontAsset = AssetDatabase.LoadAssetAtPath(asset, typeof(FontAsset)) as FontAsset;
                    // Only refresh font asset definition if font asset was previously initialized.
                    if (fontAsset != null && fontAsset.m_CharacterLookupDictionary != null)
                        TextEditorResourceManager.RegisterFontAssetForDefinitionRefresh(fontAsset);
                    continue;
                }

                if (assetType == typeof(Texture2D))
                    textureImported = true;
            }

            // If textures were imported, issue callback to any potential text objects that might require updating.
            if (textureImported)
                TextEventManager.ON_SPRITE_ASSET_PROPERTY_CHANGED(true, null);
        }
Example #12
0
        public IAsset Load(string name, IRawAsset data)
        {
            if (data.IsCompiled)
            {
                return(new FontAsset(this.m_AssetContentManager, name, null, 0, false, 0, data.GetProperty <PlatformData>("PlatformData")));
            }

            PlatformData platformData = null;

            if (data.GetProperty <PlatformData>("PlatformData") != null)
            {
                platformData = new PlatformData
                {
                    Platform = data.GetProperty <PlatformData>("PlatformData").Platform,
                    Data     = ByteReader.ReadAsByteArray(data.GetProperty <PlatformData>("PlatformData").Data)
                };
            }

            var effect = new FontAsset(
                this.m_AssetContentManager,
                name,
                data.GetProperty <string>("FontName"),
                data.GetProperty <int>("FontSize"),
                data.GetProperty <bool>("UseKerning"),
                data.GetProperty <int>("Spacing"),
                platformData);

            return(effect);
        }
Example #13
0
        protected override void RenderContent(RenderComposer composer)
        {
            ImGui.InputInt("Font Size", ref _size);

            if (ImGui.Button("Select Font"))
            {
                var explorer = new FileExplorer <FontAsset>(f => { _font = f; });
                Parent.AddWindow(explorer);
            }

            if (_font == null)
            {
                return;
            }

            ImGui.Text($"Font: {_font.Font.FullName}");
            ImGui.Text($"Asset Name: {_font.Name}");
            if (ImGui.Checkbox("Emotion Renderer", ref _emotionRenderer))
            {
                FontAsset.GlyphRasterizer = _emotionRenderer ? GlyphRasterizer.Emotion : GlyphRasterizer.StbTrueType;
            }
            ImGui.InputTextMultiline("Test Text", ref _testText, 200, new Vector2(200, 100));

            composer.RenderString(new Vector3(0, 100, 0), Color.Black, _testText, _font.GetAtlas(_size));
        }
        public MyGameWorld(
            I2DRenderUtilities renderUtilities,
            IAssetManagerProvider assetManagerProvider,
            IEntityFactory entityFactory)
        {
            this.Entities = new List<IEntity>();

            _renderUtilities = renderUtilities;
            _assetManager = assetManagerProvider.GetAssetManager();
            _defaultFont = this._assetManager.Get<FontAsset>("font.Default");

            // You can also save the entity factory in a field and use it, e.g. in the Update
            // loop or anywhere else in your game.
            var entityA = entityFactory.CreateExampleEntity("EntityA");
            entityA.X = 100;
            entityA.Y = 50;
            var entityB = entityFactory.CreateExampleEntity("EntityB");
            entityB.X = 120;
            entityB.Y = 100;

            // Don't forget to add your entities to the world!
            this.Entities.Add(entityA);
            this.Entities.Add(entityB);

            // This pulls in the texture asset via the asset manager.  Note that
            // the folder seperator from "texture/Player" has been translated
            // into a single dot.
            _playerTexture = _assetManager.Get<TextureAsset>("texture.Player");
        }
Example #15
0
        /// <summary>
        /// Function to add a new material reference and returning its index in the material reference array.
        /// </summary>
        /// <param name="material"></param>
        /// <param name="fontAsset"></param>
        /// <param name="materialReferences"></param>
        /// <param name="materialReferenceIndexLookup"></param>
        /// <returns></returns>
        public static int AddMaterialReference(Material material, FontAsset fontAsset, ref MaterialReference[] materialReferences, Dictionary <int, int> materialReferenceIndexLookup)
        {
            int materialId = material.GetInstanceID();
            int index;

            if (materialReferenceIndexLookup.TryGetValue(materialId, out index))
            {
                return(index);
            }

            index = materialReferenceIndexLookup.Count;

            // Add new reference index
            materialReferenceIndexLookup[materialId] = index;

            if (index >= materialReferences.Length)
            {
                Array.Resize(ref materialReferences, Mathf.NextPowerOfTwo(index + 1));
            }

            materialReferences[index].index             = index;
            materialReferences[index].fontAsset         = fontAsset;
            materialReferences[index].spriteAsset       = null;
            materialReferences[index].material          = material;
            materialReferences[index].isDefaultMaterial = materialId == fontAsset.material.GetInstanceID();
            materialReferences[index].referenceCount    = 0;

            return(index);
        }
Example #16
0
        /// <summary>
        ///
        /// </summary>
        internal static void RebuildFontAssetCache()
        {
            // Iterate over loaded font assets to update affected font assets
            foreach (var pair in s_FontAssetReferences)
            {
                FontAssetRef fontAssetRef = pair.Value;

                FontAsset fontAsset = fontAssetRef.fontAsset;

                if (fontAsset == null)
                {
                    // Remove font asset from our lookup dictionaries
                    s_FontAssetNameReferenceLookup.Remove(fontAssetRef.nameHashCode);
                    s_FontAssetFamilyNameAndStyleReferenceLookup.Remove(fontAssetRef.familyNameAndStyleHashCode);

                    // Add font asset to our removal list
                    s_FontAssetRemovalList.Add(pair.Key);
                    continue;
                }

                fontAsset.InitializeCharacterLookupDictionary();
                fontAsset.AddSynthesizedCharactersAndFaceMetrics();
            }

            // Remove font assets in our removal list from our font asset references
            for (int i = 0; i < s_FontAssetRemovalList.Count; i++)
            {
                s_FontAssetReferences.Remove(s_FontAssetRemovalList[i]);
            }
            s_FontAssetRemovalList.Clear();

            TextEventManager.ON_FONT_PROPERTY_CHANGED(true, null);
        }
Example #17
0
            /// <summary>
            /// Load scene
            /// </summary>
            protected override void Load()
            {
                // set assets root
                Assets.AssetsRoot = "../../../../TestAssets";

                // load config
                Game.LoadConfig("config.ini");

                // load assets
                _cursor  = Assets.LoadImage("gfx/cursor.png", ImageFilterMode.Nearest);
                _fontBig = Assets.LoadFont("gfx/OpenSans-Regular.ttf", 46, false);
                _font    = Assets.LoadFont("gfx/OpenSans-Regular.ttf", 28, false);

                // add demos
                AddDemo("Input & Spritesheet", new Demos.InputAndSpritesheetScene());
                AddDemo("Music & Sound Effects", new Demos.MusicAndSoundScene());
                AddDemo("Drawing Texts", new Demos.TextScene());
                AddDemo("Fullscreen Mode", new Demos.FullscreenScene());
                AddDemo("Windowed Fullscreen", new Demos.WindowedFullscreenScene());
                AddDemo("Rendering Viewport", new Demos.ViewportScene());
                AddDemo("Performance Test", new Demos.PerformanceTestScene());
                AddDemo("Render To Texture", new Demos.RenderToTextureScene());
                AddDemo("Basic Lights", new Demos.BasicLightsScene());
                AddDemo("Custom Managers", new Demos.CustomManagerScene());
                AddDemo("Drawing Shapes", new Demos.DrawingShapesScene());
                AddDemo("UI System", new Demos.UIScene());
            }
Example #18
0
 /// <summary>
 /// 文字列のみ描画する関数(透明度設定なし)
 /// </summary>
 private void DrawTextWithoutMODESETTING()
 {
     if (FontHandle >= 0)
     {
         FontAsset.Draw(FontHandle, Text, TextPosX, TextPosY, TextColor);
     }
 }
Example #19
0
 /// <summary>
 /// テキストのみ描画する
 /// </summary>
 public void DrawText()
 {
     if (FontHandle >= 0)
     {
         FontAsset.Draw(FontHandle, Text, TextPosX, TextPosY, TextColor);
     }
 }
Example #20
0
 /// <summary>
 /// Create a FontDefinition from <see cref="FontAsset"/>.
 /// </summary>
 /// <param name="f">The SDF font to use to display text.</param>
 /// <returns>A new FontDefinition object.</returns>
 public static FontDefinition FromSDFFont(FontAsset f)
 {
     return(new FontDefinition()
     {
         m_FontAsset = f
     });
 }
Example #21
0
        List <FontAsset> loadFonts()
        {
            var fonts = new List <FontAsset>();

            if (!Directory.Exists(metadataPath + "Fonts"))
            {
                Directory.CreateDirectory(metadataPath + "Fonts");
            }

            foreach (var filename in Directory.EnumerateFiles(metadataPath + "Fonts"))
            {
                var metadata = File.ReadAllLines(filename);

                var font = new FontAsset();

                font.Name             = System.IO.Path.GetFileNameWithoutExtension(filename);
                font.Description      = metadata[0].Split('=')[1].Trim();
                font.LastUpdated      = parseLastUpdatedDate(metadata[1].Split('=')[1].Trim(), "font", font.Name);
                font.FontName         = metadata[2].Split('=')[1].Trim();
                font.ImportedFilename = metadata[3].Split('=')[1].Trim();

                fonts.Add(font);
            }

            return(fonts);
        }
        public MyGameWorld(
            I2DRenderUtilities renderUtilities,
            IAssetManagerProvider assetManagerProvider,
            IEntityFactory entityFactory)
        {
            this.Entities = new List <IEntity>();

            _renderUtilities = renderUtilities;
            _assetManager    = assetManagerProvider.GetAssetManager();
            _defaultFont     = this._assetManager.Get <FontAsset>("font.Default");

            // You can also save the entity factory in a field and use it, e.g. in the Update
            // loop or anywhere else in your game.
            var entityA = entityFactory.CreateExampleEntity("EntityA");

            entityA.X = 100;
            entityA.Y = 50;
            var entityB = entityFactory.CreateExampleEntity("EntityB");

            entityB.X = 120;
            entityB.Y = 100;

            // Don't forget to add your entities to the world!
            this.Entities.Add(entityA);
            this.Entities.Add(entityB);

            // This pulls in the texture asset via the asset manager.  Note that
            // the folder seperator from "texture/Player" has been translated
            // into a single dot.
            _playerTexture = _assetManager.Get <TextureAsset>("texture.Player");
        }
Example #23
0
 public DefaultCaptureService(
     I2DRenderUtilities twoDRenderUtilities,
     IAssetManagerProvider assetManagerProvider)
 {
     this.m_2DRenderUtilities = twoDRenderUtilities;
     this.m_DefaultFont = assetManagerProvider.GetAssetManager().Get<FontAsset>("font.Default");
 }
Example #24
0
        internal static Material[] FindMaterialReferences(FontAsset fontAsset)
        {
            List <Material> refs = new List <Material>();
            Material        mat  = fontAsset.material;

            refs.Add(mat);

            // Get materials matching the search pattern.
            string searchPattern = "t:Material" + " " + fontAsset.name.Split(new char[] { ' ' })[0];

            string[] materialAssetGUIDs = AssetDatabase.FindAssets(searchPattern);

            for (int i = 0; i < materialAssetGUIDs.Length; i++)
            {
                string   materialPath   = AssetDatabase.GUIDToAssetPath(materialAssetGUIDs[i]);
                Material targetMaterial = AssetDatabase.LoadAssetAtPath <Material>(materialPath);

                if (targetMaterial.HasProperty(TextShaderUtilities.ID_MainTex) && targetMaterial.GetTexture(TextShaderUtilities.ID_MainTex) != null && mat.GetTexture(TextShaderUtilities.ID_MainTex) != null && targetMaterial.GetTexture(TextShaderUtilities.ID_MainTex).GetInstanceID() == mat.GetTexture(TextShaderUtilities.ID_MainTex).GetInstanceID())
                {
                    if (!refs.Contains(targetMaterial))
                    {
                        refs.Add(targetMaterial);
                    }
                }
                else
                {
                    // TODO: Find a more efficient method to unload resources.
                    //Resources.UnloadAsset(targetMaterial.GetTexture(ShaderUtilities.ID_MainTex));
                }
            }

            return(refs.ToArray());
        }
Example #25
0
        // load the scene
        protected override void Load()
        {
            // load fonts
            _font    = Assets.LoadFont("gfx/OpenSans-Regular.ttf", 22, false);
            _fontBig = Assets.LoadFont("gfx/OpenSans-Regular.ttf", 42, false);

            // set level and starting positions
            _ballPosition.Set(400, 500);
            _ballSpeed.Set(-1f, -0.75f);

            // init player
            var windowSize = Gfx.WindowSize;

            _player = new RectangleF(windowSize.X / 2 - 60, windowSize.Y - 50, 120, 15);

            // init level
            for (int i = 0; i < windowSize.X / BlockSize.X; ++i)
            {
                for (int j = 0; j < 10; ++j)
                {
                    _blocks.Add(new Block()
                    {
                        Rectangle = new RectangleI(i * BlockSize.X, j * BlockSize.Y, BlockSize.X, BlockSize.Y),
                        Color     = new Color(1f - (j / 10f), 0f, (j / 10f) - 1f, 1f)
                    });
                }
            }

            // create empty texture for trail effects
            _trailEffectTexture = Assets.CreateEmptyImage(windowSize);
        }
 public void RenderText(IRenderContext context, Vector2 position, string text, FontAsset font,
     HorizontalAlignment horizontalAlignment = HorizontalAlignment.Left,
     VerticalAlignment verticalAlignment = VerticalAlignment.Top, Color? textColor = null, bool renderShadow = true,
     Color? shadowColor = null)
 {
     throw new NotSupportedException();
 }
Example #27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TextBuffer"/> class.
 /// </summary>
 /// <param name="font">The font to use.</param>
 /// <param name="size">The font size (may be slightly different to the size of <paramref name="font"/>).</param>
 public TextBuffer(FontAsset font, float size)
 {
     SetFont(font, size);
     _kerning      = true;
     _lastTimeUsed = DateTime.MinValue;
     _lastTextSize = new SizeF();
     ResetScrollPosition();
 }
Example #28
0
 public FontAssetRef(int nameHashCode, int familyNameHashCode, int styleNameHashCode, FontAsset fontAsset)
 {
     this.nameHashCode               = nameHashCode;
     this.familyNameHashCode         = familyNameHashCode;
     this.styleNameHashCode          = styleNameHashCode;
     this.familyNameAndStyleHashCode = (long)styleNameHashCode << 32 | (uint)familyNameHashCode;
     this.fontAsset = fontAsset;
 }
Example #29
0
 public StatusBar(
     I2DRenderUtilities twodRenderUtilities,
     IAssetManagerProvider assetManagerProvider)
 {
     this.m_2DRenderUtilities = twodRenderUtilities;
     this.m_AssetManager = assetManagerProvider.GetAssetManager();
     this.m_DefaultFont = this.m_AssetManager.Get<FontAsset>("font.Default");
 }
Example #30
0
 /// <summary>
 /// Draw text on screen.
 /// </summary>
 /// <param name="font">Font to use.</param>
 /// <param name="text">Text to draw.</param>
 /// <param name="position">Text position.</param>
 public void DrawText(FontAsset font, string text, PointF position)
 {
     if (!font.HaveHandle)
     {
         throw new Exception("Tried to render a font without handle!");
     }
     _BonEngineBind.BON_Gfx_DrawText(font._handle, text, position.X, position.Y, 1f, 1f, 1f, 1f, 0, 0, (int)BlendModes.AlphaBlend, 0, 0, 0);
 }
Example #31
0
 /// <summary>
 /// Draw text on screen.
 /// </summary>
 /// <param name="font">Font to use.</param>
 /// <param name="text">Text to draw.</param>
 /// <param name="position">Text position.</param>
 /// <param name="color">Text color.</param>
 /// <param name="fontSize">Font size.</param>
 /// <param name="maxWidth">Max line width.</param>
 /// <param name="blend">Blend mode.</param>
 /// <param name="origin">Text origin.</param>
 /// <param name="rotation">Text rotation.</param>
 public void DrawText(FontAsset font, string text, PointF position, Color color, int fontSize, int maxWidth, BlendModes blend, PointF origin, float rotation)
 {
     if (!font.HaveHandle)
     {
         throw new Exception("Tried to render a font without handle!");
     }
     _BonEngineBind.BON_Gfx_DrawText(font._handle, text, position.X, position.Y, color.R, color.G, color.B, color.A, fontSize, maxWidth, (int)blend, origin.X, origin.Y, rotation);
 }
Example #32
0
 /// <summary>
 /// Draw text on screen.
 /// </summary>
 /// <param name="font">Font to use.</param>
 /// <param name="text">Text to draw.</param>
 /// <param name="position">Text position.</param>
 /// <param name="color">Text color.</param>
 /// <param name="outlineColor">Text outline color.</param>
 /// <param name="outlineWidth">Text outline width.</param>
 /// <param name="fontSize">Font size.</param>
 /// <param name="maxWidth">Max line width.</param>
 /// <param name="blend">Blend mode.</param>
 public void DrawText(FontAsset font, string text, PointF position, Color color, Color outlineColor, int outlineWidth = 1, int fontSize = 0, int maxWidth = 0, BlendModes blend = BlendModes.AlphaBlend)
 {
     if (!font.HaveHandle)
     {
         throw new Exception("Tried to render a font without handle!");
     }
     _BonEngineBind.BON_Gfx_DrawTextWithOutline(font._handle, text, position.X, position.Y, color.R, color.G, color.B, color.A, fontSize, maxWidth, (int)blend, 0, 0, 0, outlineWidth, outlineColor.R, outlineColor.G, outlineColor.B, outlineColor.A);
 }
Example #33
0
 void DisposeFont()
 {
     if (_font != null)
     {
         _font.Deallocated -= DisposeBuffer;
     }
     _font = null;
 }
 public PhysicsMetricsProfilerVisualiser(
     IAssetManagerProvider assetManagerProvider,
     I2DRenderUtilities renderUtilities,
     IPhysicsEngine physicsEngine)
 {
     _renderUtilities = renderUtilities;
     _physicsEngine = physicsEngine;
     _defaultFont = assetManagerProvider.GetAssetManager().Get<FontAsset>("font.Default");
 }
Example #35
0
 public FontAssetRef(int nameHashCode, int familyNameHashCode, int styleNameHashCode, FontAsset fontAsset)
 {
     // Use familyNameHashCode for font assets created at runtime as these asset do not typically have a names.
     this.nameHashCode               = nameHashCode != 0 ? nameHashCode : familyNameHashCode;
     this.familyNameHashCode         = familyNameHashCode;
     this.styleNameHashCode          = styleNameHashCode;
     this.familyNameAndStyleHashCode = (long)styleNameHashCode << 32 | (uint)familyNameHashCode;
     this.fontAsset = fontAsset;
 }
Example #36
0
        static void RegenerateFontAsset(MenuCommand command)
        {
            FontAsset fontAsset = command.context as FontAsset;

            if (fontAsset != null)
            {
                FontAssetCreatorWindow.ShowFontAtlasCreatorWindow(fontAsset);
            }
        }
Example #37
0
        public GeneratedWorld(
            I2DRenderUtilities twoDRenderUtilities,
            IAssetManagerProvider assetManagerProvider)
        {
            this.Entities = new List<IEntity>();

            this.m_2DRenderUtilities = twoDRenderUtilities;
            this.m_AssetManager = assetManagerProvider.GetAssetManager();
            this.m_DefaultFont = this.m_AssetManager.Get<FontAsset>("font.Default");
        }
 public KernelMetricsProfilerVisualiser(
     IKernel kernel,
     IHierarchy hierachy,
     IAssetManagerProvider assetManagerProvider,
     I2DRenderUtilities renderUtilities)
 {
     _kernel = kernel;
     _hierachy = hierachy;
     _renderUtilities = renderUtilities;
     _defaultFont = assetManagerProvider.GetAssetManager().Get<FontAsset>("font.Default");
 }
        public NetworkTrafficProfilerVisualiser(
            IAssetManagerProvider assetManagerProvider,
            INetworkEngine networkEngine,
            I2DRenderUtilities renderUtilities)
        {
            _defaultFont = assetManagerProvider.GetAssetManager().Get<FontAsset>("font.Default");
            _networkEngine = networkEngine;
            _renderUtilities = renderUtilities;

            _sentSampler = new NetworkSampler(_renderUtilities, _defaultFont, "SENT");
            _receivedSampler = new NetworkSampler(_renderUtilities, _defaultFont, "RECV");
        }
Example #40
0
 public TychaiaProfilerEntity(
     TychaiaProfiler profiler,
     I2DRenderUtilities twodRenderUtilities,
     IAssetManagerProvider assetManagerProvider,
     IPersistentStorage persistentStorage)
 {
     this.Profiler = profiler;
     this.m_2DRenderUtilities = twodRenderUtilities;
     this.m_DefaultFontAsset = assetManagerProvider.GetAssetManager().Get<FontAsset>("font.Default");
     this.m_ProfilingInformation = new List<FrameProfileInfo>();
     this.m_PersistentStorage = persistentStorage;
     this.m_TychaiaProfilerEntityUtil = new TychaiaProfilerEntityUtil();
 }
 public GraphicsMetricsProfilerVisualiser(
     IAssetManagerProvider assetManagerProvider,
     I2DRenderUtilities renderUtilities,
     IRenderCache renderCache,
     IRenderAutoCache renderAutoCache,
     IRenderBatcher renderBatcher)
 {
     _renderUtilities = renderUtilities;
     _renderCache = renderCache;
     _renderAutoCache = renderAutoCache;
     _renderBatcher = renderBatcher;
     _defaultFont = assetManagerProvider.GetAssetManager().Get<FontAsset>("font.Default");
 }
Example #42
0
        public LobbyWorld(
            IKernel kernel,
            I2DRenderUtilities twodRenderUtilities,
            IAssetManagerProvider assetManagerProvider, 
            bool join,
            IPAddress address)
        {
            this.m_2DRenderUtilities = twodRenderUtilities;
            this.m_DefaultFont = assetManagerProvider.GetAssetManager().Get<FontAsset>("font.Default");

            this.Entities = new List<IEntity>();

            this.m_NetworkAPI = new DefaultNetworkAPI(join, address);
            kernel.Bind<INetworkAPI>().ToMethod(x => this.m_NetworkAPI);
        }
        public OperationCostProfilerVisualiser(
            IAssetManagerProvider assetManagerProvider,
            I2DRenderUtilities renderUtilities,
            IMemoryProfiler memoryProfiler)
        {
            _defaultFont = assetManagerProvider.GetAssetManager().Get<FontAsset>("font.Default");
            _renderUtilities = renderUtilities;
            _memoryProfiler = memoryProfiler;
            _averageOverTimePeriod = new Dictionary<string, double>();
            _historyOverTimePeriod = new Dictionary<string, List<double>>();
            _lastFrameToHaveData = new Dictionary<string, int>();
            _maximumOverTimePeriod = new Dictionary<string, double>();

            MicrosecondLimit = 14000;
            FramesToAnalyse = 240;
        }
Example #44
0
        public ShipEditorWorld(
            IFactory factory, 
            I2DRenderUtilities twoDRenderUtilities, 
            IAssetManagerProvider assetManagerProvider, 
            IShipTool[] shipTools)
        {
            this.Entities = new List<IEntity>();

            this.m_2DRenderUtilities = twoDRenderUtilities;
            this.m_AssetManager = assetManagerProvider.GetAssetManager();
            this.m_ShipTools = shipTools;
            this.m_DefaultFont = this.m_AssetManager.Get<FontAsset>("font.Default");

            this.m_Ship = factory.CreateShip();

            this.m_ShipEditorEntity = factory.CreateShipEditorEntity(this.m_Ship);

            this.Entities.Add(this.m_ShipEditorEntity);
        }
        public Vector2 MeasureText(IRenderContext context, string text, FontAsset font)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (string.IsNullOrWhiteSpace(text))
            {
                return new Vector2(0, 0);
            }

            if (font == null)
            {
                throw new ArgumentNullException(nameof(font));
            }

            return font.Font.MeasureString(_stringSanitizer.SanitizeCharacters(font.Font, text));
        }
        public GCMetricsProfilerVisualiser(
            IAssetManagerProvider assetManagerProvider,
            I2DRenderUtilities renderUtilities)
        {
            _renderUtilities = renderUtilities;
            _defaultFont = assetManagerProvider.GetAssetManager().Get<FontAsset>("font.Default");

#if PLATFORM_WINDOWS || PLATFORM_MACOS || PLATFORM_LINUX
            string instanceName;
            if (TryGetInstanceName(Process.GetCurrentProcess(), out instanceName))
            {
                _gen0PerformanceCounter = new PerformanceCounter(".NET CLR Memory", "# Gen 0 Collections",
                    instanceName, true);
                _gen1PerformanceCounter = new PerformanceCounter(".NET CLR Memory", "# Gen 1 Collections",
                    instanceName, true);
                _gen2PerformanceCounter = new PerformanceCounter(".NET CLR Memory", "# Gen 2 Collections",
                    instanceName, true);
            }
#endif
        }
Example #47
0
        public MainMenuWorld(IAssetManagerProvider assetManagerProvider, I2DRenderUtilities twodRenderUtilities)
        {
            this.m_2DRenderUtilities = twodRenderUtilities;

            var assetManager = assetManagerProvider.GetAssetManager();

            this.m_RussianLargeFont = assetManager.Get<FontAsset>("font.RussianLarge");
            this.m_RussianMediumFont = assetManager.Get<FontAsset>("font.RussianMedium");

            this.Entities = new IEntity[0];

            this.Actions = new Dictionary<string, Action<IGameContext>>
            {
                { "-Hyperplayer", this.DoHyperplayer },
                { "-Multiplayer", this.DoMultiplayer },
                { "-Singleplayer", this.DoSingleplayer },
                { "Ship editor", this.DoShipEditor },
                { "Quit", this.DoQuit }
            };
        }
Example #48
0
        public MenuWorld(
            I2DRenderUtilities twodRenderUtilities, 
            IAssetManagerProvider assetManagerProvider, 
            IBackgroundCubeEntityFactory backgroundCubeEntityFactory, 
            ISkin skin)
        {
            this.m_2DRenderUtilities = twodRenderUtilities;
            this.AssetManager = assetManagerProvider.GetAssetManager();
            this.m_BackgroundCubeEntityFactory = backgroundCubeEntityFactory;
            this.m_TitleFont = this.AssetManager.Get<FontAsset>("font.Title");
            this.m_PlayerModel = this.AssetManager.Get<ModelAsset>("model.Character");
            this.m_PlayerModelTexture = this.AssetManager.Get<TextureAsset>("model.CharacterTex");

            this.Entities = new List<IEntity>();

            this.m_CanvasEntity = new CanvasEntity(skin) { Canvas = new Canvas() };
            this.m_CanvasEntity.Canvas.SetChild(this.m_TitleMenu = new TitleMenu());

            // Don't add the canvas to the entities list; that way we can explicitly
            // order it's depth.
        }
        public IntermissionWorld(
            IKernel kernel,
            INetworkAPI networkAPI,
            I2DRenderUtilities twodRenderUtilities,
            IAssetManagerProvider assetManagerProvider, 
            int level)
        {
            this.m_2DRenderUtilities = twodRenderUtilities;
            this.m_MessageFont = assetManagerProvider.GetAssetManager().Get<FontAsset>("font.Message");
            this.m_NetworkAPI = networkAPI;

            this.Entities = new List<IEntity>();

            this.m_Ticks = 0;
            this.m_ApproachingLevel = level;

            this.m_NetworkAPI.ClearAllListeners();

            this.m_NoNextLevel =
                (assetManagerProvider.GetAssetManager().TryGet<LevelAsset>("level." + level + "a") == null);
        }
Example #50
0
        public ShipEditorEntity(
            IAssetManagerProvider assetManagerProvider,
            I2DRenderUtilities twoRenderUtilities,
            I3DRenderUtilities threeRenderUtilities,
            IGridRenderer gridRenderer, 
            ICollision collision,
            Ship ship)
        {
            this.m_DefaultFont = assetManagerProvider.GetAssetManager().Get<FontAsset>("font.Default");
            this.m_2DRenderUtilities = twoRenderUtilities;
            this.m_3DRenderUtilities = threeRenderUtilities;
            this.m_GridRenderer = gridRenderer;
            this.m_Collision = collision;
            this.m_Ship = ship;

            this.m_PreviewRotation = 0;

            this.HorizontalRange = 30;
            this.VerticalRange = 30;
            this.VerticalSelection = 3;

            this.UpdateShipVisibilityCull();
        }
        public DetectorEntity(WebcamEntity webcamEntity, IAssetManager assetManager, I2DRenderUtilities renderUtilities)
        {
            _webcamEntity = webcamEntity;
            _assetManager = assetManager;
            _renderUtilities = renderUtilities;
            _defaultFont = _assetManager.Get<FontAsset>("font.Default");

            _colorsToDetect = new List<ColorToDetect>
            {
                new ColorToDetect {Color = new Color(1f, 0f, 0f), Name = "Red"},
                new ColorToDetect {Color = new Color(0f, 1f, 0f), Name = "Green"},
                new ColorToDetect {Color = new Color(0f, 0f, 1f), Name = "Blue"},
                new ColorToDetect {Color = new Color(1f, 1f, 0f), Name = "Yellow"}
            };

            _currentIndex = 0;
            _currentColor = _colorsToDetect[_currentIndex];

            GlobalSensitivity = 1/10000000f*25f;

            _thread = new Thread(ProcessorThread);
            _thread.IsBackground = true;
            _thread.Start();
        }
        public PROJECT_SAFE_NAMEWorld(
            INode worldNode,
            IHierarchy hierarchy,
            I2DRenderUtilities twoDRenderUtilities,
            IAssetManagerProvider assetManagerProvider,
            IEntityFactory entityFactory)
        {
            this.Entities = new List<IEntity>();

            _renderUtilities = twoDRenderUtilities;
            _assetManager = assetManagerProvider.GetAssetManager();
            _defaultFont = this._assetManager.Get<FontAsset>("font.Default");

            // You can also save the entity factory in a field and use it, e.g. in the Update
            // loop or anywhere else in your game.
            var entityA = entityFactory.CreateExampleEntity("EntityA");
            entityA.Transform.LocalPosition = new Vector3(100, 50, 0);
            var entityB = entityFactory.CreateExampleEntity("EntityB");
            entityB.Transform.LocalPosition = new Vector3(120, 100, 0);

            // Don't forget to add your entities to the world!
            hierarchy.MoveNode(worldNode, hierarchy.Lookup(entityA));
            hierarchy.MoveNode(worldNode, hierarchy.Lookup(entityB));
        }
        public BoardAnalyzerEntity(
            DetectorEntity detectorEntity, 
            TextBox pointThresholdTextBox, 
            TextBox minNumberOfPointsTextBox, 
            TextBox maxNumberOfPointsTextBox, 
            I2DRenderUtilities renderUtilities,
            IAssetManager assetManager)
        {
            _detectorEntity = detectorEntity;
            _pointThresholdTextBox = pointThresholdTextBox;
            _minNumberOfPointsTextBox = minNumberOfPointsTextBox;
            _maxNumberOfPointsTextBox = maxNumberOfPointsTextBox;
            _renderUtilities = renderUtilities;

            _pointThresholdTextBox.Text = _pointThreshold.ToString();
            _minNumberOfPointsTextBox.Text = _minNumberOfPoints.ToString();
            _maxNumberOfPointsTextBox.Text = _maxNumberOfPoints.ToString();

            _defaultFont = assetManager.Get<FontAsset>("font.Default");

            _thread = new Thread(Run);
            _thread.IsBackground = true;
            _thread.Start();
        }
Example #54
0
        public ConnectWorld(
            IKernel kernel, 
            I2DRenderUtilities twodRenderUtilities, 
            IAssetManagerProvider assetManagerProvider, 
            IBackgroundCubeEntityFactory backgroundCubeEntityFactory, 
            ISkin skin, 
            IProfiler profiler,
            IPersistentStorage persistentStorage,
            bool startServer, 
            IPAddress address, 
            int port)
            : base(twodRenderUtilities, assetManagerProvider, backgroundCubeEntityFactory, skin)
        {
            this.m_2DRenderUtilities = twodRenderUtilities;
            this.m_PersistentStorage = persistentStorage;

            this.m_DefaultFont = assetManagerProvider.GetAssetManager().Get<FontAsset>("font.Default");
            this.m_Address = address;
            this.m_Port = port;
            TychaiaClient client = null;
            byte[] initial = null;
            Action cleanup = () =>
            {
                kernel.Unbind<INetworkAPI>();
                kernel.Unbind<IClientNetworkAPI>();
                if (client != null)
                {
                    client.Close();
                }

                this.TerminateExistingProcess();
            };

            if (startServer)
            {
                this.m_Actions = new Action[]
                {
                    () => this.m_Message = "Closing old process...", () => this.TerminateExistingProcess(),
                    () => this.m_Message = "Starting server...", () => this.StartServer(),
                    () => this.m_Message = "Creating client...", () => client = new TychaiaClient(port + 2, port + 3),
                    () => client.AttachProfiler(profiler),
                    () => this.m_Message = "Connecting to server...",
                    () => client.Connect(new DualIPEndPoint(address, port, port + 1)),
                    () => this.m_Message = "Binding node to kernel...",
                    () => kernel.Bind<INetworkAPI>().ToMethod(x => client),
                    () => kernel.Bind<IClientNetworkAPI>().ToMethod(x => client), () => this.m_Message = "Joining game...",
                    () => this.m_UniqueClientIdentifier = this.JoinGame(client), () => this.m_Message = "Retrieving initial game state...",
                    () => initial = client.LoadInitialState(), () => this.m_Message = "Starting client...",
                    () => this.m_PerformFinalAction = true
                };
            }
            else
            {
                this.m_Actions = new Action[]
                {
                    () => this.m_Message = "Creating client...", () => client = new TychaiaClient(port + 2, port + 3),
                    () => client.AttachProfiler(profiler),
                    () => this.m_Message = "Connecting to server...",
                    () => client.Connect(new DualIPEndPoint(address, port, port + 1)),
                    () => this.m_Message = "Binding node to kernel...",
                    () => kernel.Bind<INetworkAPI>().ToMethod(x => client),
                    () => kernel.Bind<IClientNetworkAPI>().ToMethod(x => client),
                    () => this.m_Message = "Joining game...",
                    () => this.m_UniqueClientIdentifier = this.JoinGame(client), () => this.m_Message = "Retrieving initial game state...",
                    () => initial = client.LoadInitialState(), () => this.m_Message = "Starting client...",
                    () => this.m_PerformFinalAction = true
                };
            }

            this.m_FinalAction =
                () =>
                this.TargetWorld =
                this.GameContext.CreateWorld<IWorldFactory>(x => x.CreateTychaiaGameWorld(this.m_UniqueClientIdentifier, cleanup));

            var thread = new Thread(this.Run) { IsBackground = true };
            thread.Start();

            AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
            {
                if (this.m_Process != null)
                {
                    try
                    {
                        this.m_Process.Kill();
                        this.m_Process = null;
                    }
                    catch (InvalidOperationException)
                    {
                    }
                }
            };
            AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
            {
                if (this.m_Process != null)
                {
                    try
                    {
                        this.m_Process.Kill();
                        this.m_Process = null;
                    }
                    catch (InvalidOperationException)
                    {
                    }
                }
            };
        }
        public void RenderText(
            IRenderContext context, 
            Vector2 position, 
            string text, 
            FontAsset font, 
            HorizontalAlignment horizontalAlignment = HorizontalAlignment.Left, 
            VerticalAlignment verticalAlignment = VerticalAlignment.Top, 
            Color? textColor = null, 
            bool renderShadow = true, 
            Color? shadowColor = null)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (string.IsNullOrWhiteSpace(text))
            {
                return;
            }

            if (font == null)
            {
                throw new ArgumentNullException(nameof(font));
            }

            if (textColor == null)
            {
                textColor = Color.White;
            }

            if (shadowColor == null)
            {
                shadowColor = Color.Black;
            }

            if (font.Font == null)
            {
                throw new AssetNotCompiledException(font.Name);
            }

            // Sanitize the text.
            text = _stringSanitizer.SanitizeCharacters(font.Font, text);

            // Determine position to draw.
            var size = font.Font.MeasureString(text);
            float xx = 0, yy = 0;
            switch (horizontalAlignment)
            {
                case HorizontalAlignment.Left:
                    xx = position.X;
                    break;
                case HorizontalAlignment.Center:
                    xx = position.X - (size.X / 2);
                    break;
                case HorizontalAlignment.Right:
                    xx = position.X - size.X;
                    break;
            }

            switch (verticalAlignment)
            {
                case VerticalAlignment.Top:
                    yy = position.Y;
                    break;
                case VerticalAlignment.Center:
                    yy = position.Y - (size.Y / 2);
                    break;
                case VerticalAlignment.Bottom:
                    yy = position.Y - size.Y;
                    break;
            }

            // Normalize location to prevent blurring artifacts.
            xx = (int)xx;
            yy = (int)yy;

            // Draw shadow if required.
            if (renderShadow)
            {
                context.SpriteBatch.DrawString(font.Font, text, new Vector2(xx + 1, yy + 1), shadowColor.Value);
            }

            // Render the main text.
            context.SpriteBatch.DrawString(font.Font, text, new Vector2(xx, yy), textColor.Value);
        }
        /// <summary>
        /// The render text.
        /// </summary>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <param name="matrix">
        /// The matrix.
        /// </param>
        /// <param name="text">
        /// The text.
        /// </param>
        /// <param name="font">
        /// The font.
        /// </param>
        /// <param name="horizontalAlignment">
        /// The horizontal alignment.
        /// </param>
        /// <param name="verticalAlignment">
        /// The vertical alignment.
        /// </param>
        /// <param name="textColor">
        /// The text color.
        /// </param>
        /// <param name="renderShadow">
        /// The render shadow.
        /// </param>
        /// <param name="shadowColor">
        /// The shadow color.
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// </exception>
        public void RenderText(
            IRenderContext context, 
            Matrix matrix, 
            string text, 
            FontAsset font, 
            HorizontalAlignment horizontalAlignment = HorizontalAlignment.Left, 
            VerticalAlignment verticalAlignment = VerticalAlignment.Top, 
            Color? textColor = null, 
            bool renderShadow = true, 
            Color? shadowColor = null)
        {
            if (!context.Is3DContext)
            {
                throw new InvalidOperationException("Can't use 3D rendering utilities in 2D context.");
            }

            var targets = context.GraphicsDevice.GetRenderTargets();
            var size = this.MeasureText(context, text, font);

            var temporary = new RenderTarget2D(
                context.GraphicsDevice,
                (int)size.X,
                (int)size.Y,
                false,
                SurfaceFormat.Color,
                DepthFormat.None,
                0,
                RenderTargetUsage.DiscardContents);
            context.GraphicsDevice.SetRenderTarget(temporary);
            context.GraphicsDevice.Clear(Color.Transparent);

            using (var spriteBatch = new SpriteBatch(context.GraphicsDevice))
            {
                this.m_2DRenderUtilities.RenderText(
                    context,
                    new Vector2(0, 0),
                    text,
                    font,
                    HorizontalAlignment.Left,
                    VerticalAlignment.Top,
                    textColor,
                    renderShadow,
                    shadowColor);
                spriteBatch.End();
            }

            var texture = (Texture2D)temporary;
            context.GraphicsDevice.SetRenderTarget(null);

            context.GraphicsDevice.BlendState = BlendState.Opaque;
            context.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            context.GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;
            context.GraphicsDevice.RasterizerState = RasterizerState.CullNone;

            this.RenderTexture(context, matrix, texture, Color.White, flipHorizontally: false, flipVertically: false);
        }
 /// <summary>
 /// The measure text.
 /// </summary>
 /// <param name="context">
 /// The context.
 /// </param>
 /// <param name="text">
 /// The text.
 /// </param>
 /// <param name="font">
 /// The font.
 /// </param>
 /// <returns>
 /// The <see cref="Vector2"/>.
 /// </returns>
 public Vector2 MeasureText(IRenderContext context, string text, FontAsset font)
 {
     return this.m_2DRenderUtilities.MeasureText(context, text, font);
 }
Example #58
0
 void DisposeFont()
 {
   if (_font != null)
     _font.Deallocated -= DisposeBuffer;
   _font = null;
 }
Example #59
0
        public TychaiaGameWorld(
            IAssetManagerProvider assetManagerProvider, 
            I3DRenderUtilities threedRenderUtilities, 
            IFilteredFeatures filteredFeatures, 
            IChunkOctreeFactory chunkOctreeFactory, 
            IIsometricCameraFactory isometricCameraFactory, 
            IChunkSizePolicy chunkSizePolicy, 
            IChunkManagerEntityFactory chunkManagerEntityFactory, 
            IProfiler profiler, 
            IConsole console, 
            ILevelAPI levelAPI /* temporary */, 
            IGameUIFactory gameUIFactory, 
            I2DRenderUtilities twodRenderUtilities,
            IClientNetworkAPI networkAPI,
            IEntityFactory entityFactory,
            IChunkConverter chunkConverter,
            IChunkCompressor chunkCompressor,
            IChunkGenerator chunkGenerator,
            ITerrainSurfaceCalculator terrainSurfaceCalculator,
            int uniqueClientIdentifier,
            Action cleanup,
            IViewportMode viewportMode)
        {
            this.m_3DRenderUtilities = threedRenderUtilities;
            this.m_FilteredFeatures = filteredFeatures;
            this.m_ChunkSizePolicy = chunkSizePolicy;
            this.m_Profiler = profiler;
            this.m_Console = console;
            this.m_2DRenderUtilities = twodRenderUtilities;
            this.m_NetworkAPI = networkAPI;
            this.m_EntityFactory = entityFactory;
            this.m_ChunkConverter = chunkConverter;
            this.m_ChunkCompressor = chunkCompressor;
            this.m_ChunkGenerator = chunkGenerator;
            this.m_TerrainSurfaceCalculator = terrainSurfaceCalculator;
            this.m_UniqueClientIdentifier = uniqueClientIdentifier;
            this.m_AssetManagerProvider = assetManagerProvider;
            this.m_Cleanup = cleanup;
            this.Level = levelAPI.NewLevel("test");
            this.m_ViewportMode = viewportMode;

            this.m_DefaultFontAsset = this.m_AssetManagerProvider.GetAssetManager().Get<FontAsset>("font.Default");

            this.ChunkOctree = chunkOctreeFactory.CreateChunkOctree<ClientChunk>();
            var chunk = new ClientChunk(0, 0, 0);
            this.IsometricCamera = isometricCameraFactory.CreateIsometricCamera(this.ChunkOctree, chunk);
            this.m_ChunkManagerEntity = chunkManagerEntityFactory.CreateChunkManagerEntity(this);

            this.m_InventoryUIEntity = gameUIFactory.CreateInventoryUIEntity();
            this.Entities = new List<IEntity> { this.m_ChunkManagerEntity, this.m_InventoryUIEntity };

            // TODO: Move this somewhere better.
            this.m_NetworkAPI.ListenForMessage(
                "player update",
                (client, data) =>
                {
                    var playerState = InMemorySerializer.Deserialize<PlayerServerEntity.PlayerServerState>(data);

                    // Lookup the player entity for this unique client ID if we have one.
                    var player =
                        this.Entities.OfType<PlayerEntity>()
                            .FirstOrDefault(x => x.RuntimeData.UniqueClientIdentifier == playerState.UniqueClientID);

                    if (player == null)
                    {
                        // Need to create a new player entity.
                        player =
                            this.m_EntityFactory.CreatePlayerEntity(
                                new Player { UniqueClientIdentifier = playerState.UniqueClientID });
                        this.Entities.Add(player);
                    }

                    player.X = playerState.X;
                    player.Y = playerState.Y;
                    player.Z = playerState.Z;
                });

            // TODO: Move this somewhere better.
            this.m_NetworkAPI.ListenForMessage(
                "player leave",
                (client, data) =>
                {
                    var playerState = InMemorySerializer.Deserialize<PlayerServerEntity.PlayerServerState>(data);

                    // Lookup the player entity for this unique client ID if we have one.
                    var player =
                        this.Entities.OfType<PlayerEntity>()
                            .FirstOrDefault(x => x.RuntimeData.UniqueClientIdentifier == playerState.UniqueClientID);

                    // If we have a player entity, remove it from the world.
                    if (player != null)
                    {
                        this.Entities.Remove(player);
                    }
                });

            // TODO: Move this somewhere better.
            this.m_NetworkAPI.ListenForMessage(
                "chunk available",
                (client, data) =>
                {
                    var dataChunk = this.m_ChunkCompressor.Decompress(data);

                    var clientChunk = this.ChunkOctree.Get(dataChunk.X, dataChunk.Y, dataChunk.Z);
                    if (clientChunk == null)
                    {
                        clientChunk = new ClientChunk(dataChunk.X, dataChunk.Y, dataChunk.Z);
                        this.ChunkOctree.Set(clientChunk);
                    }
                    else if (clientChunk.Generated)
                    {
                        // TODO: We already have this chunk.  The server shouldn't announce it to
                        // us because we've already had it sent before, but at the moment the server
                        // doesn't track this.  We just ignore it for now (so we don't recompute
                        // graphics data).
                        Console.WriteLine("Chunk is marked as generated, will not reload from server");
                        return;
                    }

                    this.m_ChunkConverter.FromChunk(dataChunk, clientChunk);

                    this.m_ChunkGenerator.Generate(clientChunk);
                });
        }
 public Vector2 MeasureText(IRenderContext context, string text, FontAsset font)
 {
     return _twoDimensionalRenderUtilities.MeasureText(context, text, font);
 }