raster.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. package pdfrender
  2. import (
  3. "image"
  4. "math"
  5. "sort"
  6. "time"
  7. )
  8. /*
  9. raster.go
  10. A small anti-aliased vector rasteriser: paths are flattened into
  11. polygons, polygons become coverage masks (non-zero or even-odd, exact
  12. horizontal coverage and a few sub-scanlines per pixel), and masks are
  13. composited onto a premultiplied float canvas. Strokes are built as a
  14. union of per-segment quads, joins and caps, all wound the same way, so
  15. one non-zero fill draws them without seams.
  16. */
  17. type matrix [6]float64
  18. var identity = matrix{1, 0, 0, 1, 0, 0}
  19. // mul returns m followed by n
  20. func (m matrix) mul(n matrix) matrix {
  21. return matrix{
  22. m[0]*n[0] + m[1]*n[2],
  23. m[0]*n[1] + m[1]*n[3],
  24. m[2]*n[0] + m[3]*n[2],
  25. m[2]*n[1] + m[3]*n[3],
  26. m[4]*n[0] + m[5]*n[2] + n[4],
  27. m[4]*n[1] + m[5]*n[3] + n[5],
  28. }
  29. }
  30. func (m matrix) apply(x, y float64) (float64, float64) {
  31. return m[0]*x + m[2]*y + m[4], m[1]*x + m[3]*y + m[5]
  32. }
  33. func (m matrix) applyVec(x, y float64) (float64, float64) {
  34. return m[0]*x + m[2]*y, m[1]*x + m[3]*y
  35. }
  36. func (m matrix) invert() (matrix, bool) {
  37. det := m[0]*m[3] - m[1]*m[2]
  38. if math.Abs(det) < 1e-12 || math.IsNaN(det) {
  39. return identity, false
  40. }
  41. return matrix{
  42. m[3] / det, -m[1] / det,
  43. -m[2] / det, m[0] / det,
  44. (m[2]*m[5] - m[3]*m[4]) / det,
  45. (m[1]*m[4] - m[0]*m[5]) / det,
  46. }, true
  47. }
  48. // scale is the average length a unit vector gets under m
  49. func (m matrix) scale() float64 {
  50. return math.Sqrt(math.Abs(m[0]*m[3] - m[1]*m[2]))
  51. }
  52. type point struct{ x, y float64 }
  53. type pathOp uint8
  54. const (
  55. opMove pathOp = iota
  56. opLine
  57. opQuad
  58. opCubic
  59. opClose
  60. )
  61. type path struct {
  62. ops []pathOp
  63. pts []point
  64. }
  65. func (p *path) moveTo(x, y float64) {
  66. p.ops = append(p.ops, opMove)
  67. p.pts = append(p.pts, point{x, y})
  68. }
  69. func (p *path) lineTo(x, y float64) {
  70. if len(p.ops) == 0 {
  71. p.moveTo(x, y)
  72. return
  73. }
  74. p.ops = append(p.ops, opLine)
  75. p.pts = append(p.pts, point{x, y})
  76. }
  77. func (p *path) quadTo(x1, y1, x, y float64) {
  78. if len(p.ops) == 0 {
  79. p.moveTo(x1, y1)
  80. }
  81. p.ops = append(p.ops, opQuad)
  82. p.pts = append(p.pts, point{x1, y1}, point{x, y})
  83. }
  84. func (p *path) cubicTo(x1, y1, x2, y2, x, y float64) {
  85. if len(p.ops) == 0 {
  86. p.moveTo(x1, y1)
  87. }
  88. p.ops = append(p.ops, opCubic)
  89. p.pts = append(p.pts, point{x1, y1}, point{x2, y2}, point{x, y})
  90. }
  91. func (p *path) close() {
  92. if len(p.ops) > 0 && p.ops[len(p.ops)-1] != opClose {
  93. p.ops = append(p.ops, opClose)
  94. }
  95. }
  96. func (p *path) empty() bool {
  97. return len(p.ops) == 0
  98. }
  99. func (p *path) currentPoint() (point, bool) {
  100. if len(p.pts) == 0 {
  101. return point{}, false
  102. }
  103. //After a close the current point is the start of that subpath
  104. if p.ops[len(p.ops)-1] == opClose {
  105. pi := 0
  106. start := point{}
  107. for _, op := range p.ops {
  108. switch op {
  109. case opMove:
  110. start = p.pts[pi]
  111. pi++
  112. case opLine:
  113. pi++
  114. case opQuad:
  115. pi += 2
  116. case opCubic:
  117. pi += 3
  118. }
  119. }
  120. return start, true
  121. }
  122. return p.pts[len(p.pts)-1], true
  123. }
  124. type polyline struct {
  125. pts []point
  126. closed bool
  127. }
  128. // flatten turns the path into polylines in the space of m, with curves
  129. // split until they are within tol of the polyline
  130. func (p *path) flatten(m matrix, tol float64) []polyline {
  131. var out []polyline
  132. var cur *polyline
  133. pi := 0
  134. var last point
  135. tp := func(q point) point {
  136. x, y := m.apply(q.x, q.y)
  137. return point{x, y}
  138. }
  139. for _, op := range p.ops {
  140. switch op {
  141. case opMove:
  142. out = append(out, polyline{})
  143. cur = &out[len(out)-1]
  144. last = tp(p.pts[pi])
  145. cur.pts = append(cur.pts, last)
  146. pi++
  147. case opLine:
  148. if cur == nil {
  149. pi++
  150. continue
  151. }
  152. last = tp(p.pts[pi])
  153. cur.pts = append(cur.pts, last)
  154. pi++
  155. case opQuad:
  156. if cur == nil {
  157. pi += 2
  158. continue
  159. }
  160. c := tp(p.pts[pi])
  161. e := tp(p.pts[pi+1])
  162. //Elevate to a cubic
  163. c1 := point{last.x + 2.0/3*(c.x-last.x), last.y + 2.0/3*(c.y-last.y)}
  164. c2 := point{e.x + 2.0/3*(c.x-e.x), e.y + 2.0/3*(c.y-e.y)}
  165. cur.pts = flattenCubic(cur.pts, last, c1, c2, e, tol)
  166. last = e
  167. pi += 2
  168. case opCubic:
  169. if cur == nil {
  170. pi += 3
  171. continue
  172. }
  173. c1 := tp(p.pts[pi])
  174. c2 := tp(p.pts[pi+1])
  175. e := tp(p.pts[pi+2])
  176. cur.pts = flattenCubic(cur.pts, last, c1, c2, e, tol)
  177. last = e
  178. pi += 3
  179. case opClose:
  180. if cur != nil {
  181. cur.closed = true
  182. if len(cur.pts) > 0 {
  183. last = cur.pts[0]
  184. }
  185. //Drawing after a close starts a new subpath at the same point
  186. out = append(out, polyline{pts: []point{last}})
  187. cur = &out[len(out)-1]
  188. }
  189. }
  190. }
  191. //Drop the empty subpaths created after close
  192. clean := out[:0]
  193. for _, pl := range out {
  194. if len(pl.pts) > 1 || (len(pl.pts) == 1 && !pl.closed) {
  195. clean = append(clean, pl)
  196. }
  197. }
  198. return clean
  199. }
  200. func flattenCubic(dst []point, p0, p1, p2, p3 point, tol float64) []point {
  201. //Number of segments from the control polygon's deviation
  202. dd := math.Max(
  203. math.Hypot(p0.x-2*p1.x+p2.x, p0.y-2*p1.y+p2.y),
  204. math.Hypot(p1.x-2*p2.x+p3.x, p1.y-2*p2.y+p3.y))
  205. n := int(math.Ceil(math.Sqrt(dd * 0.75 / tol)))
  206. if n < 1 {
  207. n = 1
  208. }
  209. if n > 100 || math.IsNaN(dd) {
  210. n = 100
  211. }
  212. for i := 1; i <= n; i++ {
  213. t := float64(i) / float64(n)
  214. mt := 1 - t
  215. a := mt * mt * mt
  216. b := 3 * mt * mt * t
  217. c := 3 * mt * t * t
  218. e := t * t * t
  219. dst = append(dst, point{a*p0.x + b*p1.x + c*p2.x + e*p3.x, a*p0.y + b*p1.y + c*p2.y + e*p3.y})
  220. }
  221. return dst
  222. }
  223. /*
  224. Coverage masks
  225. */
  226. // mask holds coverage 0..255 over a rectangle; outside it the coverage is
  227. // zero. A nil a means full coverage everywhere inside r.
  228. type mask struct {
  229. r image.Rectangle
  230. a []uint8
  231. }
  232. func (m *mask) at(x, y int) uint8 {
  233. if m == nil {
  234. return 255
  235. }
  236. if !(image.Point{x, y}).In(m.r) {
  237. return 0
  238. }
  239. if m.a == nil {
  240. return 255
  241. }
  242. return m.a[(y-m.r.Min.Y)*m.r.Dx()+(x-m.r.Min.X)]
  243. }
  244. // intersectMasks multiplies two masks; nil stands for "no mask"
  245. func intersectMasks(a, b *mask) *mask {
  246. if a == nil {
  247. return b
  248. }
  249. if b == nil {
  250. return a
  251. }
  252. r := a.r.Intersect(b.r)
  253. if r.Empty() {
  254. return &mask{r: image.Rectangle{}}
  255. }
  256. if a.a == nil && b.a == nil {
  257. return &mask{r: r}
  258. }
  259. out := &mask{r: r, a: make([]uint8, r.Dx()*r.Dy())}
  260. i := 0
  261. for y := r.Min.Y; y < r.Max.Y; y++ {
  262. for x := r.Min.X; x < r.Max.X; x++ {
  263. out.a[i] = uint8((int(a.at(x, y))*int(b.at(x, y)) + 127) / 255)
  264. i++
  265. }
  266. }
  267. return out
  268. }
  269. func (m *mask) bounds() image.Rectangle {
  270. if m == nil {
  271. return image.Rect(-1<<20, -1<<20, 1<<20, 1<<20)
  272. }
  273. return m.r
  274. }
  275. type edge struct {
  276. x0, y0, x1, y1 float64
  277. dir int
  278. }
  279. const subSamples = 5
  280. // rasterize builds the coverage of closed polygons within bounds
  281. func rasterize(polys []polyline, evenOdd bool, bounds image.Rectangle) *mask {
  282. m, _ := rasterizeUntil(polys, evenOdd, bounds, time.Time{})
  283. return m
  284. }
  285. // rasterizeUntil is rasterize with a deadline (zero for none). A shape with
  286. // a huge number of edges across the whole canvas can take far longer than
  287. // the render budget, so the deadline is checked as the work goes; aborted
  288. // reports that it ran out and the coverage is unusable.
  289. func rasterizeUntil(polys []polyline, evenOdd bool, bounds image.Rectangle, deadline time.Time) (m *mask, aborted bool) {
  290. var edges []edge
  291. minX, minY := math.Inf(1), math.Inf(1)
  292. maxX, maxY := math.Inf(-1), math.Inf(-1)
  293. for _, pl := range polys {
  294. n := len(pl.pts)
  295. if n < 2 {
  296. continue
  297. }
  298. for i := 0; i < n; i++ {
  299. a := pl.pts[i]
  300. b := pl.pts[(i+1)%n]
  301. if math.IsNaN(a.x) || math.IsNaN(a.y) || math.IsNaN(b.x) || math.IsNaN(b.y) {
  302. continue
  303. }
  304. minX = math.Min(minX, a.x)
  305. maxX = math.Max(maxX, a.x)
  306. minY = math.Min(minY, a.y)
  307. maxY = math.Max(maxY, a.y)
  308. if a.y == b.y {
  309. continue
  310. }
  311. if a.y < b.y {
  312. edges = append(edges, edge{a.x, a.y, b.x, b.y, 1})
  313. } else {
  314. edges = append(edges, edge{b.x, b.y, a.x, a.y, -1})
  315. }
  316. }
  317. }
  318. if len(edges) == 0 {
  319. return nil, false
  320. }
  321. clampF := func(v float64) int {
  322. if v < -1<<24 {
  323. return -1 << 24
  324. }
  325. if v > 1<<24 {
  326. return 1 << 24
  327. }
  328. return int(v)
  329. }
  330. r := image.Rect(clampF(math.Floor(minX)), clampF(math.Floor(minY)), clampF(math.Ceil(maxX))+1, clampF(math.Ceil(maxY))+1).Intersect(bounds)
  331. if r.Empty() {
  332. return nil, false
  333. }
  334. sort.Slice(edges, func(i, j int) bool { return edges[i].y0 < edges[j].y0 })
  335. w := r.Dx()
  336. out := &mask{r: r, a: make([]uint8, w*r.Dy())}
  337. cov := make([]float32, w+1)
  338. diff := make([]float32, w+2)
  339. type crossing struct {
  340. x float64
  341. dir int
  342. }
  343. var active []int
  344. var xs []crossing
  345. nextEdge := 0
  346. ox := float64(r.Min.X)
  347. full := true
  348. work := 0
  349. for y := r.Min.Y; y < r.Max.Y; y++ {
  350. if work > 1<<18 && !deadline.IsZero() {
  351. work = 0
  352. if time.Now().After(deadline) {
  353. return nil, true
  354. }
  355. }
  356. work += len(active)
  357. rowHit := false
  358. for s := 0; s < subSamples; s++ {
  359. sy := float64(y) + (float64(s)+0.5)/subSamples
  360. for nextEdge < len(edges) && edges[nextEdge].y0 <= sy {
  361. active = append(active, nextEdge)
  362. nextEdge++
  363. }
  364. xs = xs[:0]
  365. keep := active[:0]
  366. for _, ei := range active {
  367. e := &edges[ei]
  368. if e.y1 <= sy {
  369. continue
  370. }
  371. keep = append(keep, ei)
  372. if e.y0 > sy {
  373. continue
  374. }
  375. x := e.x0 + (sy-e.y0)*(e.x1-e.x0)/(e.y1-e.y0)
  376. xs = append(xs, crossing{x - ox, e.dir})
  377. }
  378. active = keep
  379. if len(xs) < 2 {
  380. continue
  381. }
  382. sort.Slice(xs, func(i, j int) bool { return xs[i].x < xs[j].x })
  383. wind := 0
  384. for i := 0; i < len(xs)-1; i++ {
  385. wind += xs[i].dir
  386. inside := wind != 0
  387. if evenOdd {
  388. inside = wind&1 != 0
  389. }
  390. if !inside {
  391. continue
  392. }
  393. xa := math.Max(xs[i].x, 0)
  394. xb := math.Min(xs[i+1].x, float64(w))
  395. if xb <= xa {
  396. continue
  397. }
  398. rowHit = true
  399. ia := int(xa)
  400. ib := int(xb)
  401. if ia == ib {
  402. cov[ia] += float32(xb - xa)
  403. continue
  404. }
  405. cov[ia] += float32(float64(ia+1) - xa)
  406. diff[ia+1]++
  407. diff[ib]--
  408. if ib < w {
  409. cov[ib] += float32(xb - float64(ib))
  410. }
  411. }
  412. }
  413. row := out.a[(y-r.Min.Y)*w : (y-r.Min.Y+1)*w]
  414. if !rowHit {
  415. full = false
  416. continue
  417. }
  418. var run float32
  419. for x := 0; x < w; x++ {
  420. run += diff[x]
  421. v := (run + cov[x]) / subSamples
  422. if v >= 0.999 {
  423. row[x] = 255
  424. } else if v > 0 {
  425. row[x] = uint8(v*255 + 0.5)
  426. full = false
  427. } else {
  428. full = false
  429. }
  430. cov[x] = 0
  431. diff[x] = 0
  432. }
  433. diff[w] = 0
  434. diff[w+1] = 0
  435. cov[w] = 0
  436. }
  437. if full {
  438. out.a = nil
  439. }
  440. return out, false
  441. }
  442. /*
  443. Stroking
  444. */
  445. const (
  446. capButt = iota
  447. capRound
  448. capSquare
  449. )
  450. const (
  451. joinMiter = iota
  452. joinRound
  453. joinBevel
  454. )
  455. type strokeStyle struct {
  456. width float64
  457. cap int
  458. join int
  459. miterLimit float64
  460. dash []float64
  461. dashPhase float64
  462. //Segments per full circle for round joins and caps
  463. circleSegs int
  464. //Device pixels per unit, to skip joins too small to see
  465. devScale float64
  466. //Upper bound on the polygons built (0 for no limit)
  467. maxPolys int
  468. }
  469. func polyArea(pts []point) float64 {
  470. a := 0.0
  471. n := len(pts)
  472. for i := 0; i < n; i++ {
  473. j := (i + 1) % n
  474. a += pts[i].x*pts[j].y - pts[j].x*pts[i].y
  475. }
  476. return a / 2
  477. }
  478. func addPoly(dst []polyline, pts []point) []polyline {
  479. if polyArea(pts) < 0 {
  480. for i, j := 0, len(pts)-1; i < j; i, j = i+1, j-1 {
  481. pts[i], pts[j] = pts[j], pts[i]
  482. }
  483. }
  484. return append(dst, polyline{pts: pts, closed: true})
  485. }
  486. func circlePoly(c point, r float64, segs int) []point {
  487. pts := make([]point, segs)
  488. for i := 0; i < segs; i++ {
  489. a := 2 * math.Pi * float64(i) / float64(segs)
  490. pts[i] = point{c.x + r*math.Cos(a), c.y + r*math.Sin(a)}
  491. }
  492. return pts
  493. }
  494. // dashLines splits polylines by a dash pattern
  495. func dashLines(lines []polyline, dash []float64, phase float64) []polyline {
  496. total := 0.0
  497. for _, v := range dash {
  498. if v < 0 {
  499. return lines
  500. }
  501. total += v
  502. }
  503. if total <= 0 {
  504. return lines
  505. }
  506. var out []polyline
  507. for _, pl := range lines {
  508. pts := pl.pts
  509. if pl.closed && len(pts) > 1 {
  510. pts = append(append([]point{}, pts...), pts[0])
  511. }
  512. //Find the starting dash from the phase
  513. idx := 0
  514. left := dash[0]
  515. ph := math.Mod(phase, total)
  516. if ph < 0 {
  517. ph += total
  518. }
  519. for ph > 0 {
  520. if ph >= left {
  521. ph -= left
  522. idx = (idx + 1) % len(dash)
  523. left = dash[idx]
  524. } else {
  525. left -= ph
  526. ph = 0
  527. }
  528. }
  529. on := idx%2 == 0
  530. var cur []point
  531. if on && len(pts) > 0 {
  532. cur = []point{pts[0]}
  533. }
  534. pieces := 0
  535. for i := 0; i+1 < len(pts); i++ {
  536. a, b := pts[i], pts[i+1]
  537. segLen := math.Hypot(b.x-a.x, b.y-a.y)
  538. pos := 0.0
  539. for segLen-pos > left {
  540. pos += left
  541. t := pos / segLen
  542. p := point{a.x + (b.x-a.x)*t, a.y + (b.y-a.y)*t}
  543. if on {
  544. cur = append(cur, p)
  545. out = append(out, polyline{pts: cur})
  546. cur = nil
  547. } else {
  548. cur = []point{p}
  549. }
  550. on = !on
  551. idx = (idx + 1) % len(dash)
  552. left = dash[idx]
  553. pieces++
  554. if pieces > 100000 {
  555. return out
  556. }
  557. }
  558. left -= segLen - pos
  559. if on {
  560. cur = append(cur, b)
  561. }
  562. }
  563. if on && len(cur) > 1 {
  564. out = append(out, polyline{pts: cur})
  565. }
  566. }
  567. return out
  568. }
  569. // strokePolys builds the outline polygons of stroked polylines
  570. func strokePolys(lines []polyline, st strokeStyle) []polyline {
  571. hw := st.width / 2
  572. if hw <= 0 {
  573. return nil
  574. }
  575. if len(st.dash) > 0 {
  576. lines = dashLines(lines, st.dash, st.dashPhase)
  577. }
  578. segs := st.circleSegs
  579. if segs < 8 {
  580. segs = 8
  581. }
  582. var out []polyline
  583. full := func() bool { return st.maxPolys > 0 && len(out) >= st.maxPolys }
  584. for _, pl := range lines {
  585. if full() {
  586. break
  587. }
  588. //Drop repeated points
  589. pts := make([]point, 0, len(pl.pts))
  590. for _, p := range pl.pts {
  591. if len(pts) == 0 || math.Hypot(p.x-pts[len(pts)-1].x, p.y-pts[len(pts)-1].y) > hw*1e-3 {
  592. pts = append(pts, p)
  593. }
  594. }
  595. closed := pl.closed
  596. if closed && len(pts) > 2 && math.Hypot(pts[0].x-pts[len(pts)-1].x, pts[0].y-pts[len(pts)-1].y) <= hw*1e-3 {
  597. pts = pts[:len(pts)-1]
  598. }
  599. if len(pts) == 1 {
  600. //A zero length subpath draws only its caps
  601. p := pts[0]
  602. switch st.cap {
  603. case capRound:
  604. out = addPoly(out, circlePoly(p, hw, segs))
  605. case capSquare:
  606. out = addPoly(out, []point{{p.x - hw, p.y - hw}, {p.x + hw, p.y - hw}, {p.x + hw, p.y + hw}, {p.x - hw, p.y + hw}})
  607. }
  608. continue
  609. }
  610. if len(pts) < 2 {
  611. continue
  612. }
  613. if closed && len(pts) < 3 {
  614. closed = false
  615. }
  616. n := len(pts)
  617. nseg := n - 1
  618. if closed {
  619. nseg = n
  620. }
  621. dirs := make([]point, nseg)
  622. for i := 0; i < nseg; i++ {
  623. a, b := pts[i], pts[(i+1)%n]
  624. l := math.Hypot(b.x-a.x, b.y-a.y)
  625. dirs[i] = point{(b.x - a.x) / l, (b.y - a.y) / l}
  626. }
  627. for i := 0; i < nseg; i++ {
  628. a, b := pts[i], pts[(i+1)%n]
  629. nx, ny := -dirs[i].y*hw, dirs[i].x*hw
  630. out = addPoly(out, []point{{a.x + nx, a.y + ny}, {b.x + nx, b.y + ny}, {b.x - nx, b.y - ny}, {a.x - nx, a.y - ny}})
  631. }
  632. //Joins
  633. for i := 0; i < n; i++ {
  634. var d0, d1 point
  635. if closed {
  636. d0 = dirs[(i-1+nseg)%nseg]
  637. d1 = dirs[i%nseg]
  638. } else {
  639. if i == 0 || i == n-1 {
  640. continue
  641. }
  642. d0, d1 = dirs[i-1], dirs[i]
  643. }
  644. v := pts[i]
  645. cross := d0.x*d1.y - d0.y*d1.x
  646. dot := d0.x*d1.x + d0.y*d1.y
  647. if math.Abs(cross) < 1e-9 && dot > 0 {
  648. continue
  649. }
  650. //A shallow bend (a flattened curve) leaves a gap well under a
  651. //pixel; drawing a join there only costs time
  652. if dot > 0 && st.devScale > 0 && math.Abs(cross)*hw*st.devScale < 0.2 {
  653. continue
  654. }
  655. if full() {
  656. break
  657. }
  658. switch st.join {
  659. case joinRound:
  660. out = addPoly(out, circlePoly(v, hw, segs))
  661. default:
  662. //Outer side normals
  663. side := 1.0
  664. if cross > 0 {
  665. side = -1
  666. }
  667. n0 := point{-d0.y * hw * side, d0.x * hw * side}
  668. n1 := point{-d1.y * hw * side, d1.x * hw * side}
  669. p0 := point{v.x + n0.x, v.y + n0.y}
  670. p1 := point{v.x + n1.x, v.y + n1.y}
  671. if st.join == joinMiter {
  672. //Miter length ratio is 1 / sin(theta / 2)
  673. //The miter length ratio is 1 / sin(phi / 2), phi being
  674. //the angle between the segments
  675. cosT := clamp(dot, -1, 1)
  676. //The miter tip lies on the bisector of the outer normals
  677. bx, by := n0.x+n1.x, n0.y+n1.y
  678. bl := math.Hypot(bx, by)
  679. cosHalf := math.Sqrt((1 + cosT) / 2)
  680. if bl > 1e-9 && cosHalf > 1e-6 && 1/cosHalf <= st.miterLimit {
  681. ml := hw / cosHalf
  682. tip := point{v.x + bx/bl*ml, v.y + by/bl*ml}
  683. out = addPoly(out, []point{v, p0, tip, p1})
  684. continue
  685. }
  686. }
  687. out = addPoly(out, []point{v, p0, p1})
  688. }
  689. }
  690. //Caps
  691. if !closed {
  692. ends := []struct {
  693. p point
  694. d point
  695. }{
  696. {pts[0], point{-dirs[0].x, -dirs[0].y}},
  697. {pts[n-1], dirs[nseg-1]},
  698. }
  699. for _, e := range ends {
  700. switch st.cap {
  701. case capRound:
  702. out = addPoly(out, circlePoly(e.p, hw, segs))
  703. case capSquare:
  704. nx, ny := -e.d.y*hw, e.d.x*hw
  705. ex, ey := e.d.x*hw, e.d.y*hw
  706. out = addPoly(out, []point{
  707. {e.p.x + nx, e.p.y + ny},
  708. {e.p.x + nx + ex, e.p.y + ny + ey},
  709. {e.p.x - nx + ex, e.p.y - ny + ey},
  710. {e.p.x - nx, e.p.y - ny},
  711. })
  712. }
  713. }
  714. }
  715. }
  716. return out
  717. }
  718. /*
  719. Canvas
  720. */
  721. // canvas is premultiplied RGBA in float32
  722. type canvas struct {
  723. w, h int
  724. pix []float32
  725. }
  726. func newCanvas(w, h int, opaqueWhite bool) *canvas {
  727. c := &canvas{w: w, h: h, pix: make([]float32, w*h*4)}
  728. if opaqueWhite {
  729. for i := range c.pix {
  730. c.pix[i] = 1
  731. }
  732. }
  733. return c
  734. }
  735. func (c *canvas) bounds() image.Rectangle {
  736. return image.Rect(0, 0, c.w, c.h)
  737. }
  738. // painter returns the colour (not premultiplied) and alpha at a pixel
  739. type painter interface {
  740. at(x, y int) (r, g, b, a float32)
  741. }
  742. type solidPaint struct {
  743. r, g, b float32
  744. }
  745. func (s solidPaint) at(int, int) (float32, float32, float32, float32) {
  746. return s.r, s.g, s.b, 1
  747. }
  748. const (
  749. blendNormal = iota
  750. blendMultiply
  751. blendScreen
  752. blendDarken
  753. blendLighten
  754. blendOverlay
  755. blendDifference
  756. )
  757. func blendChannel(mode int, cb, cs float32) float32 {
  758. switch mode {
  759. case blendMultiply:
  760. return cb * cs
  761. case blendScreen:
  762. return cb + cs - cb*cs
  763. case blendDarken:
  764. if cb < cs {
  765. return cb
  766. }
  767. return cs
  768. case blendLighten:
  769. if cb > cs {
  770. return cb
  771. }
  772. return cs
  773. case blendOverlay:
  774. if cb <= 0.5 {
  775. return 2 * cb * cs
  776. }
  777. return 1 - 2*(1-cb)*(1-cs)
  778. case blendDifference:
  779. if cb > cs {
  780. return cb - cs
  781. }
  782. return cs - cb
  783. }
  784. return cs
  785. }
  786. // composite paints src through the coverage, clip and soft mask
  787. func (c *canvas) composite(cov *mask, clip *mask, soft *mask, src painter, alpha float32, blend int) {
  788. if cov == nil || alpha <= 0 {
  789. return
  790. }
  791. r := cov.r.Intersect(c.bounds()).Intersect(clip.bounds()).Intersect(soft.bounds())
  792. if r.Empty() {
  793. return
  794. }
  795. solid, isSolid := src.(solidPaint)
  796. cw := cov.r.Dx()
  797. for y := r.Min.Y; y < r.Max.Y; y++ {
  798. rowOff := (y - cov.r.Min.Y) * cw
  799. for x := r.Min.X; x < r.Max.X; x++ {
  800. a := alpha
  801. if cov.a != nil {
  802. cv := cov.a[rowOff+x-cov.r.Min.X]
  803. if cv == 0 {
  804. continue
  805. }
  806. a *= float32(cv) / 255
  807. }
  808. if clip != nil && clip.a != nil {
  809. a *= float32(clip.a[(y-clip.r.Min.Y)*clip.r.Dx()+x-clip.r.Min.X]) / 255
  810. }
  811. if soft != nil && soft.a != nil {
  812. a *= float32(soft.a[(y-soft.r.Min.Y)*soft.r.Dx()+x-soft.r.Min.X]) / 255
  813. }
  814. if a <= 0 {
  815. continue
  816. }
  817. var sr, sg, sb float32
  818. if isSolid {
  819. sr, sg, sb = solid.r, solid.g, solid.b
  820. } else {
  821. var sa float32
  822. sr, sg, sb, sa = src.at(x, y)
  823. a *= sa
  824. if a <= 0 {
  825. continue
  826. }
  827. }
  828. i := (y*c.w + x) * 4
  829. if blend != blendNormal {
  830. da := c.pix[i+3]
  831. if da > 0 {
  832. br, bg, bb := c.pix[i]/da, c.pix[i+1]/da, c.pix[i+2]/da
  833. sr = (1-da)*sr + da*blendChannel(blend, br, sr)
  834. sg = (1-da)*sg + da*blendChannel(blend, bg, sg)
  835. sb = (1-da)*sb + da*blendChannel(blend, bb, sb)
  836. }
  837. }
  838. ia := 1 - a
  839. c.pix[i] = sr*a + c.pix[i]*ia
  840. c.pix[i+1] = sg*a + c.pix[i+1]*ia
  841. c.pix[i+2] = sb*a + c.pix[i+2]*ia
  842. c.pix[i+3] = a + c.pix[i+3]*ia
  843. }
  844. }
  845. }
  846. // toRGBA flattens the canvas onto white into an 8 bit image
  847. func (c *canvas) toRGBA() *image.RGBA {
  848. img := image.NewRGBA(image.Rect(0, 0, c.w, c.h))
  849. for i := 0; i < c.w*c.h; i++ {
  850. a := c.pix[i*4+3]
  851. for k := 0; k < 3; k++ {
  852. v := c.pix[i*4+k] + (1 - a)
  853. img.Pix[i*4+k] = uint8(clamp(float64(v), 0, 1)*255 + 0.5)
  854. }
  855. img.Pix[i*4+3] = 255
  856. }
  857. return img
  858. }