diff --git a/examples/go.mod b/examples/go.mod index e1f47a1f..948c9e4f 100644 --- a/examples/go.mod +++ b/examples/go.mod @@ -21,5 +21,6 @@ require ( require ( github.com/ebitengine/purego v0.7.1 // indirect + golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 // indirect golang.org/x/sys v0.20.0 // indirect ) diff --git a/examples/go.sum b/examples/go.sum index 19ef93f4..ed625b8d 100644 --- a/examples/go.sum +++ b/examples/go.sum @@ -4,5 +4,7 @@ github.com/jakecoffman/cp v1.2.1 h1:zkhc2Gpo9l4NLUZfeG3j33+3bQD7MkqPa+n5PdX+5mI= github.com/jakecoffman/cp v1.2.1/go.mod h1:JjY/Fp6d8E1CHnu74gWNnU0+b9VzEdUVPoJxg2PsTQg= github.com/neguse/go-box2d-lite v0.0.0-20170921151050-5d8ed9b7272b h1:+67TGbwfgeB5o03Rx+ZBW44zAQ+wUujcwdRA0p9CbJI= github.com/neguse/go-box2d-lite v0.0.0-20170921151050-5d8ed9b7272b/go.mod h1:kvKwD9codtns5mvpA53V3vLnqFb/Ahcu8zgkGM0SIbI= +golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 h1:vr/HnozRka3pE4EsMEg1lgkXJkTFJCVUX+S/ZT6wYzM= +golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842/go.mod h1:XtvwrStGgqGPLc4cjQfWqZHG1YFdYs6swckp8vpsjnc= golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= diff --git a/examples/text/font_sdf/AnonymousPro-Bold.ttf b/examples/text/font_sdf/AnonymousPro-Bold.ttf new file mode 100644 index 00000000..f14c18c1 Binary files /dev/null and b/examples/text/font_sdf/AnonymousPro-Bold.ttf differ diff --git a/examples/text/font_sdf/OFL.txt b/examples/text/font_sdf/OFL.txt new file mode 100644 index 00000000..45b11f5b --- /dev/null +++ b/examples/text/font_sdf/OFL.txt @@ -0,0 +1,94 @@ +Copyright (c) 2009, Mark Simonson (http://www.ms-studio.com, mark@marksimonson.com), +with Reserved Font Name Anonymous Pro. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/examples/text/font_sdf/main.go b/examples/text/font_sdf/main.go new file mode 100644 index 00000000..a6265125 --- /dev/null +++ b/examples/text/font_sdf/main.go @@ -0,0 +1,106 @@ +package main + +import ( + _ "embed" + "fmt" + "unsafe" + + rl "github.com/gen2brain/raylib-go/raylib" +) + +//go:embed AnonymousPro-Bold.ttf +var fileData []byte + +func main() { + // Initialization + const screenWidth, screenHeight = 800, 450 + rl.InitWindow(screenWidth, screenHeight, "raylib [text] example - SDF fonts") + defer rl.CloseWindow() // Close window and OpenGL context + + // NOTE: Textures/Fonts MUST be loaded after Window initialization (OpenGL context is required) + + const msg = "Signed Distance Fields" + + // Default font generation from TTF font + fontDefault := rl.Font{BaseSize: 16, CharsCount: 95} + defer rl.UnloadFont(fontDefault) // Default font unloading + + // Loading font data from memory data + // Parameters > font size: 16, no glyphs array provided (nil), glyphs count: 95 (autogenerate chars array) + glyphs := rl.LoadFontData(fileData, 16, nil, 95, rl.FontDefault) + fontDefault.Chars = &glyphs[0] + + // Parameters > font size: 16, glyphs padding in image: 4 px, pack method: 0 (default) + atlas := rl.GenImageFontAtlas(unsafe.Slice(fontDefault.Chars, fontDefault.CharsCount), unsafe.Slice(&fontDefault.Recs, fontDefault.CharsCount), 16, 4, 0) + fontDefault.Texture = rl.LoadTextureFromImage(&atlas) + rl.UnloadImage(&atlas) + + // SDF font generation from TTF font + fontSDF := rl.Font{BaseSize: 16, CharsCount: 95} + defer rl.UnloadFont(fontSDF) // SDF font unloading + + // Parameters > font size: 16, no glyphs array provided (nil), glyphs count: 0 (defaults to 95) + glyphsSDF := rl.LoadFontData(fileData, 16, nil, 0, rl.FontSdf) + fontSDF.Chars = &glyphsSDF[0] + // Parameters > font size: 16, glyphs padding in image: 0 px, pack method: 1 (Skyline algorithm) + atlas = rl.GenImageFontAtlas(unsafe.Slice(fontSDF.Chars, fontSDF.CharsCount), unsafe.Slice(&fontSDF.Recs, fontSDF.CharsCount), 16, 0, 1) + fontSDF.Texture = rl.LoadTextureFromImage(&atlas) + rl.UnloadImage(&atlas) + + // Load SDF required shader (we use default vertex shader) + shader := rl.LoadShader("", "sdf.fs") + defer rl.UnloadShader(shader) // Unload SDF shader + rl.SetTextureFilter(fontSDF.Texture, rl.FilterBilinear) // Required for SDF font + + fontPosition := rl.NewVector2(40, screenHeight/2.0-50) + textSize := rl.Vector2Zero() + fontSize := float32(16) + currentFont := 0 // 0 - fontDefault, 1 - fontSDF + + rl.SetTargetFPS(60) // Set our game to run at 60 frames-per-second + + // Main game loop + for !rl.WindowShouldClose() { // Detect window close button or ESC key + fontSize += rl.GetMouseWheelMove() * 8.0 + + if fontSize < 6 { + fontSize = 6 + } + + if rl.IsKeyDown(rl.KeySpace) { + currentFont = 1 + textSize = rl.MeasureTextEx(fontSDF, msg, fontSize, 0) + } else { + currentFont = 0 + textSize = rl.MeasureTextEx(fontDefault, msg, fontSize, 0) + } + + fontPosition.X = float32(rl.GetScreenWidth()/2) - textSize.X/2 + fontPosition.Y = float32(rl.GetScreenHeight()/2) - textSize.Y/2 + 80 + + rl.BeginDrawing() + rl.ClearBackground(rl.RayWhite) + + if currentFont == 1 { + // NOTE: SDF fonts require a custom SDf shader to compute fragment color + rl.BeginShaderMode(shader) // Activate SDF font shader + rl.DrawTextEx(fontSDF, msg, fontPosition, fontSize, 0, rl.Black) + rl.EndShaderMode() // Activate our default shader for next drawings + rl.DrawTexture(fontSDF.Texture, 10, 10, rl.Black) + rl.DrawText("SDF!", 320, 20, 80, rl.Red) + } else { + rl.DrawTextEx(fontDefault, msg, fontPosition, fontSize, 0, rl.Black) + rl.DrawTexture(fontDefault.Texture, 10, 10, rl.Black) + rl.DrawText("default font", 315, 40, 30, rl.Gray) + } + + rl.DrawText("FONT SIZE: 16.0", int32(rl.GetScreenWidth()-240), 20, 20, rl.DarkGray) + rl.DrawText(fmt.Sprintf("RENDER SIZE: %02.02f", fontSize), int32(rl.GetScreenWidth()-240), 50, 20, rl.DarkGray) + rl.DrawText("Use MOUSE WHEEL to SCALE TEXT!", int32(rl.GetScreenWidth()-240), 90, 10, rl.DarkGray) + + rl.DrawText("HOLD SPACE to USE SDF FONT VERSION!", 340, int32(rl.GetScreenHeight()-30), 20, rl.Maroon) + + rl.EndDrawing() + + } +} diff --git a/examples/text/font_sdf/sdf.fs b/examples/text/font_sdf/sdf.fs new file mode 100644 index 00000000..545f4507 --- /dev/null +++ b/examples/text/font_sdf/sdf.fs @@ -0,0 +1,26 @@ +#version 330 + +// Input vertex attributes (from vertex shader) +in vec2 fragTexCoord; +in vec4 fragColor; + +// Input uniform values +uniform sampler2D texture0; +uniform vec4 colDiffuse; + +// Output fragment color +out vec4 finalColor; + +// NOTE: Add here your custom variables + +void main() +{ + // Texel color fetching from texture sampler + // NOTE: Calculate alpha using signed distance field (SDF) + float distanceFromOutline = texture(texture0, fragTexCoord).a - 0.5; + float distanceChangePerFragment = length(vec2(dFdx(distanceFromOutline), dFdy(distanceFromOutline))); + float alpha = smoothstep(-distanceChangePerFragment, distanceChangePerFragment, distanceFromOutline); + + // Calculate final fragment color + finalColor = vec4(fragColor.rgb, fragColor.a*alpha); +} diff --git a/raylib/raylib_purego.go b/raylib/raylib_purego.go index 73f83bbc..e94af0c9 100644 --- a/raylib/raylib_purego.go +++ b/raylib/raylib_purego.go @@ -2900,9 +2900,12 @@ func IsFontReady(font Font) bool { } // LoadFontData - Load font data for further use -func LoadFontData(fileData []byte, fontSize int32, codepoints []rune, typ int32) []GlyphInfo { +func LoadFontData(fileData []byte, fontSize int32, codepoints []rune, codepointCount, typ int32) []GlyphInfo { dataSize := int32(len(fileData)) - codepointCount := int32(len(codepoints)) + // In case no chars count provided, default to 95 + if codepointCount <= 0 { + codepointCount = 95 + } ret := loadFontData(fileData, dataSize, fontSize, codepoints, codepointCount, typ) return unsafe.Slice(ret, codepointCount) } diff --git a/raylib/rtext.go b/raylib/rtext.go index 25f980d0..1e0c305e 100644 --- a/raylib/rtext.go +++ b/raylib/rtext.go @@ -101,12 +101,16 @@ func IsFontReady(font Font) bool { } // LoadFontData - Load font data for further use -func LoadFontData(fileData []byte, fontSize int32, codePoints []int32, typ int32) []GlyphInfo { +func LoadFontData(fileData []byte, fontSize int32, codePoints []rune, codepointCount, typ int32) []GlyphInfo { cfileData := (*C.uchar)(unsafe.Pointer(&fileData[0])) cdataSize := (C.int)(len(fileData)) cfontSize := (C.int)(fontSize) - ccodePoints := (*C.int)(unsafe.Pointer(&codePoints[0])) - ccodePointCount := (C.int)(len(codePoints)) + ccodePoints := (*C.int)(unsafe.SliceData(codePoints)) + // In case no chars count provided, default to 95 + if codepointCount <= 0 { + codepointCount = 95 + } + ccodePointCount := (C.int)(codepointCount) ctype := (C.int)(typ) ret := C.LoadFontData(cfileData, cdataSize, cfontSize, ccodePoints, ccodePointCount, ctype) v := unsafe.Slice((*GlyphInfo)(unsafe.Pointer(ret)), ccodePointCount) @@ -223,3 +227,13 @@ func GetGlyphAtlasRec(font Font, codepoint int32) Rectangle { v := newRectangleFromPointer(unsafe.Pointer(&ret)) return v } + +// GenImageFontAtlas - Generate image font atlas using chars info +func GenImageFontAtlas(glyphs []GlyphInfo, glyphRecs []*Rectangle, fontSize int32, padding int32, packMethod int32) Image { + cglyphs := (*C.GlyphInfo)(unsafe.Pointer(&glyphs[0])) + cglyphRecs := (**C.Rectangle)(unsafe.Pointer(&glyphRecs[0])) + cglyphCount := C.int(len(glyphs)) + ret := C.GenImageFontAtlas(cglyphs, cglyphRecs, cglyphCount, C.int(fontSize), C.int(padding), C.int(packMethod)) + v := newImageFromPointer(unsafe.Pointer(&ret)) + return *v +}