-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathnanovg.nim
612 lines (451 loc) · 16.9 KB
/
nanovg.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
import math
import strformat
import nanovg/wrapper
# {{{ Exports
# Types
export wrapper.Font
export wrapper.Image
export wrapper.NoFont
export wrapper.NoImage
export wrapper.`==`
export wrapper.NVGContext
export wrapper.NVGInitFlag
export wrapper.BlendFactor
export wrapper.Bounds
export wrapper.Color
export wrapper.CompositeOperation
export wrapper.CompositeOperationState
export wrapper.GlyphPosition
export wrapper.HorizontalAlign
export wrapper.ImageFlags
export wrapper.LineCapJoin
export wrapper.Paint
export wrapper.PathWinding
export wrapper.Solidity
export wrapper.TransformMatrix
export wrapper.VerticalAlign
export wrapper.NVGLUFramebuffer
# Global
export wrapper.nvgDeleteContext
export wrapper.beginFrame
export wrapper.cancelFrame
export wrapper.endFrame
export wrapper.globalCompositeOperation
export wrapper.globalCompositeBlendFunc
export wrapper.globalCompositeBlendFuncSeparate
# Color utils
export wrapper.rgb
export wrapper.rgba
export wrapper.lerp
export wrapper.withAlpha
export wrapper.hsl
export wrapper.hsla
# State Handling
export wrapper.save
export wrapper.restore
export wrapper.reset
# Render styles
export wrapper.strokeColor
export wrapper.strokePaint
export wrapper.fillColor
export wrapper.fillPaint
export wrapper.strokeWidth
export wrapper.lineCap
export wrapper.lineJoin
export wrapper.globalAlpha
# Transforms
export wrapper.resetTransform
export wrapper.transform
export wrapper.translate
export wrapper.rotate
export wrapper.skewX
export wrapper.skewY
export wrapper.scale
# Images
export wrapper.updateImage
export wrapper.deleteImage
# Paints
export wrapper.linearGradient
export wrapper.boxGradient
export wrapper.radialGradient
export wrapper.imagePattern
# Scissoring
export wrapper.scissor
export wrapper.intersectScissor
export wrapper.resetScissor
# Paths
export wrapper.beginPath
export wrapper.moveTo
export wrapper.lineTo
export wrapper.bezierTo
export wrapper.quadTo
export wrapper.arcTo
export wrapper.closePath
export wrapper.pathWinding
export wrapper.arc
export wrapper.rect
export wrapper.roundedRect
export wrapper.ellipse
export wrapper.circle
export wrapper.fill
export wrapper.stroke
# Text
export wrapper.findFont
export wrapper.addFallbackFont
export wrapper.resetFallbackFonts
export wrapper.fontSize
export wrapper.fontBlur
export wrapper.textLetterSpacing
export wrapper.textLineHeight
export wrapper.fontFace
export wrapper.text
export wrapper.textBox
# Framebuffer
export wrapper.nvgluBindFramebuffer
export wrapper.nvgluDeleteFramebuffer
# }}}
type
NVGError* = object of CatchableError
message*: string
using ctx: NVGContext
{.push warning[CStringConv]:off.}
# {{{ General functions
var g_gladInitialized = false
proc gladLoadGLLoader*(a: pointer): int {.cdecl, importc.}
proc nvgInit*(getProcAddress: pointer) =
if not g_gladInitialized:
if gladLoadGLLoader(getProcAddress) > 0:
g_gladInitialized = true
if not g_gladInitialized:
raise newException(NVGError, "Failed to initialise NanoVG")
proc nvgCreateContext*(flags: set[NVGInitFlag] = {}): NVGContext =
result = wrapper.nvgCreateContext(flags)
if result == nil:
raise newException(NVGError, "Failed to create NanoVG context")
template shapeAntiAlias*(ctx; enabled: bool) =
shapeAntiAlias(ctx, enabled.cint)
proc nvgluCreateFramebuffer*(ctx; width: int, height: int,
imageFlags: set[ImageFlags]): NVGLUFramebuffer =
nvgluCreateFramebuffer(ctx, width.cint, height.cint, cast[cint](imageFlags))
# }}}
# {{{ Transform functions
proc currentTransform*(ctx): TransformMatrix =
nvgCurrentTransform(ctx, result.m[0].addr)
proc identity*(dst: var TransformMatrix) =
nvgIdentity(dst.m[0].addr)
proc translate*(dst: var TransformMatrix, tx: float, ty: float) =
nvgTranslate(dst.m[0].addr, tx.cfloat, ty.cfloat)
proc scale*(dst: var TransformMatrix, sx: float, sy: float) =
nvgScale(dst.m[0].addr, sx.cfloat, sy.cfloat)
proc rotate*(dst: var TransformMatrix, angle: float) =
nvgRotate(dst.m[0].addr, angle.cfloat)
proc skewX*(dst: var TransformMatrix, angle: float) =
nvgSkewX(dst.m[0].addr, angle.cfloat)
proc skewY*(dst: var TransformMatrix, angle: float) =
nvgSkewY(dst.m[0].addr, angle.cfloat)
proc multiply*(dst: var TransformMatrix, src: TransformMatrix) =
nvgMultiply(dst.m[0].addr, src.m[0].unsafeAddr)
proc premultiply*(dst: var TransformMatrix, src: TransformMatrix) =
nvgPremultiply(dst.m[0].addr, src.m[0].unsafeAddr)
proc inverse*(src: TransformMatrix): (bool, TransformMatrix) =
var dst: TransformMatrix
let res = nvgInverse(dst.m[0].addr, src.m[0].unsafeAddr)
result = (res == 1, dst)
proc transformPoint*(xform: TransformMatrix,
x: float, y: float): (float, float) =
var destX, destY: cfloat
nvgTransformPoint(destX.addr, destY.addr, xform.m[0].unsafeAddr,
x.cfloat, y.cfloat)
result = (destX.float, destY.float)
# }}}
# {{{ Font functions
proc createFont*(ctx; name: string, filename: string): Font =
result = wrapper.createFont(ctx, name, filename)
if result == NoFont:
raise newException(NVGError, "Failed to create font")
proc createFontAtIndex*(ctx; name: string, filename: string,
fontIndex: Natural): Font =
result = createFontAtIndex(ctx, name, filename, fontIndex.cint)
if result == NoFont:
raise newException(NVGError, "Failed to create font")
proc createFontMem*(ctx; name: string,
data: var openArray[byte]): Font =
result = createFontMem(ctx, name, cast[ptr byte](data[0].addr),
data.len.cint, freeData=0)
if result == NoFont:
raise newException(NVGError, "Failed to create font")
proc createFontMemAtIndex*(ctx; name: string, data: var openArray[byte],
fontIndex: Natural): Font =
result = createFontMemAtIndex(ctx, name, cast[ptr byte](data[0].addr),
data.len.cint, freeData=0, fontIndex.cint)
if result == NoFont:
raise newException(NVGError, "Failed to create font")
# }}}
# {{{ Text functions
template `++`[A](a: ptr A, offset: int): ptr A =
cast[ptr A](cast[int](a) + offset)
template `--`[A](a, b: ptr A): int =
cast[int](a) - cast[int](b)
template getStartPtr(s: string, startPos: Natural): cstring =
s[0].unsafeAddr ++ startPos
template getEndPtr(s: string, endPos: int): cstring =
if endPos < 0: nil else: s[0].unsafeAddr ++ endPos ++ 1
proc textAlign*(ctx; halign: HorizontalAlign = haLeft,
valign: VerticalAlign = vaBaseline) {.inline.} =
textAlign(ctx, halign.cint or valign.cint)
proc text*(ctx; x, y: float, s: string,
startPos: Natural = 0, endPos: int = -1,): float {.inline.} =
if s == "": return
text(ctx, x, y, getStartPtr(s, startPos), getEndPtr(s, endPos))
proc textBox*(ctx; x, y, breakRowWidth: float, s: string,
startPos: Natural = 0, endPos: int = -1,) {.inline.} =
if s == "": return
textBox(ctx, x, y, breakRowWidth,
getStartPtr(s, startPos), getEndPtr(s, endPos))
template textMetrics*(ctx): tuple[ascender: float, descender: float,
lineHeight: float] =
var ascender, descender, lineHeight: cfloat
textMetrics(ctx, ascender.addr, descender.addr, lineHeight.addr)
(ascender.float, descender.float, lineHeight.float)
type
TextRow* = object
startPos*: Natural
endPos*: Natural
nextPos*: Natural
width*: float
minX*: float
maxX*: float
proc textBreakLines*(ctx; s: string, startPos: Natural = 0, endPos: int = -1,
breakRowWidth: float, maxRows: int = -1): seq[TextRow] =
result = newSeq[TextRow]()
if s == "" or maxRows == 0: return
var
rows: array[64, wrapper.TextRow]
rowsLeft = if maxRows >= 0: maxRows else: rows.len
startPtr = getStartPtr(s, startPos)
endPtr = getEndPtr(s, endPos)
while rowsLeft > 0:
let numRows = wrapper.textBreakLines(ctx, startPtr, endPtr,
breakRowWidth.cfloat, rows[0].addr,
min(rowsLeft, rows.len).cint)
for i in 0..<numRows:
let row = rows[i]
let sPtr = s[0].unsafeAddr
let tr = TextRow(
startPos: row.startPtr[0].unsafeAddr -- sPtr,
# endPtr points to the char after the last character in the line
endPos: row.endPtr[0].unsafeAddr -- sPtr - 1,
nextPos: row.nextPtr[0].unsafeAddr -- sPtr,
width: row.width,
minX: row.minX,
maxX: row.maxX
)
result.add(tr)
if numRows == 0:
rowsLeft = 0
else:
startPtr = rows[numRows-1].nextPtr
rowsLeft -= numRows
template textBreakLines*(ctx; s: string, startPos: Natural = 0,
breakRowWidth: float,
maxRows: int = -1): seq[TextRow] =
textBreakLines(ctx, s, startPos, endPos = -1, breakRowWidth, maxRows)
template textBreakLines*(ctx; s: string, breakRowWidth: float,
maxRows: int = -1): seq[TextRow] =
textBreakLines(ctx, s, startPos=0, endPos = -1, breakRowWidth, maxRows)
proc horizontalAdvance*(ctx; x: float, y: float, s: string,
startPos: Natural = 0,
endPos: int = -1): float {.inline.} =
if s == "": return
textBounds(ctx, x, y, getStartPtr(s, startPos), getEndPtr(s, endPos),
bounds=nil)
proc textWidth*(ctx; s: string, startPos: Natural = 0,
endPos: int = -1): float {.inline.} =
if s == "": return
textBounds(ctx, 0, 0, getStartPtr(s, startPos), getEndPtr(s, endPos),
bounds=nil)
proc textBounds*(ctx; x: float, y: float, s: string, startPos: Natural = 0,
endPos: int = -1): tuple[bounds: Bounds,
horizAdvance: float] {.inline.} =
if s == "": return
var b: Bounds
let adv = textBounds(ctx, x, y,
getStartPtr(s, startPos), getEndPtr(s, endPos),
bounds=b.x1.addr)
result = (b, adv.float)
proc textBoxBounds*(ctx; x: float, y: float,
breakRowWidth: float, s: string,
startPos: Natural = 0, endPos: int = -1): Bounds {.inline.} =
if s == "": return
textBoxBounds(ctx, x, y, breakRowWidth,
getStartPtr(s, startPos), getEndPtr(s, endPos), result.x1.addr)
proc textGlyphPositions*(ctx; x: float, y: float,
s: string, startPos: Natural = 0, endPos: int = -1,
positions: var openArray[GlyphPosition]): int {.inline.} =
if s == "": return
textGlyphPositions(ctx, x, y, getStartPtr(s, startPos), getEndPtr(s, endPos),
positions[0].addr, positions.len.cint)
template textGlyphPositions*(ctx; x: float, y: float,
s: string, startPos: Natural = 0,
positions: var openArray[GlyphPosition]): int =
textGlyphPositions(ctx, x, y, s, startPos, endPos = -1, positions)
template textGlyphPositions*(ctx; x: float, y: float, s: string,
positions: var openArray[GlyphPosition]): int =
textGlyphPositions(ctx, x, y, s, startPos=0, endPos = -1, positions)
# }}}
# {{{ Color functions
func clampToByte(i: int): byte = clamp(i, 0, 255).byte
func rgb*(r, g, b: int): Color =
rgb(clampToByte(r), clampToByte(g), clampToByte(b))
func rgba*(r, g, b, a: int): Color =
rgba(clampToByte(r), clampToByte(g), clampToByte(b), clampToByte(a))
func hsla*(h: float, s: float, l: float, a: float): Color =
hsla(h.cfloat, s.cfloat, l.cfloat, clamp(a * 255, 0, 255).byte)
template withAlpha*(c: Color, a: int): Color =
wrapper.withAlpha(c, clampToByte(a))
template withAlpha*(c: Color, a: float): Color =
wrapper.withAlpha(c, a)
template gray*(g: float, a: float = 1.0): Color = rgba(g, g, g, a)
template gray*(g: int, a: int = 255): Color = rgba(g, g, g, a)
template black*(a: float = 1.0): Color = gray(0.0, a)
template white*(a: float = 1.0): Color = gray(1.0, a)
template black*(a: int): Color = black(a/255)
template white*(a: int): Color = white(a/255)
# Useful for debugging
template blue*(a: float = 1.0): Color = rgba(0.0, 0.0, 1.0, a)
template green*(a: float = 1.0): Color = rgba(0.0, 1.0, 0.0, a)
template cyan*(a: float = 1.0): Color = rgba(0.0, 1.0, 1.0, a)
template red*(a: float = 1.0): Color = rgba(1.0, 0.0, 0.0, a)
template magenta*(a: float = 1.0): Color = rgba(1.0, 0.0, 1.0, a)
template yellow*(a: float = 1.0): Color = rgba(1.0, 1.0, 0.0, a)
template blue*(a: int): Color = blue(a/255)
template green*(a: int): Color = green(a/255)
template cyan*(a: int): Color = cyan(a/255)
template red*(a: int): Color = red(a/255)
template magenta*(a: int): Color = magenta(a/255)
template yellow*(a: int): Color = yellow(a/255)
# {{{ toLinear*()
proc toLinear(c: Color): Color =
# From: https://entropymine.com/imageworsener/srgbformula/
proc conv(x: float): float=
if x <= 0.0404482362771082: x / 12.92
else: pow((x + 0.055) / 1.055, 2.4)
rgb(conv(c.r), conv(c.g), conv(c.b))
# }}}
# {{{ fromLinear*()
proc fromLinear(c: Color): Color =
# From: https://entropymine.com/imageworsener/srgbformula/
proc conv(x: float): float=
if x <= 0.00313066844250063: x * 12.92
else: 1.055 * pow(x, 1/2.4) - 0.055
rgb(conv(c.r), conv(c.g), conv(c.b))
# }}}
# {{{ toHSV*()
func toHSV*(c: Color): (float, float, float) =
const HueMax = 360
let
r = c.r
g = c.g
b = c.b
xmax = max(r, max(g, b))
xmin = min(r, min(g, b))
v = xmax
c = xmax - xmin
let h = if c == 0: 0.0
elif v == r: ((60 * (g-b)/c + HueMax) mod HueMax) / HueMax
elif v == g: ((60 * (b-r)/c + 120) mod HueMax) / HueMax
else: ((60 * (r-g)/c + 240) mod HueMax) / HueMax # v == b
let s = if v == 0.0: 0.0 else: c/v
(h.float, s.float, v.float)
# }}}
# {{{ hsva*()
func hsva*(h, s, v, a: float): Color =
var r, g, b: float
if s == 0.0:
r = v
g = v
b = v
else:
let
hf = if h >= 1.0: 0.0 else: h*6
i = hf.int # should be in the range 0..5
f = hf - i.float # fractional part
m = v * (1 - s)
n = v * (1 - s*f)
k = v * (1 - s*(1-f))
(r, g, b) = if i == 0: (v, k, m)
elif i == 1: (n, v, m)
elif i == 2: (m, v, k)
elif i == 3: (m, n, v)
elif i == 4: (k, m, v)
else: (v, m, n)
rgba(r, g, b, a)
# }}}
func luma*(c: Color): float =
# Luma calculations according to the Rec. 709 spec
# https://en.wikipedia.org/wiki/Luma_(video)
c.r*0.2126 + c.g*0.7152 * c.b*0.0722
func isLight*(c: Color): bool = c.luma > 0.179
func isDark*(c: Color): bool = not c.isLight
func weightedEuclidanDistance*(c: Color): float =
sqrt(c.r*c.r*0.299 + c.g*c.g*0.587 + c.b*c.b*0.114)
func isLightEuclidan*(c: Color): bool =
weightedEuclidanDistance(c) > 0.7
func isDarkEuclidan*(c: Color): bool = not c.isLightEuclidan
# }}}
# {{{ Image functions
proc createImage*(ctx; filename: string, flags: set[ImageFlags] = {}): Image =
result = wrapper.createImage(ctx, filename, flags)
if result == NoImage:
raise newException(NVGError, "Failed to create image")
proc createImageMem*(ctx; flags: set[ImageFlags] = {},
data: var openArray[byte]): Image =
result = createImageMem(ctx, flags, cast[ptr byte](data[0].addr),
data.len.cint)
if result == NoImage:
raise newException(NVGError, "Failed to create image")
proc createImageRGBA*(ctx; w: Natural, h: Natural, flags: set[ImageFlags] = {},
data: var openArray[byte]): Image =
result = createImageRGBA(ctx, w.cint, h.cint, flags,
cast[ptr byte](data[0].addr))
if result == NoImage:
raise newException(NVGError, "Failed to create image")
proc imageSize*(ctx; image: Image): tuple[w, h: int] =
var w, h: cint
imageSize(ctx, image, w.addr, h.addr)
result = (w.int, h.int)
# {{{ Image extensions
proc stbi_load(filename: cstring, x, y, channels: ptr cint,
desiredChannels: cint): ptr UncheckedArray[byte]
{.cdecl, importc: "stbi_load".}
proc stbi_image_free(data: ptr UncheckedArray[byte])
{.cdecl, importc: "stbi_image_free".}
type ImageData* = object
width*, height*: Natural
numChannels*: Natural
data*: ptr UncheckedArray[byte]
proc size*(d: ImageData): Natural =
d.width * d.height * d.numChannels
proc `=destroy`*(d: var ImageData) =
if d.data != nil:
stbi_image_free(d.data)
d.width = 0
d.height = 0
d.numChannels = 0
d.data = nil
proc loadImage*(filename: string, desiredChannels: Natural = 4): ImageData =
var w, h, channels: cint
var data = stbi_load(filename, w.addr, h.addr, channels.addr,
desiredChannels.cint)
if data == nil:
raise newException(IOError, fmt"Could not load image '{filename}'")
result = ImageData(
width: w.Natural,
height: h.Natural,
numChannels: desiredChannels,
data: data
)
# }}}
# }}}
{.push warning[CStringConv]:on.}
# vim: et:ts=2:sw=2:fdm=marker