golang-ui / nuklear

This project provides Go bindings for nuklear.h — a small ANSI C GUI library.
https://github.com/vurtun/nuklear
MIT License
1.57k stars 98 forks source link

proof of concept: go rune as nk_rune #76

Closed chidea closed 5 years ago

chidea commented 5 years ago

This PR is for proofing that it's possible to use golang rune as nk_rune natively. It makes custom range definitions reside in golang code, thus definitions like const nk_rune nk_font_japanese_glyph_ranges[] can be removed from nk/etc.go . Below is an user code example.

import "path"  // path concatenation function from path lib for true cross-platform impl.
var japaneseGlyphRanges = []rune{  // must be declared as global variable (outside of any function)
    0x0020, 0x00FF,
    0x2200, 0x22FF, // Mathematical Operators
    0x3000, 0x303F, // CJK Symbols and Punctuation
    0x3040, 0x309F, // Hiragana // This is also possible : 'ぁ', 'ぁ' | 0x1F,
    0x30A0, 0x30FF, // Katakana
    0x0370, 0x03FF, // Greek and Coptic
    0xFF00, 0xFFEF, // Halfwidth and Fullwidth Forms
    0x4E00, 0x9FFF, // CJK Unified Ideographs
    0,
}
var numGlyphRanges = []rune{  // must be declared as global variable (outside of any function)
    '0', '9'|0xF,  // nuclear font baker requires the last byte of the end range to be 0xF.
    '.', '.'|0xF,
    0, }  // must end with zero to flag termination
atlas := nk.NewFontAtlas()
nk.NkFontStashBegin(&atlas)

fontConfig := nk.NkFontConfig(0)  // height=0 for automatic height
fontConfig.SetOversample(1, 1) // it reduces memory usage for low memory devices
fontConfig.SetRangeGoRune(japaneseGlyphRanges)  // go runes (int32) are natively used as nk_rune (uint32)
japFont := nk.NkFontAtlasAddFromFile(atlas, path.Join("assets", "NotoSansCJKkr.ttf"), 25, &fontConfig)
// AddFromFile greately reduces memory usage in comparison to AddFromBytes

fontConfig.SetRangeGoRune(numGlyphRanges)  // go runes (int32) are natively used as nk_rune (uint32)
numFont := nk.NkFontAtlasAddFromFile(atlas, path.Join("assets", "NotoSansCJKkr.ttf"), 35, &fontConfig)
// setting height=0 makes it possible to reuse fontConfig with different font sizes.

nk.NkFontStashEnd()