Giter VIP home page Giter VIP logo

quickfont's Introduction

QuickFont Join the chat at https://gitter.im/opcon/QuickFont Build Status Build status NuGet

A modern OpenGL text rendering library for OpenTK.

Forked from swax/QuickFont library. Original Library QFont

You can install this library via nuget.

Supported Platforms

QuickFont has been tested and runs on Windows, Linux and OSX.

The minimum supported OpenGL version is 3.0

Note the example project will need to be changed to build correctly on OSX, since by default Apple returns an OpenGL 2.1 context if a specific version is not specified.

Simply replace the Game.cs constructor with:

public Game()
	: base(800, 600, GraphicsMode.Default, "QuickFont Example", GameWindowFlags.Default, DisplayDevice.Default, 3, 2, GraphicsContextFlags.Default)

This will select an OpenGL version >= 3.2 (usually 4.1).

Changelog

Latest Release - Version 4.5

  • Update to OpenTK 3.1
  • Add FAKE build script
  • Support loading FreeType fonts from memory

Previous Releases:

Version 4.4

  • Updated to OpenTK 2.0 and SharpFont 4.0.1
  • Added fallback to builtin kerning if font file does not have any
  • Switch to using paket for dependency management rather than nuget
  • Added OSX and Linux continuous integration through travis-ci
  • Added a custom view-model-matrix to QFontDrawingPrimitive which allows for some fun effects - see Example
  • Improved inbuilt documentation

Version 4.3

  • Kerning information is now loaded from FreeType if FreeTypeFont is used
  • Improved built in kerning method to account for pixels on glyph boundary
  • Fixes to example project
  • Improved overall code quality
    • Renamed variables to a consistent naming scheme
    • Added XML documentation to all public facing classes, methods, fields, properties, etc.
    • Added lots of XML documentation to internal/private classes, methods, fields, properties etc
  • Fixed QFontDrawing not implementing IDisposable
  • Improved disposing in QVertexArrayObject

Version 4.2

  • Switched to using a shared package to build QuickFont
  • Added an OpenGL ES 2.0 nuget package

Version 4.1

  • Updated font loading mechanism to use SharpFont for loading fonts by path, and use the regular GDIFont mechanism for loading installed (system) fonts
  • Updated example project to show some different installed system fonts

Version 4.0

  • Now uses SharpFont for loading the font files, so custom (non-installed) fonts are now supported on Linux and OSX
  • Added Nuget package
  • Added support for OpenGL ES (requires conditional compilation) thanks to vescon
  • Improved Shader loading
  • Cross-platform support (tested on Windows 10, Ubuntu 15.10, OSX 10.11,10.10)
  • Unicode support
  • Example is working again
  • Updated to latest OpenTK nuget package (OpenTK.Next)

Todo

  • Maybe extract all Print methods in a static class to leave QFontDrawingPrimitive more basic.
  • Right to Left text flow support (arabic, hebrew)
  • Unicode zero spacing eg. combining character support
  • On-the-fly character addition (If a character can not be found, add it, regenerate the font)

Screenshot

Example

In some OnLoad() method create your QFont and your QFontDrawing

_myFont = new QFont("Fonts/HappySans.ttf", 72, new QFontBuilderConfiguration(true));
_myFont2 = new QFont("basics.qfont", new QFontBuilderConfiguration(true));
_drawing = new QFontDrawing();

Call some print methods or create Drawing primitives by themselves. Add them to the drawing.

_drawing.DrawingPrimitives.Clear();
_drawing.Print(_myFont, "text1", pos, FontAlignment.Left);

// draw with options
var textOpts = new QFontRenderOptions()
    {
	Colour = Color.FromArgb(new Color4(0.8f, 0.1f, 0.1f, 1.0f).ToArgb()),
	DropShadowActive = true
	};
SizeF size = _drawing.Print(_myFont, "text2", pos2, FontAlignment.Left, textOpts);

var dp = new QFontDrawingPrimitive(_myFont2);
size = dp.Print(text, new Vector3(bounds.X, Height - yOffset, 0), new SizeF(maxWidth, float.MaxValue), alignment);
drawing.DrawingPrimitives.Add(dp);

// after all changes do update buffer data and extend it's size if needed.
_drawing.RefreshBuffers();

Then in your draw loop do:

_drawing.ProjectionMatrix = proj;
_drawing.Draw();
SwapBuffers();

At the end of the program dispose the QuickFont resources:

protected virtual void Dispose(bool disposing)
{
	_drawing.Dispose();
	_myFont.Dispose();
	_myFont2.Dispose();
}

See the included example project for more!

Contributors

The following is a non-exhaustive list of people who have contributed to QuickFont:

James Lohr - Creator of the original library (http://www.opentk.com/project/QuickFont)

John (swax) Marshall - Added vertex buffer support

Patrick (opcon) Yates - Current maintainer

Robertofon - Refactored monolithic QFont class

Martinay - OpenGL ES 2.0 support

Jan Polak

Jonathan

License

Licensed under MIT, please see the file License.txt in the project root directory

quickfont's People

Contributors

forki avatar gitter-badger avatar hughph avatar livila avatar martinay avatar opcon avatar swax avatar szymski avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

quickfont's Issues

DLL Exceptions when loading a TTF font

So, when using new QFont(...) I get "DLL freetype6 not found", or after some manipulations I get this:
System.BadImageFormatException: "Была сделана попытка загрузить программу, имеющую неверный формат. (0x8007000B)"
like "An attempt was made to load an incorrect format program"

code:
_myFont = new QFont("Fonts\\ARIAL.TTF", 72, new QFontBuilderConfiguration(true)); _drawing = new QFontDrawing();
full stack:
Unhandled exception. System.BadImageFormatException: Была сделана попытка загрузить программу, имеющую неверный формат. (0x8007000B) at SharpFont.FT.FT_Init_FreeType(IntPtr& alibrary) at SharpFont.Library..ctor() at QuickFont.FreeTypeFont..ctor(String fontPath, Single size, FontStyle style, Int32 superSampleLevels, Single scale) at QuickFont.QFont.GetFont(String fontPath, Single size, FontStyle style, Int32 superSampleLevels, Single scale) at QuickFont.QFont..ctor(String fontPath, Single size, QFontBuilderConfiguration config, FontStyle style) at SparkEngine.Program.OnLoad() in C:\Users\DimucaTheDev\source\repos\SparkEngine\Program.cs:line 316 at OpenTK.Windowing.Desktop.GameWindow.Run() at SparkEngine.Program.Run() in C:\Users\DimucaTheDev\source\repos\SparkEngine\Program.cs:line 231 at SparkEngine.Program.Main(String[] args_) in C:\Users\DimucaTheDev\source\repos\SparkEngine\Program.cs:line 192

Windows 11, NET 8
OpenTK, using Wayfinder.Quickfont nuget packet, latest version
Debug, X64
VC++ installed(2022)

tried to compile freetype6 myself, but i dunno how to get DLL instead of LIB

Crash

I am trying to use this nice project but get a "BadImageFormatException" right away.

Directly by calling "new QFont(font, size, new QFontBuilderConfiguration(true))"

How show graph and text on GLControl ?

I want to show a rectangle and some text on a GLControl panel,but it doesn't work,the panel only show the text. What should I do to slove it?

`//图形
GL.Disable(EnableCap.Texture2D);
GL.Color3(Color.Black);
GL.Begin(BeginMode.LineLoop);
GL.Vertex2(300, 100);
GL.Vertex2(300, 50);
GL.Vertex2(400, 50);
GL.Vertex2(400, 100);
GL.End();

qfont = new QFont("C:\Windows\Fonts\tahoma.ttf", 50, new QuickFont.Configuration.QFontBuilderConfiguration(true));
qdraw = new QFontDrawing();
qdraw.ProjectionMatrix = _projectionMatrix;
QFontRenderOptions textOpts;
textOpts = new QFontRenderOptions()
{
Colour = Color.Red, //Color.DarkRed, etc
DropShadowActive = false
};
qdraw.DrawingPrimitives.Clear();
qdraw.Print(qfont, "Hello world", new Vector3(100f,100f,0f), QFontAlignment.Left,textOpts);
qdraw.RefreshBuffers();
qdraw.Draw();
//Add this
qdraw.DisableShader();

glControl1.SwapBuffers();`

Variable size font

Hello, not sure if here is the best place to ask this, but is there any way to make the font scale according to it's bounding box?

Switch to using a FAKE build script

This will improve the creation of nuget packages and allow us to produce strong-name signed ones in conjunction with un-strong-name signed ones

How are fonts scaled

How are fonts scaled? I don't see a mechanism for scaling the font size. When I added some scaling to the modelView matrix of a primitive, it translated as well as scaled the font. I'm not really sure why, there doesn't to be anything funky going on in the vertex shader. I can't modify the texture coordinates, as this obviously messes up the entire scheme, since all of the bimaps are located in one giant texture.

Problem using quickfont in immediate mode application.

Hello,

I have been working on porting an old c application to c#. The application uses opengl to render some graphics in what I understand to be called immediate mode. (I'm clearly inexperienced with opengl). I'm trying to get a 1 to 1 port going before I make broad changes, but I do have to replace the font rendering code. I thought to use quickfont and running through the examples I got it to display text in the application. Unfortunately as soon as I draw text the immediate mode graphics that come afterward are no longer visible on the screen. I cannot figure out what I'm doing that causes this. Might be obvious to people accustomed to opengl, but that's not me :)

I made the test code below to show my problem. The first quad renders and the second does not unless I comment out the qfont code.

Hope someone can point met in the correct direction.

This is on .net Core 2.0 using a quickfont lib modified to work with that (using system.drawing compat library and removing the GDI stuff.

static void Main(string[] args)
        {
            // Workarround for current directory being the project folder not the debug folder.
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));

            INativeWindow window = new NativeWindow(
                640,
                480,
                "TestApp",
                GameWindowFlags.Default,
                GraphicsMode.Default,
                DisplayDevice.Default);
            window.Visible = true;
            
            IGraphicsContext context = new GraphicsContext(GraphicsMode.Default, window.WindowInfo);
            context.MakeCurrent(window.WindowInfo);
            (context as IGraphicsContextInternal).LoadAll();

            GL.ClearColor(Color4.Purple);
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            // This quad shows
            GL.Begin(PrimitiveType.Quads);

            GL.Color3(Color.Red);
            GL.Vertex2(0, 0);
            GL.Color3(Color.Blue);
            GL.Vertex2(0.9f, 0);
            GL.Color3(Color.Orange);
            GL.Vertex2(1, -0.9f);
            GL.Color3(Color.Green);
            GL.Vertex2(0, -1);

            GL.End();

            Matrix4 projectionMatrix = Matrix4.CreateOrthographicOffCenter(0, 640, 0, 480, -1.0f, 1.0f);

            // this text shows
            QFont font = new QFont(@"test_condensed_regular.ttf", 72, new QuickFont.Configuration.QFontBuilderConfiguration(true));
            QFontDrawing loadingText = new QFontDrawing();
            loadingText.Print(font, "Testing..", new Vector3(100, 300, 0), QFontAlignment.Left, new QFontRenderOptions() { Colour = (Color)new Color4(0.8f, 0.1f, 0.1f, 1.0f) });

            loadingText.RefreshBuffers();
            loadingText.ProjectionMatrix = projectionMatrix;
            loadingText.Draw();

            // This quad does not show unless I comment out the QFont code
            GL.Begin(PrimitiveType.Quads);

            GL.Color3(Color.Red);
            GL.Vertex2(0, 0);
            GL.Color3(Color.Blue);
            GL.Vertex2(0, 0.9f);
            GL.Color3(Color.Orange);
            GL.Vertex2(-0.9f, 1);
            GL.Color3(Color.Green);
            GL.Vertex2(-1, 0);

            GL.End();


            context.SwapBuffers();

            Console.WriteLine("Hello World!");
            Console.ReadKey();
        }

Use better kerning information

Since the font files contain kerning information, we should probably use that instead of calculating our own.

This should be possible to do relatively easily with SharpFont, however it will only be implemented for loading font paths (which go through FreeTypeFont).

It won't work for system (installed) fonts since they are loaded through GDIFont and don't expose kerning information. If there was a cross-platform way to get the path to the font file then it would be possible to load them using FreeTypeFont instead, but I don't think a way exists.

Maintaining same size for the text

I am creating a CAD-like application. In the application, there needs to be numbers near a scale. I need the numbers to have always the same (screen) size independent of the current zoom. It uses a orthographic projection in this way CreateOrthographic(WindowWidth / ZoomScale, WindowHeight / ZoomScale, ZNear, ZFar); I set the matrix to the QFontDrawing.ProjectionMatrix. But now the text also gets scaled when the user zooms in. Is there a built-in way how to do this? Or do I have to do it myself using some matrix-magic?

Inlcuded Examples do not work, some form of Documentation required

The provided Examples in the Readme do not work. In addition to containing multiple spelling mistakes (such as "DrawingPimitiveses" instead of "DrawingPrimitives"), it contains multiple variables not mentioned or explained anywhere else. I tried replacing these variables with values that seem resonable to me however it does not work.

The included "Example" Folder is also not very useable in my opinion. In addition to the massive amount of different strings and other variables whose purpose is rather unclear to someone not familiar with this code, that hideous switch absolutely needs to go.

I think some sort of Documentation or Starter Guide is necessary.

Using Quickfont in drawing environment

Hello,

Thanks a lot for the Quickfont library. It helps me a lot.

I have some problems to embed Quickfont into an existing drawing context where lines an rectangles are drawn.

Every time I draw text like in the example all the other drawing primitives like lines and rectangles go away.

Here is my sample code (in the drawing routine):

QFont _myFont = null;

public void render()
{
         if (_myFont == null)
           {
                    QFontBuilderConfiguration fontConfig = new QFontBuilderConfiguration(false);

                    _myFont = new QFont(@"C:\Windows\Fonts\arial.ttf", 6, fontConfig);
                    _fontDrawing = new QFontDrawing();
         
                    // it does not matter if this part is inside the if section or not
                    _fontDrawing.DrawingPrimitives.Clear();
                    _fontDrawing.Print(_myFont, "This is my test text!", new Vector3(200, 200, 0), QFontAlignment.Left);
                    _fontDrawing.RefreshBuffers();
                }
  
 GL.Viewport(0, 0, (int)m_Viewport.GetDx(), (int)m_Viewport.GetDy());
  GL.Clear(ClearBufferMask.ColorBufferBit);
 GL.ClearColor(OpenTK.Graphics.Color4.CornflowerBlue);
 GL.Disable(EnableCap.Texture2D);

  // As a test just drawing a simple line over the screen             
  GL.MatrixMode(MatrixMode.Projection);
  GL.LoadIdentity();

  int dx1 = (int)m_Viewport.GetDx();
  if (dx1 < 1) dx1 = 1;
  int dy1 = (int)m_Viewport.GetDy();
  if (dy1 < 1) dy1 = 1;
  GL.Ortho(0, dx1, dy1, 0, 0.0f, 100.0f);

  GL.MatrixMode(MatrixMode.Modelview);
  GL.LoadIdentity();

  // this line is not visible :(
  GL.Color4(1.0, 0.0, 1.0, 1.0);
  GL.LineWidth(8.0f);
  GL.Begin(BeginMode.Lines);
  GL.Vertex3(100.0f, 100.0f, 0.0f);
  GL.Vertex3(1000.0f, 600.0f, 0.0f);
  GL.End();

  GL.Enable(EnableCap.Texture2D);
  _fontDrawing.VertexArrayObject.EnableAttributes();
  _fontDrawing.ProjectionMatrix = Matrix4.CreateOrthographicOffCenter(0, (int)m_Viewport.GetDx(), 0, 
  (int)m_Viewport.GetDy(), 0.0f, 100.0f);
   _fontDrawing.Draw();

  SwapBuffers();
}

I found out that it has something to do when the Shading is enabled. What is the best way to do this? Did I forget something.

Thanks alot for any help.

Best regards

Happe

Chinese font seams doesn't work

thank you for your quickfont library!It makes me easier to complete the task.
Nowadays,I copy Sh0rti's code for test. It can normally display opentk window.
but when I modify the text by chinese character.It does't work, the window display the background color.
how can I do to display chinese character in opentk window?

Update to OpenTK 3.0.1

In OpenTK 3.0.1 the signature of GL.BlendFunc changed. The enums are BlendFactor instead of BlendFactorSrc and BlendFactor instead of BlendFactorDest

Update the call QFontDrawing accordingly:

if (_useDefaultBlendFunction)
            {
                GL.Enable(EnableCap.Blend);
                GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);
            }

Stop using System.Drawing

The System.Drawing namespace always causes problems with Mono, and while QuickFont works okay now, it is a good idea to move away from System.Drawing altogether.

The following is a list of ways System.Drawing is used in the current codebase, and a replacement:

Use Alternative
Bitmap manipulation ImageSharp, a cross-platform image manipulation library. Still in early alpha, but probably usable enough.
Size/Rectangle/Point structs Can just implement these as standalone structs - see OpenTK
Text Rendering hints for bitmaps Not sure if this is needed or will make a difference
Converting SharpFont FTBitmaps to GDIBitmaps Can replace this conversion mechanism with one using ImageSharp
Loading fonts in the GDIFont class No alternative, this method of loading uses System.Drawing specifically for loading the fonts and so will be removed along with System.Drawing
Color class/list OpenTK has Color4, could use that instead. What does ImageSharp use?
Font Style Can create a simple enumeration for this
Brushes Can probably use ImageSharp

Is it possible to support Chinese rendering?

Hi,
This is a wonderful library. I want use it to render Chinese. But it seems characterset don't containt chinese.
So is it possible to support chinese characterset ?
Thanks.

Library can only be disposed once per application instance

I am trying to use this library in an application that allows the user to (repeatedly) open and close an OpenTK window. When the window closed the OpenTK and QuickFont are disposed. The second time the window is created the library fails to render properly because 'SharedState' is pointing to disposed resources. I did a quick fix locally to publicly expose the setter on QFontDrawing SharedState property. When disposing of QuickFont I also set _drawing.SharedState to null. This resolved my issue but perhaps there is a more elegant fix. If this change would be accepted I can send a merge request.

Font rendering technique description in README

It's probably worth explaining what font rendering technique you use (and perhaps why this approach was chosen) in the README.

From what I can gather it seems to be traditional rasterization, rather than SDF or more obscure vector techniques.

Null Reference exception when loading fonts on OSX/Linux

Mono's MeasureString library does not return a very good estimate of the actual string size, which means that when the glyphs are measured precisely, the size is larger than the MeasureString size. This leads to glyphs not fitting on the texture page when they are packed, and so they are never assigned.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.