Exemplo n.º 1
0
 public void PrintText(Vector3 position)
 {
     LabelDrawing.DrawingPrimitives.Clear();
     LabelDrawing.Print(LabelFont, Text, new Vector3(
                            position.X + (Width / 2), position.Y - 6, 1.0f), QFontAlignment.Centre);
     LabelDrawing.RefreshBuffers();
 }
Exemplo n.º 2
0
        private void UpdateText()
        {
            _fontDrawing.ProjectionMatrix = SceneManager.ScreenCamera.ScreenProjectionMatrix;
            _fontDrawing.DrawingPrimitives.Clear();
            _endGameTextSize = _font.Font.Measure(_endGameText);

            float fontOffset = 0;
            float endOffset  = 0;

            if (_newHighScore)
            {
                fontOffset += _fontDrawing.Print(_font.Font, "New High Score", new Vector3(0, 2.0f * _endGameTextSize.Height, 0), QFontAlignment.Centre, Color.White).Height;
                fontOffset += _fontDrawing.Print(_font.Font, string.Format("Score: {0}", _highestScore.Score.ToString("N0", CultureInfo.CurrentCulture)), new Vector3(0, 0, 0), QFontAlignment.Centre, Color.White).Height;
                fontOffset += _fontDrawing.Print(_font.Font, string.Format("Accuracy: {0}%", _highestScore.Accuracy.ToString("#.##")), new Vector3(0, -_endGameTextSize.Height, 0), QFontAlignment.Centre, Color.White).Height;
                endOffset   = -3.0f * _endGameTextSize.Height;
            }
            else
            {
                fontOffset += _fontDrawing.Print(_font.Font, string.Format("High Score: {0}", _highestScore.Score), new Vector3(0, 2.0f * _endGameTextSize.Height, 0), QFontAlignment.Centre, Color.White).Height;
                fontOffset += _fontDrawing.Print(_font.Font, string.Format("Score: {0}", _newScore.Score.ToString("N0", CultureInfo.CurrentCulture)), new Vector3(0, 0, 0), QFontAlignment.Centre, Color.White).Height;
                fontOffset += _fontDrawing.Print(_font.Font, string.Format("Accuracy: {0}%", _newScore.Accuracy.ToString("#.##")), new Vector3(0, -_endGameTextSize.Height, 0), QFontAlignment.Centre, Color.White).Height;
                endOffset   = -3.0f * _endGameTextSize.Height;
            }
            _fontDrawing.Print(_font.Font, _endGameText, new Vector3(0, -(WindowHeight) / 2.0f + _endGameTextSize.Height + 20, 0), QFontAlignment.Centre, Color.White);
            _fontDrawing.Print(_font.Font, string.Format("{0} - {1}", _stage.CurrentSong.SongBase.Identifier, _stage.CurrentDifficulty), new Vector3(0, (WindowHeight) / 2.0f - 20, 0),
                               new SizeF(WindowWidth * 0.75f, -1), QFontAlignment.Centre, new QFontRenderOptions {
                Colour = Color.White
            });
            _fontDrawing.RefreshBuffers();
        }
Exemplo n.º 3
0
        protected override void OnRenderFrame(FrameEventArgs e)
        {
            // fps
            var now = DateTime.Now;

            if (now - FrameCounterPeriod >= LastFrameCounterUpdate)
            {
                LastFrameCounterUpdate = now;
                LastFrameCounter       = CurrentFrameCounter;
                CurrentFrameCounter    = 0;
            }
            ++CurrentFrameCounter;

            // clear the screen
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            // render the terrain
            TerrainRenderer.Render();

            // render the fps
            FontDrawing.DrawingPrimitives.Clear();
            FontDrawing.Print(MainFont, $"FPS: {LastFrameCounter / FrameCounterPeriod.TotalSeconds:0}",
                              new Vector3(0, Height, 0), QFontAlignment.Left, Color.Black);
            FontDrawing.RefreshBuffers();
            FontDrawing.Draw();

            SwapBuffers();
        }
Exemplo n.º 4
0
        public override void Draw(double time)
        {
            GL.Disable(EnableCap.CullFace);
            _shaderProgram.Bind();
            _shaderProgram.SetUniform("mvp", SceneManager.ScreenCamera.WorldModelViewProjection);
            _shaderProgram.SetUniform("in_color", Color4.White);

            //Draw the player
            _player.Draw(time);

            //Draw the center polygon
            _centerPolygon.Draw(time);

            _shaderProgram.SetUniform("in_color", Color4.Black);
            _centerPolygon.DrawOutline(time);

            //Cleanup the program
            _shaderProgram.UnBind();

            _loadingFontDrawing.DrawingPrimitives.Clear();
            float yOffset = 0;

            yOffset += _loadingFontDrawing.Print(_loadingFont.Font, _loadingText, _loadingTextPosition).Height;
            yOffset  = MathHelper.Clamp(yOffset + 200 - 50 * SceneManager.ScreenCamera.Scale.Y, yOffset, SceneManager.GameWindow.Height * 0.5f);
            var pos = new Vector3(0, -yOffset, 0);

            yOffset += _loadingFontDrawing.Print(_loadingFont.Font, _songText, pos).Height;
            yOffset += _loadingFontDrawing.Print(_loadingFont.Font, _loadingStatus, new Vector3(0, -yOffset, 0), QFontAlignment.Centre).Height;
            _loadingFontDrawing.RefreshBuffers();
            _loadingFontDrawing.Draw();
        }
Exemplo n.º 5
0
        public static void Font_Render()
        {
            string FPS_RenderStr = RealFPS.ToString("0.0");

            FPS_FontDrawing.ProjectionMatrix = FPS_Font_ProjectionMatrix;
            FPS_FontDrawing.DrawingPimitiveses.Clear();
            FPS_FontDrawing.Print(FPS_Font, FPS_RenderStr, new Vector3(7f, Settings.Window.Height - 7f, 0f), QFontAlignment.Left, FPS_Font_Options);
            FPS_FontDrawing.RefreshBuffers();
            FPS_FontDrawing.Draw();
            GL.Disable(EnableCap.Blend);
        }
Exemplo n.º 6
0
        static void OnRenderFrame()
        {
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            drawing.ProjectionMatrix = QFontProjectionMatrix;
            drawing.DrawingPimitiveses.Clear();
            drawing.Print(mainText, "ModernQuickFont", new Vector3(Width / 2, (Height + 56) / 2, 0), QFontAlignment.Centre, mainTextOptions);
            drawing.RefreshBuffers();
            drawing.Draw();
            //GL.Disable(EnableCap.Blend);
        }
Exemplo n.º 7
0
 public override void Update()
 {
     if (UpdateText)
     {
         LabelDrawing.DrawingPrimitives.Clear();
         LabelDrawing.Print(LabelFont, Text, new Vector3(
                                Position.X + (Width / 2), Position.Y, 1.0f), QFontAlignment.Centre);
         LabelDrawing.RefreshBuffers();
         UpdateText = false;
     }
 }
Exemplo n.º 8
0
 public void OnRender()
 {
     if (GameStatus)
     {
         t.Draw();
         c.Draw();
     }
     _drawing.DrawingPrimitives.Clear();
     _drawing.ProjectionMatrix = _projectionMatrix;
     _drawing.Print(_myFont, "SCORE: " + puntuacion.ToString(), new Vector3(Settings.CURRENT_WIN_WIDTH / 2 - 100, Settings.CURRENT_WIN_HEIGHT * 5 / 6, 0), QFontAlignment.Left);
     _drawing.RefreshBuffers();
     _drawing.Draw();
 }
        private void DrawText()
        {
            m_FontDrawing.RefreshBuffers();
            m_FontDrawing.Draw();

            GL.ActiveTexture(TextureUnit.Texture0);
            GL.UseProgram(guiShader.Program);

            GL.BindVertexArray(vao);
            GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);

            m_LastTextureID = -1;
        }
Exemplo n.º 10
0
        private static void DrawHUD()
        {
            drawing.DrawingPrimitives.Clear();
            drawing.ProjectionMatrix = projectionMatrix;

            drawing.Print(
                font,
                "FPS: " + Tools.CalculateFrameRate(),
                new Vector3(-window.Width * 0.9f, window.Height * 0.9f, 0.0f),
                QFontAlignment.Left,
                Color.White
                );

            drawing.RefreshBuffers();
            drawing.Draw();
        }
Exemplo n.º 11
0
        public void Draw(double time)
        {
            StageGeometry.Draw(time);

            MultiplierFontDrawing.DrawingPrimitives.Clear();
            MultiplierFontDrawing.Print(MultiplierFont.Font, _centerText, new Vector3(0, MultiplierFont.Font.Measure("0", QFontAlignment.Centre).Height * 0.5f, 0),
                                        QFontAlignment.Centre, (Color?)StageGeometry.TextColour);
            MultiplierFontDrawing.RefreshBuffers();
            MultiplierFontDrawing.Draw();

            ScoreFontDrawing.DrawingPrimitives.Clear();
            ScoreFontDrawing.Print(MultiplierFont.Font, StageGeometry.Player.Score.ToString("N0", CultureInfo.CurrentCulture), new Vector3(-SceneManager.Width / 2 + 20, SceneManager.Height / 2 - 10, 0),
                                   QFontAlignment.Left, (Color?)StageGeometry.TextColour);
            ScoreFontDrawing.RefreshBuffers();
            ScoreFontDrawing.Draw();
        }
        public void Draw()
        {
            if (IsShowing)
            {
                if (!HasError)//Display normal splashscreen
                {
                    gl.Clear();
                    gl.Disable(EnableCap.DepthTest);

                    _drawing.DrawingPrimitives.Clear();
                    _drawing.ProjectionMatrix = Matrix4.CreateOrthographicOffCenter(Window.Instance.ClientRectangle.X, Window.Instance.ClientRectangle.Width, Window.Instance.ClientRectangle.Y, Window.Instance.ClientRectangle.Height, 0f, 5.0f);
                    _drawing.Print(_font, TextStatus, new Vector3(Window.Instance.Width / 2, Window.Instance.ClientRectangle.Top + 40, 0), new SizeF(Window.Instance.ClientRectangle.Width, Window.Instance.ClientRectangle.Height), QFontAlignment.Centre, RendeTextOption);
                    _drawing.RefreshBuffers();
                    _drawing.Draw();


                    //Draw Image Logo
                    GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);
                    gl.Enable(EnableCap.Blend);

                    GL.BindVertexArray(VAO);
                    GL.BindBuffer(BufferTarget.ElementArrayBuffer, IBO);

                    if (_texture != null)
                    {
                        _texture.Use();
                    }

                    if (_Shader != null)
                    {
                        _Shader.Use();
                    }

                    GL.DrawElements(BeginMode.Triangles, _mesh._indices.Length, DrawElementsType.UnsignedInt, 0);
                    GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
                    GL.BindVertexArray(0);

                    gl.Disable(EnableCap.Blend);
                    gl.Enable(EnableCap.DepthTest);

                    Window.Instance.SwapBuffers();
                }
                else//Display a error screen
                {
                }
            }
        }
Exemplo n.º 13
0
 public void DrawUI()
 {
     if (Engine.Instance != null)
     {
         if (_drawing != null)
         {
             if (_myFont != null)
             {
                 if (RendeTextOption != null)
                 {
                     _drawing.DrawingPrimitives.Clear();
                     _drawing.ProjectionMatrix = Matrix4.CreateOrthographicOffCenter(Engine.Instance.ClientRectangle.X, Engine.Instance.ClientRectangle.Width, Engine.Instance.ClientRectangle.Y, Engine.Instance.ClientRectangle.Height, 0f, 5.0f);
                     _drawing.Print(_myFont, Text, new Vector3(Engine.Instance.Width / 2, Engine.Instance.ClientRectangle.Bottom - 25, 0), new SizeF(Engine.Instance.ClientRectangle.Width, Engine.Instance.ClientRectangle.Height), QFontAlignment.Centre, RendeTextOption);
                     _drawing.RefreshBuffers();
                     _drawing.Draw();
                 }
             }
         }
     }
 }
Exemplo n.º 14
0
        public void RenderText(string text, TFont font, float x, float y)
        {
            drawing.ProjectionMatrix = projectionMatrix;
            drawing.DrawingPrimitives.Clear();

            var qfont = Fonts.ContainsKey(font.Name) ?
                        Fonts[font.Name] :
                        DefaultFonts[TimesNewRoman];

            drawing.Print
            (
                qfont,
                text,
                new Vector3(x, ScreenHeight - y, 0),
                QFontAlignment.Left,
                font.RenderOptions
            );

            drawing.RefreshBuffers();
            drawing.Draw();
        }
Exemplo n.º 15
0
        public override void Draw(double time)
        {
            _shaderProgram.Bind();
            _shaderProgram.SetUniform("mvp", SceneManager.ScreenCamera.WorldModelViewProjection);
            _shaderProgram.SetUniform("in_color", Color4.White);

            //Draw the player
            _player.Draw(time);

            //Draw the center polygon
            _centerPolygon.Draw(time);

            _shaderProgram.SetUniform("in_color", Color4.Black);
            _centerPolygon.DrawOutline(time);

            //Cleanup the program
            _shaderProgram.UnBind();

            _menuFontDrawing.RefreshBuffers();
            _menuFontDrawing.Draw();

            SceneManager.DrawTextLine("TURNT NINJA " + _gameVersion, new Vector3(-WindowWidth / 2 + 5, -WindowHeight / 2 + _versionFont.Font.MaxLineHeight, 0), Color.White, QFontAlignment.Left, _versionFont.Font);
        }
Exemplo n.º 16
0
        protected override void OnRenderFrame(FrameEventArgs e)
        {
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);


            if (Wireframe)
            {
                GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line);
            }
            else
            {
                GL.PolygonMode(MaterialFace.Front, PolygonMode.Fill);
            }

            World.Render(e.Time);

            if (Wireframe)
            {
                GL.PolygonMode(MaterialFace.Front, PolygonMode.Fill);
            }

            fontDrawer.ProjectionMatrix = Matrix4.CreateOrthographic(Width, Height, -1.0f, 1.0f);
            fontDrawer.DrawingPrimitives.Clear();
            fontDrawer.Print(droidSans,
                             $"<X = {World.Player.Position.X}, Y = {World.Player.Position.Y}, Z = {World.Player.Position.Z}>\n" +
                             $"FPS: {Math.Floor(1 / e.Time)}\n" +
                             $"Chunk: {World.Player.ChunkPosition}",
                             new Vector3(-900, 500, 0), QFontAlignment.Left);
            fontDrawer.Print(droidSans,
                             World.ChunkManager.GetDebugString(),
                             new Vector3(600, 500, 0), QFontAlignment.Left);
            fontDrawer.RefreshBuffers();
            fontDrawer.Draw();
            Context.SwapBuffers();

            base.OnRenderFrame(e);
        }
        public override void RenderAfter()
        {
            _drawing.DrawingPrimitives.Clear();
            _drawing.ProjectionMatrix = Matrix4.CreateOrthographicOffCenter(Window.Instance.ClientRectangle.X, Window.Instance.ClientRectangle.Width, Window.Instance.ClientRectangle.Y, Window.Instance.ClientRectangle.Height, 0f, 5.0f);

            RendeTextOption.ClippingRectangle = GetRectangle;


            /*if (Value.Equals(string.Empty))
             * {
             *  if (Time._Time % 60 <= 20 && IsFocused)
             *  {
             *      _drawing.Print(AssetsManager.GetFont(FontName), PlacerHolder + "|", Pos, MaxSize, QFontAlignment.Justify, RendeTextOption);
             *
             *  }
             *  else
             *  {
             *      _drawing.Print(AssetsManager.GetFont(FontName), PlacerHolder + " ", Pos, MaxSize, QFontAlignment.Justify, RendeTextOption);
             *  }
             * }
             * else
             * {
             *  if (Time._Time % 60 <= 20 && IsFocused)
             *  {
             *      _drawing.Print(AssetsManager.GetFont(FontName), Value + "|", Pos, MaxSize, QFontAlignment.Justify, RendeTextOption);
             *
             *  }
             *  else
             *  {
             *      _drawing.Print(AssetsManager.GetFont(FontName), Value + " ", Pos, MaxSize, QFontAlignment.Justify, RendeTextOption);
             *  }
             * }*/

            _drawing.RefreshBuffers();
            _drawing.Draw();
            base.RenderAfter();
        }
Exemplo n.º 18
0
        public ButtonBackup(ShaderProgram program, string text, Color4 colour,
                            int x, int y, int width, int height, int windowWidth, int windowHeight,
                            Matrix4 projection, Func <Task> execDelegate,
                            LayoutAlign layoutAlign = LayoutAlign.TopRight, string fontLocation = "arial")
            : base(program)
        {
            LayoutAlign  = layoutAlign;
            WindowWidth  = windowWidth;
            WindowHeight = windowHeight;
            switch (LayoutAlign)
            {
            case LayoutAlign.TopRight:
                X      = x;
                Y      = WindowHeight - y;
                Width  = width;
                Height = -height;
                break;

            case LayoutAlign.TopLeft:
                X      = WindowWidth - x;
                Y      = WindowHeight - y;
                Width  = width;
                Height = -height;
                break;

            case LayoutAlign.BottomRight:
                X      = x;
                Y      = y;
                Width  = width;
                Height = -height;
                break;

            case LayoutAlign.BottomLeft:
                X      = WindowWidth - x;
                Y      = y;
                Width  = width;
                Height = -height;
                break;

            default:
                X      = x;
                Y      = y;
                Width  = width;
                Height = height;
                break;
            }
            // Create model, then populate button positional data to that model data.
            Vertices = new Vertex[] {
                new Vertex(// Top left
                    new Vector3(X, Y, 0.0f),
                    colour,
                    new Vector2(0.0f, 0.0f)),
                new Vertex(// Top right
                    new Vector3(X + Width, Y, 0.0f),
                    colour,
                    new Vector2(1.0f, 0.0f)),
                new Vertex(// Bottom right
                    new Vector3(X + Width, Y + Height, 0.0f),
                    colour,
                    new Vector2(1.0f, 1.0f)),
                new Vertex(// Bottom left
                    new Vector3(X, Y + Height, 0.0f),
                    colour,
                    new Vector2(0.0f, 1.0f))
            };
            Indices = new int[]
            {
                0, 1, 2,
                0, 3, 2
            };
            Text             = text;
            State            = ButtonState.NotPressed;
            ProjectionMatrix = projection;
            ExecDelegate     = execDelegate;
            // Configure text
            LabelDrawing = new QFontDrawing();
            var builderConfig = new QFontBuilderConfiguration(true)
            {
                ShadowConfig =
                {
                    BlurRadius = 2,
                    BlurPasses = 1,
                    Type       = ShadowType.Blurred
                },
                TextGenerationRenderHint = TextGenerationRenderHint.ClearTypeGridFit,
                Characters = CharacterSet.General | CharacterSet.Japanese | CharacterSet.Thai | CharacterSet.Cyrillic
            };

            LabelFont = new QFont(@"Resources\Fonts\" + fontLocation + ".ttf", 12, builderConfig);
            // Buffer text.
            LabelDrawing.DrawingPrimitives.Clear();
            LabelDrawing.Print(LabelFont, Text,
                               new Vector3(X + (Width / 2), Y, 0.0f),
                               new SizeF(Width, Height), QFontAlignment.Centre, new QFontRenderOptions()
            {
                WordWrap = false
            });
            LabelDrawing.RefreshBuffers();
        }
Exemplo n.º 19
0
        public void Draw(double time)
        {
            _qfontDrawing.DrawingPrimitives.Clear();
            var col = Color4.White;

            if (_fileSystemEntries.Count > 0)
            {
                var s = _selectedFont.Font.Measure(_fileSystemEntries[_directoryBrowserEntryIndex].Name);
                _parentManager.DrawTextLine(_fileSystemEntries[_directoryBrowserEntryIndex].Name, new Vector3(0, s.Height / 2.0f, 0), Color4.White, QFontAlignment.Centre, _selectedFont.Font);

                float startY = _unselectedFont.MaxLineHeight * (_halfEntryDrawCount) + s.Height * 0.5f + _unselectedFont.MaxLineHeight * 0.5f;
                for (int i = _directoryBrowserEntryIndex - (_halfEntryDrawCount); i < _directoryBrowserEntryIndex + _halfEntryDrawCount; i++)
                {
                    if (i >= 0 && i < _fileSystemEntries.Count && i != _directoryBrowserEntryIndex)
                    {
                        _parentManager.DrawTextLine(_fileSystemEntries[i].Name, new Vector3(0, startY, 0), col, QFontAlignment.Centre, _unselectedFont.Font);
                    }
                    if (i == _directoryBrowserEntryIndex)
                    {
                        startY -= s.Height + _unselectedFont.MaxLineHeight * 1.5f;
                    }
                    if (i != _directoryBrowserEntryIndex)
                    {
                        startY -= _unselectedFont.MaxLineHeight;
                    }
                }
            }

            // Draw file systems
            var size = _parentManager.DrawTextLine(_currentFileSystem.FriendlyName, new Vector3(0, (_parentManager.Height / 2), 0), Color4.White, QFontAlignment.Centre, _selectedFont.Font);

            int currentFSIndex = _fileSystemCollection.IndexOf(_currentFileSystem);

            // Draw two file systems on either side
            float unselectedFsScale = 0.9f;

            col   = Color4.White;
            col.A = 1.0f;

            var dp = new QFontDrawingPrimitive(_selectedFont.Font, new QFontRenderOptions {
                Colour = (System.Drawing.Color)col
            });

            // Draw next fs on right
            dp.Print(
                _fileSystemCollection[(currentFSIndex + 1 + _fileSystemCollection.Count) % _fileSystemCollection.Count].FriendlyName,
                Vector3.Zero,
                QFontAlignment.Left);
            dp.ModelViewMatrix = Matrix4.CreateTranslation(new Vector3(0, size.Height * 2.0f, 0))
                                 * Matrix4.CreateScale(unselectedFsScale)
                                 * Matrix4.CreateTranslation(new Vector3(size.Width * 0.75f, _parentManager.Height / 2 - size.Height * 2.0f, 0));

            _qfontDrawing.DrawingPrimitives.Add(dp);

            dp = new QFontDrawingPrimitive(_selectedFont.Font, new QFontRenderOptions {
                Colour = (System.Drawing.Color)col
            });
            // Draw previous fs on left
            dp.Print(
                _fileSystemCollection[(currentFSIndex - 1 + _fileSystemCollection.Count) % _fileSystemCollection.Count].FriendlyName,
                Vector3.Zero,
                QFontAlignment.Right);
            dp.ModelViewMatrix = Matrix4.CreateTranslation(new Vector3(0, size.Height * 2.0f, 0))
                                 * Matrix4.CreateScale(unselectedFsScale)
                                 * Matrix4.CreateTranslation(new Vector3(-size.Width * 0.75f, _parentManager.Height / 2 - size.Height * 2.0f, 0));
            _qfontDrawing.DrawingPrimitives.Add(dp);

            _qfontDrawing.RefreshBuffers();
            _qfontDrawing.Draw();

            var searchString = string.Format("Search: {0}", _searchString);

            _parentManager.DrawTextLine(searchString, new Vector3(0, -(_parentManager.Height / 2) + _searchFont.MaxLineHeight, 0), Color4.White, QuickFont.QFontAlignment.Centre, _searchFont.Font);
        }
Exemplo n.º 20
0
        public override void Draw(double time)
        {
            _optionsDrawing.DrawingPrimitives.Clear();

            float lineStep = Math.Max(_optionsFont.MaxLineHeight, _valueFont.MaxLineHeight);
            float height   = lineStep * _options.Count;

            float currentY             = height / 2.0f;
            float unselectedValueScale = 0.8f;

            foreach (var op in _options)
            {
                var settingColour = Color4.Black;
                if (_options[_currentlySelectedOption] != op)
                {
                    settingColour   = Color.Black;
                    settingColour.A = 0.50f;
                }

                var dp = new QFontDrawingPrimitive(_optionsFont.Font, new QFontRenderOptions {
                    Colour = (Color)settingColour
                });
                dp.Print(op.FriendlyName + ":", Vector3.Zero, QFontAlignment.Centre);
                dp.ModelViewMatrix = Matrix4.CreateTranslation(0, _optionsFont.MaxLineHeight * 0.5f, 0)
                                     * Matrix4.CreateTranslation(-WindowWidth * 0.15f, currentY, 0);
                _optionsDrawing.DrawingPrimitives.Add(dp);

                dp = new QFontDrawingPrimitive(_valueFont.Font, new QFontRenderOptions {
                    Colour = (Color)settingColour
                });
                var valueSize = dp.Print(op.GetValue(), Vector3.Zero, QFontAlignment.Centre);
                dp.ModelViewMatrix = Matrix4.CreateTranslation(0, _valueFont.MaxLineHeight * 0.5f, 0)
                                     * Matrix4.CreateTranslation(WindowWidth * 0.15f, currentY, 0);
                _optionsDrawing.DrawingPrimitives.Add(dp);

                if (op.CanMoveForward())
                {
                    dp = new QFontDrawingPrimitive(_valueFont.Font, new QFontRenderOptions {
                        Colour = (Color)settingColour
                    });
                    dp.Print(op.GetNextValue(), Vector3.Zero, QFontAlignment.Left);
                    dp.ModelViewMatrix = Matrix4.CreateScale(unselectedValueScale)
                                         * Matrix4.CreateTranslation(WindowWidth * 0.15f + valueSize.Width * 1.25f, currentY + _valueFont.Font.MaxLineHeight * 0.5f * unselectedValueScale, 0);
                    _optionsDrawing.DrawingPrimitives.Add(dp);
                }
                if (op.CanMoveBackward())
                {
                    dp = new QFontDrawingPrimitive(_valueFont.Font, new QFontRenderOptions {
                        Colour = (Color)settingColour
                    });
                    dp.Print(op.GetPrevValue(), Vector3.Zero, QFontAlignment.Right);
                    dp.ModelViewMatrix = Matrix4.CreateScale(unselectedValueScale)
                                         * Matrix4.CreateTranslation(WindowWidth * 0.15f - valueSize.Width * 1.25f, currentY + _valueFont.Font.MaxLineHeight * 0.5f * unselectedValueScale, 0);
                    _optionsDrawing.DrawingPrimitives.Add(dp);
                }

                currentY -= lineStep;
            }


            _optionsDrawing.RefreshBuffers();
            _optionsDrawing.Draw();
        }
Exemplo n.º 21
0
        static void OnRenderFrame()
        {
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            drawing.ProjectionMatrix = _projectionMatrix;

            frameCount++;

            float yOffset = 0;

            //mainText.Begin();
            //GL.Begin(BeginMode.Quads);

            //GL.Color3(1.0f, 1.0f, 1.0); GL.Vertex2(0, 0);
            //GL.Color3(0.9f, 0.9f, 0.9f); GL.Vertex2(0, Height);
            //GL.Color3(0.9f, 0.9f, 0.9f); GL.Vertex2(Width, Height);
            //GL.Color3(0.9f, 0.9f, 0.9f); GL.Vertex2(Width, 0);

            //GL.End();
            //mainText.End();
            if (currentDemoPage != _previousPage)
            {
                _previousPage = currentDemoPage;
                // we have to rebuild the stuff
                drawing.DrawingPimitiveses.Clear();

                switch (currentDemoPage)
                {
                case 0:
                {
                    yOffset += drawing.Print(heading1, "ModernQuickFont",
                                             new Vector3((float)Width / 2, Height, 0),
                                             QFontAlignment.Centre, heading1Options).Height;

                    yOffset += drawing.Print(heading2, "Introduction #0",
                                             new Vector3(20, Height - yOffset, 0),
                                             QFontAlignment.Left, heading2Options)
                               .Height;

                    yOffset += drawing.Print(mainText, modernQuickFontIntro, new Vector3(30, Height - yOffset, 0),
                                             new SizeF(Width - 60f, -1), QFontAlignment.Justify).Height;

                    PrintCode(modernIntroCode, ref yOffset);
                    break;
                }

                case 1:
                {
                    yOffset += drawing.Print(heading1, "QuickFont",
                                             new Vector3((float)Width / 2, Height, 0),
                                             QFontAlignment.Centre, heading1Options).Height;

                    yOffset += drawing.Print(heading2, "Introduction",
                                             new Vector3(20, Height - yOffset, 0),
                                             QFontAlignment.Left, heading2Options)
                               .Height;

                    yOffset += 20f;
                    drawing.Print(mainText, introduction, new Vector3(30, Height - yOffset, 0),
                                  new SizeF(Width - 60f, -1), QFontAlignment.Justify);

                    break;
                }

                case 2:
                {
                    yOffset += drawing.Print(heading2, "Easy as ABC!",
                                             new Vector3(20f, Height - yOffset, 0f),
                                             QFontAlignment.Left, heading2Options).Height;

                    PrintComment(usingQuickFontIsSuperEasy, ref yOffset);
                    PrintCode(loadingAFont1, ref yOffset);

                    PrintComment(andPrintWithIt, ref yOffset);
                    PrintCode(printWithFont1, ref yOffset);

                    PrintComment(itIsAlsoEasyToMeasure, ref yOffset);
                    PrintCode(measureText1, ref yOffset);

                    PrintComment(oneOfTheFirstGotchas, ref yOffset);
                    PrintCode(loadingAFont2, ref yOffset);

                    break;
                }

                case 3:
                {
                    yOffset += drawing.Print(heading2, "Alignment", new Vector3(20f, Height - yOffset, 0f),
                                             QFontAlignment.Left, heading2Options).Height;

                    PrintCommentWithLine(whenPrintingText, QFontAlignment.Left, 20f, ref yOffset);
                    PrintCode(printWithFont2, ref yOffset);

                    PrintCommentWithLine(righAlignedText, QFontAlignment.Right, 20f, ref yOffset);
                    yOffset += 10f;

                    PrintCommentWithLine(centredTextAsYou, QFontAlignment.Centre, Width * 0.5f, ref yOffset);

                    break;
                }

                case 4:
                {
                    // in this stage force redraw and recreation of VBO every time: just divert last page
                    _previousPage = -1;
                    yOffset      += drawing.Print(heading2, "Bounds and Justify",
                                                  new Vector3(20f, Height - yOffset, 0f),
                                                  QFontAlignment.Left, heading2Options).Height;

                    yOffset += 20;
                    yOffset += drawing.Print(controlsText, "Press [Up], [Down] or [Enter]!",
                                             new Vector3(Width * 0.5f, Height - yOffset, 0f),
                                             QFontAlignment.Centre, controlsTextOpts).Height;

                    float boundShrink = (int)(350 * (1 - Math.Cos(boundsAnimationCnt * Math.PI * 2)));

                    yOffset += 15;
                    PrintWithBounds(mainText, ofCourseItsNot,
                                    new RectangleF(30f + boundShrink * 0.5f, yOffset, Width - 60 - boundShrink,
                                                   350f), cycleAlignment, ref yOffset);

                    string printWithBounds = "myFont.Print(text, position, maxSize, QFontAlignment." +
                                             cycleAlignment + ");";
                    yOffset += 15f;
                    PrintCode(printWithBounds, ref yOffset);

                    break;
                }

                case 5:
                {
                    yOffset += drawing.Print(heading2, "Your own Texture Fonts",
                                             new Vector3(20f, Height - yOffset, 0f),
                                             QFontAlignment.Left, heading2Options).Height;

                    PrintComment(anotherCoolFeature, ref yOffset);
                    PrintCode(textureFontCode1, ref yOffset);
                    PrintComment(thisWillHaveCreated, ref yOffset);

                    break;
                }

                case 6:
                {
                    yOffset += drawing.Print(heading2, "Your own Texture Fonts",
                                             new Vector3(20f, Height - yOffset, 0f),
                                             QFontAlignment.Left, heading2Options).Height;

                    PrintComment(ifYouDoIntend, ref yOffset);
                    PrintCode(textureFontCode2, ref yOffset);
                    PrintComment(actuallyTexturing, ref yOffset);
                    PrintCode(textureFontCode3, ref yOffset);

                    break;
                }

                case 7:
                {
                    // in this stage force redraw and recreation of VBO every time: just divert last page
                    _previousPage = -1;

                    // store this primitive to remember
                    QFontDrawingPimitive dp = new QFontDrawingPimitive(heading2);
                    dp.Options.DropShadowActive = true;
                    dp.Options.DropShadowOffset = new Vector2(0.1f + 0.2f * (float)Math.Sin(cnt),
                                                              0.1f + 0.2f * (float)Math.Cos(cnt));

                    yOffset += dp.Print("Drop Shadows",
                                        new Vector3(20f, Height - yOffset, 0f),
                                        QFontAlignment.Left).Height;
                    drawing.DrawingPimitiveses.Add(dp);

                    PrintComment(asIhaveleant, ref yOffset);
                    PrintCode(dropShadowCode1, ref yOffset);
                    PrintComment(thisWorksFine, ref yOffset);
                    PrintCode(dropShadowCode2, ref yOffset);
                    PrintComment(onceAFont, ref yOffset);

                    //mainText.Options.DropShadowActive = false;
                    break;
                }

                case 8:
                {
                    yOffset += drawing.Print(heading2, "Monospaced Fonts",
                                             new Vector3(20f, Height - yOffset, 0f),
                                             QFontAlignment.Left, heading2Options).Height;

                    QFontRenderOptions monoSpaceCondensed = monoSpacedOptions.CreateClone();
                    monoSpaceCondensed.CharacterSpacing = 0.05f;
                    PrintComment(monoSpaced, hereIsSomeMono, QFontAlignment.Left, ref yOffset, monoSpaceCondensed);
                    PrintCode(monoCode1, ref yOffset);
                    PrintComment(monoSpaced, theDefaultMono, QFontAlignment.Left, ref yOffset, monoSpaceCondensed);

                    PrintCommentWithLine(monoSpaced, mono, QFontAlignment.Left, 20f, ref yOffset, monoSpaceCondensed);
                    yOffset += 2f;
                    PrintCommentWithLine(monoSpaced, mono, QFontAlignment.Right, 20f, ref yOffset, monoSpaceCondensed);
                    yOffset += 2f;
                    PrintCommentWithLine(monoSpaced, mono, QFontAlignment.Centre, Width * 0.5f, ref yOffset, monoSpaceCondensed);
                    yOffset += 2f;

                    PrintComment(monoSpaced,
                                 "As usual, you can adjust character spacing with myPrimitive.Options.CharacterSpacing.",
                                 QFontAlignment.Left, ref yOffset, monoSpaceCondensed);


                    break;
                }

                case 9:
                {
                    // in this stage force redraw and recreation of VBO every time: just divert last page
                    _previousPage = -1;
                    yOffset      += drawing.Print(heading2, "Preprocessed Text",
                                                  new Vector3(20f, Height - yOffset, 0f),
                                                  QFontAlignment.Left).Height;
                    yOffset += 20f;

                    _stopwatch = Stopwatch.StartNew();
                    yOffset   += drawing.Print(mainText, _processedText,
                                               new Vector3(20, Height - yOffset, 0)).Height;
                    _stopwatch.Stop();
                    long preprocessed = _stopwatch.Elapsed.Ticks;

                    _stopwatch = Stopwatch.StartNew();
                    yOffset   += drawing.Print(mainText, nonPreProcessed,
                                               new Vector3(20, Height - yOffset, 0),
                                               new SizeF(Width - 40f, -1), QFontAlignment.Justify)
                                 .Height;
                    _stopwatch.Stop();
                    long notpreprocessed = _stopwatch.Elapsed.Ticks;

                    if (frameCount > 60)
                    {
                        _benchResult = string.Format(("{0}       {1}\nPreprocessed was {2} ticks faster"),
                                                     preprocessed,
                                                     notpreprocessed, notpreprocessed - preprocessed);
                        frameCount = 0;
                    }

                    drawing.Print(_benchmarkResults, _benchResult,
                                  new Vector3(Width * 0.5f, Height - yOffset, 0),
                                  QFontAlignment.Centre, Color.White);
                    break;
                }

                case 10:
                {
                    yOffset += drawing.Print(heading2, "In Conclusion",
                                             new Vector3(20f, Height - yOffset, 0f),
                                             QFontAlignment.Left, heading2Options).Height;

                    PrintComment(thereAreActually, ref yOffset);

                    break;
                }
                }

                drawing.RefreshBuffers();
            }

            // Create controlsDrawing every time.. would be also good to vary ProjectionMatrix with * Matrix4.CreateTranslation() !
            // this would save buffer work for OpenGL
            controlsDrawing.DrawingPimitiveses.Clear();
            controlsDrawing.ProjectionMatrix = _projectionMatrix;

            if (currentDemoPage != lastPage)
            {
                Vector3 pos = new Vector3(Width - 10 - 16 * (float)(1 + Math.Sin(cnt * 4)),
                                          controlsText.Measure("P").Height + 10f, 0f);
                controlsDrawing.Print(controlsText, "Press [Right] ->", pos, QFontAlignment.Right, controlsTextOpts);
            }

            if (currentDemoPage != 0)
            {
                var pos = new Vector3(10 + 16 * (float)(1 + Math.Sin(cnt * 4)), controlsText.Measure("P").Height + 10f, 0f);
                controlsDrawing.Print(controlsText, "<- Press [Left]", pos, QFontAlignment.Left, controlsTextOpts);
            }
            controlsDrawing.RefreshBuffers();
            controlsDrawing.Draw();

            drawing.Draw();
            //GL.Disable(EnableCap.Blend);
        }
Exemplo n.º 22
0
 public override void OnRender(SceneEntity entity)
 {
     drawing.Print(mainText, processedText, new Vector3(0, 0, 0));
     drawing.RefreshBuffers();
     drawing.Draw();
 }
Exemplo n.º 23
0
        public LabelBackup(ShaderProgram program, string text, Color4 colour, Color4 highlightColour,
                           int x, int y, int width, int height, int windowWidth, int windowHeight,
                           Matrix4 projection,
                           LayoutAlign layoutAlign = LayoutAlign.TopRight, string fontLocation = "arial")
            : base(program)
        {
            LayoutAlign  = layoutAlign;
            WindowWidth  = windowWidth;
            WindowHeight = windowHeight;
            switch (LayoutAlign)
            {
            case LayoutAlign.TopRight:
                Position = new Vector3(x, WindowHeight - y, 0.0f);
                Width    = width;
                Height   = -height;
                break;

            case LayoutAlign.TopLeft:
                Position = new Vector3(WindowWidth - x, WindowHeight - y, 0.0f);
                Width    = width;
                Height   = -height;
                break;

            case LayoutAlign.BottomRight:
                Position = new Vector3(x, y, 0.0f);
                Width    = width;
                Height   = -height;
                break;

            case LayoutAlign.BottomLeft:
                Position = new Vector3(WindowWidth - x, y, 0.0f);
                Width    = width;
                Height   = -height;
                break;

            default:
                Position = new Vector3(x, y, 0.0f);
                Width    = width;
                Height   = height;
                break;
            }
            // Create model, then populate button positional data to that model data.
            Vertices = new Vertex[] {
                new Vertex(// Top left
                    new Vector3(0.0f, 0.0f, 0.0f),
                    colour,
                    new Vector2(0.0f, 0.0f)),
                new Vertex(// Top right
                    new Vector3(Width, 0.0f, 0.0f),
                    colour,
                    new Vector2(1.0f, 0.0f)),
                new Vertex(// Bottom right
                    new Vector3(Width, Height, 0.0f),
                    colour,
                    new Vector2(1.0f, 1.0f)),
                new Vertex(// Bottom left
                    new Vector3(0.0f, Height, 0.0f),
                    colour,
                    new Vector2(0.0f, 1.0f))
            };
            Indices = new int[]
            {
                0, 1, 2,
                0, 3, 2
            };
            float  highlightSize = Height / 10;
            Square centreSquare  = new Square(
                highlightSize,                // The X coord
                highlightSize,                // The Y coord
                Width - (highlightSize / 2),  // The Width
                Height - (highlightSize / 2), // The Height
                colour,                       // The colour of the box
                0);                           // The indexer start point.
            Square topSquare = new Square(
                0.0f,
                0.0f,
                Width - highlightSize,
                highlightSize,
                highlightColour,
                centreSquare.Vertices.Count);
            Square rightSquare = new Square(
                Width - highlightSize,
                0.0f,
                highlightSize,
                Height - highlightSize,
                highlightColour,
                centreSquare.Vertices.Count + topSquare.Vertices.Count);
            Square bottomSquare = new Square(0.0f,
                                             Height - highlightSize,
                                             Width - highlightSize,
                                             highlightSize,
                                             highlightColour,
                                             centreSquare.Vertices.Count + topSquare.Vertices.Count + rightSquare.Vertices.Count);
            Square leftSquare = new Square(0.0f,
                                           highlightSize,
                                           highlightSize,
                                           Height - highlightSize,
                                           highlightColour,
                                           centreSquare.Vertices.Count + topSquare.Vertices.Count + rightSquare.Vertices.Count + bottomSquare.Vertices.Count);

            // Text update
            Text = text;
            // Matrix update
            ProjectionMatrix = projection;
            // Configure text.
            LabelDrawing = new QFontDrawing();
            var builderConfig = new QFontBuilderConfiguration(true)
            {
                ShadowConfig =
                {
                    BlurRadius = 2,
                    BlurPasses = 1,
                    Type       = ShadowType.Blurred
                },
                TextGenerationRenderHint = TextGenerationRenderHint.ClearTypeGridFit,
                Characters = CharacterSet.General | CharacterSet.Japanese | CharacterSet.Thai | CharacterSet.Cyrillic
            };

            LabelFont = new QFont(@"Resources\Fonts\" + fontLocation + ".ttf", 8, builderConfig);
            // Buffer text.
            LabelDrawing.DrawingPrimitives.Clear();
            LabelDrawing.Print(LabelFont, Text, new Vector3(
                                   Position.X + (Width / 2), Position.Y, 1.0f), QFontAlignment.Centre);
            LabelDrawing.RefreshBuffers();
        }
Exemplo n.º 24
0
 public override void Draw(double time)
 {
     _fontDrawing.RefreshBuffers();
     _fontDrawing.Draw();
 }
Exemplo n.º 25
0
        /// <summary>
        /// Called when it is time to render the next frame. Add your rendering code here.
        /// </summary>
        /// <param name="e">Contains timing information.</param>
        protected override void OnRenderFrame(FrameEventArgs e)
        {
            base.OnRenderFrame(e);

            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            _drawing.ProjectionMatrix = _projectionMatrix;

            _frameCount++;

            float yOffset = 0;

            if (_currentDemoPage != _previousPage)
            {
                _previousPage = _currentDemoPage;
                // we have to rebuild the stuff
                _drawing.DrawingPrimitives.Clear();

                switch (_currentDemoPage)
                {
                case 0:
                {
                    yOffset += _drawing.Print(_heading1, "ModernQuickFont",
                                              new Vector3((float)Width / 2, Height, 0),
                                              QFontAlignment.Centre, _heading1Options).Height;

                    yOffset += _drawing.Print(_heading2, "Introduction #0",
                                              new Vector3(20, Height - yOffset, 0),
                                              QFontAlignment.Left, _heading2Options)
                               .Height;

                    yOffset += _drawing.Print(_mainText, _modernQuickFontIntro, new Vector3(30, Height - yOffset, 0),
                                              new SizeF(Width - 60f, -1), QFontAlignment.Left).Height;

                    PrintCode(_modernIntroCode, ref yOffset);
                    break;
                }

                case 1:
                {
                    yOffset += _drawing.Print(_heading1, "QuickFont",
                                              new Vector3((float)Width / 2, Height, 0),
                                              QFontAlignment.Centre, _heading1Options).Height;

                    yOffset += _drawing.Print(_heading2, "Introduction",
                                              new Vector3(20, Height - yOffset, 0),
                                              QFontAlignment.Left, _heading2Options)
                               .Height;

                    yOffset += 20f;
                    _drawing.Print(_mainText, _introduction, new Vector3(30, Height - yOffset, 0),
                                   new SizeF(Width - 60f, -1), QFontAlignment.Justify);

                    break;
                }

                case 2:
                {
                    yOffset += _drawing.Print(_heading2, "Easy as ABC!",
                                              new Vector3(20f, Height - yOffset, 0f),
                                              QFontAlignment.Left, _heading2Options).Height;

                    PrintComment(_usingQuickFontIsSuperEasy, ref yOffset);
                    PrintCode(_loadingAFont1, ref yOffset);

                    PrintComment(_andPrintWithIt, ref yOffset);
                    PrintCode(_printWithFont1, ref yOffset);

                    PrintComment(_itIsAlsoEasyToMeasure, ref yOffset);
                    PrintCode(_measureText1, ref yOffset);

                    PrintComment(oneOfTheFirstGotchas, ref yOffset);
                    PrintCode(_loadingAFont2, ref yOffset);

                    break;
                }

                case 3:
                {
                    yOffset += _drawing.Print(_heading2, "Alignment", new Vector3(20f, Height - yOffset, 0f),
                                              QFontAlignment.Left, _heading2Options).Height;

                    PrintCommentWithLine(_whenPrintingText, QFontAlignment.Left, 20f, ref yOffset);
                    PrintCode(_printWithFont2, ref yOffset);

                    PrintCommentWithLine(_righAlignedText, QFontAlignment.Right, 20f, ref yOffset);
                    yOffset += 10f;

                    PrintCommentWithLine(_centredTextAsYou, QFontAlignment.Centre, Width * 0.5f, ref yOffset);

                    break;
                }

                case 4:
                {
                    // in this stage force redraw and recreation of VBO every time: just divert last page
                    _previousPage = -1;
                    yOffset      += _drawing.Print(_heading2, "Bounds and Justify",
                                                   new Vector3(20f, Height - yOffset, 0f),
                                                   QFontAlignment.Left, _heading2Options).Height;

                    yOffset += 20;
                    yOffset += _drawing.Print(_controlsText, "Press [Up], [Down] or [Enter]!",
                                              new Vector3(Width * 0.5f, Height - yOffset, 0f),
                                              QFontAlignment.Centre, _controlsTextOpts).Height;

                    float boundShrink = (int)(350 * (1 - Math.Cos(_boundsAnimationCnt * Math.PI * 2)));

                    yOffset += 15;
                    PrintWithBounds(_mainText, _ofCourseItsNot,
                                    new RectangleF(30f + boundShrink * 0.5f, yOffset, Width - 60 - boundShrink,
                                                   350f), _cycleAlignment, ref yOffset);

                    string printWithBounds = "myFont.Print(text, position, maxSize, QFontAlignment." +
                                             _cycleAlignment + ");";
                    yOffset += 15f;
                    PrintCode(printWithBounds, ref yOffset);

                    break;
                }

                case 5:
                {
                    yOffset += _drawing.Print(_heading2, "Your own Texture Fonts",
                                              new Vector3(20f, Height - yOffset, 0f),
                                              QFontAlignment.Left, _heading2Options).Height;

                    PrintComment(_anotherCoolFeature, ref yOffset);
                    PrintCode(_textureFontCode1, ref yOffset);
                    PrintComment(_thisWillHaveCreated, ref yOffset);

                    break;
                }

                case 6:
                {
                    yOffset += _drawing.Print(_heading2, "Your own Texture Fonts",
                                              new Vector3(20f, Height - yOffset, 0f),
                                              QFontAlignment.Left, _heading2Options).Height;

                    PrintComment(_ifYouDoIntend, ref yOffset);
                    PrintCode(_textureFontCode2, ref yOffset);
                    PrintComment(_actuallyTexturing, ref yOffset);
                    PrintCode(_textureFontCode3, ref yOffset);

                    break;
                }

                case 7:
                {
                    // in this stage force redraw and recreation of VBO every time: just divert last page
                    _previousPage = -1;

                    // store this primitive to remember
                    QFontDrawingPrimitive dp = new QFontDrawingPrimitive(_heading2)
                    {
                        Options =
                        {
                            DropShadowActive = true,
                            DropShadowOffset = new Vector2(0.1f + 0.2f * (float)Math.Sin(_cnt),
                                                           0.1f + 0.2f * (float)Math.Cos(_cnt))
                        }
                    };

                    yOffset += dp.Print("Drop Shadows",
                                        new Vector3(20f, Height - yOffset, 0f),
                                        QFontAlignment.Left).Height;
                    _drawing.DrawingPrimitives.Add(dp);

                    PrintComment(_asIhaveleant, ref yOffset);
                    PrintCode(_dropShadowCode1, ref yOffset);
                    PrintComment(_thisWorksFine, ref yOffset);
                    PrintCode(_dropShadowCode2, ref yOffset);
                    PrintComment(_onceAFont, ref yOffset);

                    //mainText.Options.DropShadowActive = false;
                    break;
                }

                case 8:
                {
                    yOffset += _drawing.Print(_heading2, "Monospaced Fonts",
                                              new Vector3(20f, Height - yOffset, 0f),
                                              QFontAlignment.Left, _heading2Options).Height;

                    QFontRenderOptions monoSpaceCondensed = _monoSpacedOptions.CreateClone();
                    monoSpaceCondensed.CharacterSpacing = 0.05f;
                    PrintComment(_monoSpaced, _hereIsSomeMono, QFontAlignment.Left, ref yOffset, monoSpaceCondensed);
                    PrintCode(_monoCode1, ref yOffset);
                    PrintComment(_monoSpaced, _theDefaultMono, QFontAlignment.Left, ref yOffset, monoSpaceCondensed);

                    PrintCommentWithLine(_monoSpaced, _mono, QFontAlignment.Left, 20f, ref yOffset, monoSpaceCondensed);
                    yOffset += 2f;
                    PrintCommentWithLine(_monoSpaced, _mono, QFontAlignment.Right, 20f, ref yOffset, monoSpaceCondensed);
                    yOffset += 2f;
                    PrintCommentWithLine(_monoSpaced, _mono, QFontAlignment.Centre, Width * 0.5f, ref yOffset, monoSpaceCondensed);
                    yOffset += 2f;

                    PrintComment(_monoSpaced,
                                 "As usual, you can adjust character spacing with myPrimitive.Options.CharacterSpacing.",
                                 QFontAlignment.Left, ref yOffset, monoSpaceCondensed);


                    break;
                }

                case 9:
                {
                    // in this stage force redraw and recreation of VBO every time: just divert last page
                    _previousPage = -1;
                    yOffset      += _drawing.Print(_heading2, "Preprocessed Text",
                                                   new Vector3(20f, Height - yOffset, 0f),
                                                   QFontAlignment.Left).Height;
                    yOffset += 20f;

                    _stopwatch = Stopwatch.StartNew();
                    yOffset   += _drawing.Print(_mainText, _processedText,
                                                new Vector3(20, Height - yOffset, 0)).Height;
                    _stopwatch.Stop();
                    long preprocessed = _stopwatch.Elapsed.Ticks;

                    _stopwatch = Stopwatch.StartNew();
                    yOffset   += _drawing.Print(_mainText, _nonPreProcessed,
                                                new Vector3(20, Height - yOffset, 0),
                                                new SizeF(Width - 40f, -1), QFontAlignment.Left)
                                 .Height;
                    _stopwatch.Stop();
                    long notpreprocessed = _stopwatch.Elapsed.Ticks;

                    if (_frameCount > 60)
                    {
                        _benchResult = string.Format(("{0}       {1}\nPreprocessed was {2} ticks faster"),
                                                     preprocessed,
                                                     notpreprocessed, notpreprocessed - preprocessed);
                        _frameCount = 0;
                    }

                    _drawing.Print(_benchmarkResults, _benchResult,
                                   new Vector3(Width * 0.5f, Height - yOffset, 0),
                                   QFontAlignment.Centre, Color.White);
                    break;
                }

                case 10:
                {
                    yOffset += _drawing.Print(_heading2, "In Conclusion",
                                              new Vector3(20f, Height - yOffset, 0f),
                                              QFontAlignment.Left, _heading2Options).Height;

                    PrintComment(_thereAreActually, ref yOffset);

                    break;
                }

                case 11:
                {
                    yOffset += _drawing.Print(_heading2, "Different installed fonts",
                                              new Vector3(20f, Height - yOffset, 0f),
                                              QFontAlignment.Left, _heading2Options).Height + 20;

                    foreach (var qFont in _installedFonts)
                    {
                        yOffset += _drawing.Print(qFont, "This text is printed with " + qFont.FontName,
                                                  new Vector3(20f, Height - yOffset, 0), QFontAlignment.Left, Color.White).Height + 10;
                    }

                    break;
                }
                }

                _drawing.RefreshBuffers();
            }

            // Create controlsDrawing every time.. would be also good to vary ProjectionMatrix with * Matrix4.CreateTranslation() !
            // this would save buffer work for OpenGL
            _controlsDrawing.DrawingPrimitives.Clear();
            _controlsDrawing.ProjectionMatrix = _projectionMatrix;

            if (_currentDemoPage != _lastPage)
            {
                var     dim = _controlsText.Measure("Press [Right] ->");
                Vector3 pos = new Vector3(Width - dim.Width / 2 - 16 * (float)(1 + Math.Sin(_cnt * 4)),
                                          _controlsText.Measure("P").Height + 10f, 0f);
                var dp = new QFontDrawingPrimitive(_controlsText, _controlsTextOpts);
                dp.ModelViewMatrix = Matrix4.CreateTranslation(0, dim.Height / 2, 0) * Matrix4.CreateRotationZ((float)MathHelper.DegreesToRadians(Math.Sin(_cnt * 4) * 15)) * Matrix4.CreateTranslation(pos);
                _controlsDrawing.DrawingPrimitives.Add(dp);
                dp.Print("Press [Right] ->", Vector3.Zero, QFontAlignment.Centre);
            }

            if (_currentDemoPage != 0)
            {
                var pos = new Vector3(10 + 16 * (float)(1 + Math.Sin(_cnt * 4)), _controlsText.Measure("P").Height + 10f, 0f);
                _controlsDrawing.Print(_controlsText, "<- Press [Left]", pos, QFontAlignment.Left, _controlsTextOpts);
            }
            _controlsDrawing.RefreshBuffers();
            _controlsDrawing.Draw();

            _drawing.Draw();
            SwapBuffers();
        }
Exemplo n.º 26
0
        /// <summary>
        /// Creates the image on an OpenGL 2D texture and returns it's OpenGL handle.
        /// This function creates and destroys all the OpenGL objects it uses except the texture and framebuffer.
        /// </summary>
        /// <param name="singular">The singular form of the word</param>
        /// <param name="plural">The plural form of the word</param>
        /// <param name="imagePath">The path to the image showing the word to use</param>
        /// <param name="fbo">The framebuffer object that was used to render to the returned texture, still with the texture attached in color0</param>
        /// <param name="WIDTH">The width of the texture</param>
        /// <param name="HEIGHT">The height of the texture</param>
        static int MakeAllImage(String singular, String plural, String imagePath, out int fbo, out int WIDTH, out int HEIGHT)
        {
#if LOG_DATA
            DataLogger.Log("[ImageManager] MakeAllImage was called", LoggingMode.Message);
#endif

            WIDTH = 800;
            GL.Enable(EnableCap.Texture2D);
            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusDstAlpha);

#if LOG_DATA
            DataLogger.Log(String.Concat("[ImageManager] Loading bitmap from \"", imagePath, "\""), LoggingMode.Message);
#endif
            Bitmap bitmap = new Bitmap(imagePath);

            #region CalculateTextColor
#if LOG_DATA
            DataLogger.Log("[ImageManager] Calculating text color", LoggingMode.Message);
#endif
            //calculate whether to make the *noise text* black or white based on the colors on the image.
            float diffX = bitmap.Width / (float)COLOR_CALCULATOR_SAMPLE_FREQ;
            float diffY = bitmap.Height / (float)COLOR_CALCULATOR_SAMPLE_FREQ;

            int grayscaleTotal = 0;
            for (float x = (bitmap.Width - bitmap.Width / COLOR_CALCULATOR_SAMPLE_FREQ * COLOR_CALCULATOR_SAMPLE_FREQ) / 2f; x < bitmap.Width; x += diffX)
            {
                for (float y = (bitmap.Height - bitmap.Height / COLOR_CALCULATOR_SAMPLE_FREQ * COLOR_CALCULATOR_SAMPLE_FREQ) / 2f; y < bitmap.Height; y += diffY)
                {
                    Color c = bitmap.GetPixel((int)x, (int)y);
                    grayscaleTotal += c.R;
                    grayscaleTotal += c.G;
                    grayscaleTotal += c.B;
                }
            }
            bool isBlack = grayscaleTotal / (COLOR_CALCULATOR_SAMPLE_FREQ * COLOR_CALCULATOR_SAMPLE_FREQ * 3) > 127;
#if LOG_DATA
            DataLogger.Log("[ImageManager] Text color: " + (isBlack ? "black" : "white"), LoggingMode.Message);
#endif
            #endregion

            #region LoadQFont
#if LOG_DATA
            DataLogger.Log("[ImageManager] Loading QFont data", LoggingMode.Message);
#endif
            QFontShadowConfiguration shadowConfig = new QFontShadowConfiguration()
            {
                Type       = ShadowType.Expanded,
                BlurRadius = 2,
            };
            QFontBuilderConfiguration qconfig = new QFontBuilderConfiguration(true)
            {
                SuperSampleLevels        = 4,
                TextGenerationRenderHint = TextGenerationRenderHint.AntiAlias,
            };
            QFont              qfont = new QFont(new FreeTypeFont(FONT_LOCATION, 144, FontStyle.Regular), qconfig);
            QFontDrawing       qdraw = new QFontDrawing();
            QFontRenderOptions opts  = new QFontRenderOptions()
            {
                CharacterSpacing = 0.06f,
                Colour           = Color.Black,
            };
            ProcessedText text        = QFontDrawingPrimitive.ProcessText(qfont, opts, plural + " be like", new SizeF(WIDTH - TEXT_BORDER_SPACE * 2, 99999f), QFontAlignment.Left);
            SizeF         topTextSize = qdraw.Print(qfont, text, new Vector3(0, 0, 0), opts);

            qdraw.RefreshBuffers();

            #endregion

            int topHeight = 40 + (int)(topTextSize.Height + 0.5f);
            HEIGHT = WIDTH * bitmap.Height / bitmap.Width + topHeight;

#if LOG_DATA
            DataLogger.Log(String.Concat("[ImageManager] WIDTH=", WIDTH, " HEIGHT=", HEIGHT, " topHeight=", topHeight), LoggingMode.Message);
#endif

            #region GenVBO
#if LOG_DATA
            DataLogger.Log("[ImageManager] Generating VBO and VAO", LoggingMode.Message);
#endif
            float[] vboData = new float[]
            {
                0, 0, 0, 0, 1,
                0, 1, 0, 0, 0,
                1, 0, 0, 1, 1,
                1, 1, 0, 1, 0
            };
            int vbo = GL.GenBuffer();
            GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
            GL.BufferData(BufferTarget.ArrayBuffer, vboData.Length * 4, vboData, BufferUsageHint.StaticDraw);
            int vao = GL.GenVertexArray();
            GL.BindVertexArray(vao);
            GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 20, 0);
            GL.EnableVertexAttribArray(0);
            GL.VertexAttribPointer(1, 2, VertexAttribPointerType.Float, false, 20, 12);
            GL.EnableVertexAttribArray(1);
            #endregion

            #region LoadTexture
#if LOG_DATA
            DataLogger.Log("[ImageManager] Generating texture for image", LoggingMode.Message);
#endif
            int tex = GL.GenTexture();
            GL.ActiveTexture(TextureUnit.Texture0);
            GL.BindTexture(TextureTarget.Texture2D, tex);
#if LOG_DATA
            DataLogger.Log("[ImageManager] Loading texture pixels from bitmap", LoggingMode.Message);
#endif
            BitmapData bits = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bitmap.Width, bitmap.Height, 0, OpenTK.Graphics.OpenGL4.PixelFormat.Bgra, PixelType.UnsignedByte, bits.Scan0);
            bitmap.UnlockBits(bits);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            #endregion

            #region LoadShaderProgram
#if LOG_DATA
            DataLogger.Log("[ImageManager] Creating shaders", LoggingMode.Message);
#endif
            int vs = GL.CreateShader(ShaderType.VertexShader);
#if LOG_DATA
            DataLogger.Log("[ImageManager] Loading vertex shader from " + VERTEX_SHADER_LOCATION, LoggingMode.Message);
#endif
            GL.ShaderSource(vs, File.ReadAllText(VERTEX_SHADER_LOCATION));
            GL.CompileShader(vs);
            int tmp;
            GL.GetShader(vs, ShaderParameter.CompileStatus, out tmp);
#if LOG_DATA
            if (tmp != 1)
            {
                DataLogger.Log("[ImageManager] Vertex shader compilation failed", LoggingMode.Error);
            }
            DataLogger.Log("[ImageManager] Vertex Shader Info Log: ", LoggingMode.Message);
            DataLogger.Log(GL.GetShaderInfoLog(vs), LoggingMode.RawData);
            DataLogger.Log("[ImageManager] [END OF VERTEX SHADER INFO LOG]", LoggingMode.Message);
#endif
            if (tmp != 1)
            {
                throw new Exception("Vertex Shader compilation failed. Process can't continue.");
            }

            int fs = GL.CreateShader(ShaderType.FragmentShader);
#if LOG_DATA
            DataLogger.Log("[ImageManager] Loading fragment shader from " + FRAGMENT_SHADER_LOCATION, LoggingMode.Message);
#endif
            GL.ShaderSource(fs, File.ReadAllText(FRAGMENT_SHADER_LOCATION));
            GL.CompileShader(fs);
            GL.GetShader(fs, ShaderParameter.CompileStatus, out tmp);
#if LOG_DATA
            if (tmp != 1)
            {
                DataLogger.Log("[ImageManager] Fragment shader compilation failed", LoggingMode.Error);
            }
            DataLogger.Log("[ImageManager] Fragment Shader Info Log: ", LoggingMode.Message);
            DataLogger.Log(GL.GetShaderInfoLog(fs), LoggingMode.RawData);
            DataLogger.Log("[ImageManager] [END OF FRAGMENT SHADER INFO LOG]", LoggingMode.Message);
#endif
            if (tmp != 1)
            {
                throw new Exception("Fragment Shader compilation failed. Process can't continue.");
            }

#if LOG_DATA
            DataLogger.Log("[ImageManager] Performing OpenGL program creation commands", LoggingMode.Message);
#endif
            int program = GL.CreateProgram();
            GL.AttachShader(program, vs);
            GL.AttachShader(program, fs);
            GL.BindAttribLocation(program, 0, "vPosition");
            GL.BindAttribLocation(program, 1, "vTexCoords");
            GL.LinkProgram(program);
            GL.DetachShader(program, vs);
            GL.DetachShader(program, fs);
            GL.DeleteProgram(vs);
            GL.DeleteProgram(fs);
            int texUniformLoc  = GL.GetUniformLocation(program, "tex");
            int projUniformLoc = GL.GetUniformLocation(program, "Proj");
            GL.UseProgram(program);
            GL.GetProgram(program, GetProgramParameterName.LinkStatus, out tmp);

#if LOG_DATA
            if (tmp != 1)
            {
                DataLogger.Log("[ImageManager] GL Program linking failed", LoggingMode.Error);
            }
            DataLogger.Log("[ImageManager] GL Program Info Log: ", LoggingMode.Message);
            DataLogger.Log(GL.GetProgramInfoLog(program), LoggingMode.RawData);
            DataLogger.Log("[ImageManager] [END OF GL PROGRAM INFO LOG]", LoggingMode.Message);
            DataLogger.Log("[ImageManager] Just a friendly reminder that GL PROGRAM refers to a OpenGL Shader Program with attached shaders", LoggingMode.Message);
#endif
            if (tmp != 1)
            {
                throw new Exception("Program linking failed. Process can't continue.");
            }
            #endregion

            #region MakeResultTextureFramebuffer
#if LOG_DATA
            DataLogger.Log("[ImageManager] Generating Framebuffer & Texture for rendering", LoggingMode.Message);
#endif
            int resultTex = GL.GenTexture();
            GL.BindTexture(TextureTarget.Texture2D, resultTex);
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, WIDTH, HEIGHT, 0, OpenTK.Graphics.OpenGL4.PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);

            fbo = GL.GenFramebuffer();
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, fbo);
            GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, resultTex, 0);
            if (GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete)
            { //error
#if LOG_DATA
                DataLogger.Log("[ImageManager] Framebuffer creation failed", LoggingMode.Error);
#endif
                throw new Exception("Framebuffer creation failed. Process can't continue.");
            }

            #endregion

            #region Drawing
#if LOG_DATA
            DataLogger.Log("[ImageManager] Performing OpenGL draw commands", LoggingMode.Message);
#endif
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, fbo);
            GL.ClearColor(1f, 1f, 1f, 1f);
            GL.Clear(ClearBufferMask.ColorBufferBit);

            GL.UseProgram(program);
            Matrix4 mat = Matrix4.CreateOrthographicOffCenter(0, 1, 0, 1, -1, 1);
            GL.UniformMatrix4(projUniformLoc, false, ref mat);
            GL.ActiveTexture(TextureUnit.Texture0);
            GL.BindTexture(TextureTarget.Texture2D, tex);
            GL.Uniform1(texUniformLoc, 0);

            GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
            GL.BindVertexArray(vao);
            GL.Viewport(0, 0, WIDTH, HEIGHT - topHeight);
            GL.DrawArrays(PrimitiveType.TriangleStrip, 0, 4);

            GL.Viewport(0, HEIGHT - topHeight, WIDTH, topHeight);
            qdraw.ProjectionMatrix = Matrix4.CreateTranslation(TEXT_BORDER_SPACE, topTextSize.Height + TEXT_BORDER_SPACE, 0) * Matrix4.CreateOrthographicOffCenter(0, WIDTH, 0, topHeight, -1, 1);
            qdraw.Draw();

            GL.Viewport(0, 0, WIDTH, HEIGHT - topHeight);

            opts.DropShadowActive = true;
            opts.DropShadowColour = Color.White;
            opts.DropShadowOffset = Vector2.Zero;//new Vector2(-0.12f, 0.12f);
            text = QFontDrawingPrimitive.ProcessText(qfont, opts, String.Concat("*", singular, " noises*"), new SizeF(WIDTH - TEXT_BORDER_SPACE * 2, 99999f), QFontAlignment.Centre);
            SizeF noiseTextSize = qdraw.Print(qfont, text, new Vector3(0, 0, 0), opts);
            float textScale     = Math.Min((WIDTH - TEXT_BORDER_SPACE * 4) / noiseTextSize.Width, (HEIGHT - TEXT_BORDER_SPACE * 4) / noiseTextSize.Height);

#if LOG_DATA
            DataLogger.Log("[ImageManager] Updating QFont size (disposing and reloading)", LoggingMode.Message);
#endif
            qfont.Dispose();
            qconfig.ShadowConfig = shadowConfig;
            qfont = new QFont(new FreeTypeFont(FONT_LOCATION, 144 * textScale, FontStyle.Regular), qconfig);

            qdraw.DrawingPrimitives.Clear();
            opts.Colour           = isBlack ? Color.Black : Color.White;
            opts.DropShadowColour = isBlack ? Color.White : Color.Black;
            text = QFontDrawingPrimitive.ProcessText(qfont, opts, String.Concat("*", singular, " noises*"), new SizeF(WIDTH - TEXT_BORDER_SPACE * 2, 99999f), QFontAlignment.Centre);
            qdraw.Print(qfont, text, new Vector3(0, 0, 0), opts);
            qdraw.ProjectionMatrix = Matrix4.CreateTranslation(WIDTH / 2f, noiseTextSize.Height * textScale / 2f + (HEIGHT - topHeight) / 2f, 0f) * Matrix4.CreateOrthographicOffCenter(0, WIDTH, 0, HEIGHT - topHeight, -1, 1);
            qdraw.RefreshBuffers();
            qdraw.Draw();
#if LOG_DATA
            DataLogger.Log("[ImageManager] Done drawing", LoggingMode.Success);
#endif
            #endregion

            #region Disposing
#if LOG_DATA
            DataLogger.Log("[ImageManager] Disposing MakeAllImage resources", LoggingMode.Message);
#endif
            bitmap.Dispose();
            qfont.Dispose();
            qdraw.Dispose();

            GL.DeleteProgram(program);
            GL.DeleteTexture(tex);
            GL.DeleteBuffer(vbo);
            GL.DeleteVertexArray(vao);
            #endregion

#if LOG_DATA
            DataLogger.Log("[ImageManager] MakeAllImage is done. Returning texture and framebuffer data", LoggingMode.Message);
#endif
            return(resultTex);
        }