UNPKG

p5

Version:

[![npm version](https://badge.fury.io/js/p5.svg)](https://www.npmjs.com/package/p5)

642 lines (641 loc) • 19.5 kB
import { on as TEXTURE } from "../constants-DA50zLWL.js"; import { Vector } from "../math/p5.Vector.js"; import { C as Renderer3D } from "../rendering-BHEDmo0B.js"; import { Geometry } from "./p5.Geometry.js"; import { Font, arrayCommandsToObjects } from "../type/p5.Font.js"; //#region src/webgl/text.js function text(p5, fn) { Renderer3D.prototype.maxCachedGlyphs = function() { return 200; }; Font.prototype._getFontInfo = function(axs) { this._fontInfos = this._fontInfos || {}; const key = JSON.stringify(axs); if (this._fontInfos[key]) return this._fontInfos[key]; else { const val = new FontInfo(this, { axs }); this._fontInfos[key] = val; return val; } }; const charGridWidth = 9; const charGridHeight = charGridWidth; const strokeImageWidth = 64; const strokeImageHeight = 64; const gridImageWidth = 64; const gridImageHeight = 64; const cellImageWidth = 64; const cellImageHeight = 64; /** * @private * @class ImageInfos * @param {Integer} width * @param {Integer} height * * the ImageInfos class holds a list of ImageDatas of a given size. */ class ImageInfos { constructor(width, height) { this.width = width; this.height = height; this.infos = []; } /** * * @param {Integer} space * @return {Object} contains the ImageData, and pixel index into that * ImageData where the free space was allocated. * * finds free space of a given size in the ImageData list */ findImage(space) { const imageSize = this.width * this.height; if (space > imageSize) throw new Error("font is too complex to render in 3D"); let imageInfo, imageData; for (let ii = this.infos.length - 1; ii >= 0; --ii) { const imageInfoTest = this.infos[ii]; if (imageInfoTest.index + space < imageSize) { imageInfo = imageInfoTest; imageData = imageInfoTest.imageData; break; } } if (!imageInfo) { try { imageData = new ImageData(this.width, this.height); } catch { let canvas = document.getElementsByTagName("canvas")[0]; const created = !canvas; if (!canvas) { canvas = document.createElement("canvas"); canvas.style.display = "none"; document.body.appendChild(canvas); } const ctx = canvas.getContext("2d"); if (ctx) imageData = ctx.createImageData(this.width, this.height); if (created) document.body.removeChild(canvas); } imageInfo = { index: 0, imageData }; this.infos.push(imageInfo); } const index = imageInfo.index; imageInfo.index += space; imageData._dirty = true; return { imageData, index }; } } /** * @function setPixel * @private * @param {Object} imageInfo * @param {Number} r * @param {Number} g * @param {Number} b * @param {Number} a * * writes the next pixel into an indexed ImageData */ function setPixel(imageInfo, r, g, b, a) { const pixels = imageInfo.imageData.data; let index = imageInfo.index++ * 4; pixels[index++] = r; pixels[index++] = g; pixels[index++] = b; pixels[index++] = a; } const SQRT3 = Math.sqrt(3); /** * @private * @class FontInfo * @param {Object} font an opentype.js font object * * contains cached images and glyph information for an opentype font */ class FontInfo { constructor(font, { axs } = {}) { this.font = font; this.axs = axs; this.strokeImageInfos = new ImageInfos(strokeImageWidth, strokeImageHeight); this.colDimImageInfos = new ImageInfos(gridImageWidth, gridImageHeight); this.rowDimImageInfos = new ImageInfos(gridImageWidth, gridImageHeight); this.colCellImageInfos = new ImageInfos(cellImageWidth, cellImageHeight); this.rowCellImageInfos = new ImageInfos(cellImageWidth, cellImageHeight); this.glyphInfos = {}; } /** * @param {Glyph} glyph the x positions of points in the curve * @returns {Object} the glyphInfo for that glyph * * calculates rendering info for a glyph, including the curve information, * row & column stripes compiled into textures. */ getGlyphInfo(glyph) { let gi = this.glyphInfos[glyph.index]; if (gi) return gi; const axs = this.axs; const { glyph: { path: { commands } } } = this.font._singleShapeToPath(glyph.shape, { axs }); let xMin = Infinity; let xMax = -Infinity; let yMin = Infinity; let yMax = -Infinity; for (const cmd of commands) for (let i = 1; i < cmd.length; i += 2) { xMin = Math.min(xMin, cmd[i]); xMax = Math.max(xMax, cmd[i]); yMin = Math.min(yMin, cmd[i + 1]); yMax = Math.max(yMax, cmd[i + 1]); } if (xMin >= xMax || yMin >= yMax || !commands.length) return this.glyphInfos[glyph.index] = {}; const gWidth = xMax - xMin; const gHeight = yMax - yMin; const cmds = arrayCommandsToObjects(commands); let i; const strokes = []; const rows = []; const cols = []; for (i = 8; i >= 0; --i) cols.push([]); for (i = 8; i >= 0; --i) rows.push([]); /** * @function push * @private * @param {Number[]} xs the x positions of points in the curve * @param {Number[]} ys the y positions of points in the curve * @param {Object} v the curve information * * adds a curve to the rows & columns that it intersects with */ function push(xs, ys, v) { const index = strokes.length; strokes.push(v); /** * @function minMax * @private * @param {Number[]} rg the list of values to compare * @param {Number} min the initial minimum value * @param {Number} max the initial maximum value * * find the minimum & maximum value in a list of values */ function minMax(rg, min, max) { for (let i = rg.length; i-- > 0;) { const v = rg[i]; if (min > v) min = v; if (max < v) max = v; } return { min, max }; } const cellOffset = .5; const mmX = minMax(xs, 1, 0); const ixMin = Math.max(Math.floor(mmX.min * charGridWidth - cellOffset), 0); const ixMax = Math.min(Math.ceil(mmX.max * charGridWidth + cellOffset), charGridWidth); for (let iCol = ixMin; iCol < ixMax; ++iCol) cols[iCol].push(index); const mmY = minMax(ys, 1, 0); const iyMin = Math.max(Math.floor(mmY.min * charGridHeight - cellOffset), 0); const iyMax = Math.min(Math.ceil(mmY.max * charGridHeight + cellOffset), charGridHeight); for (let iRow = iyMin; iRow < iyMax; ++iRow) rows[iRow].push(index); } /** * @function clamp * @private * @param {Number} v the value to clamp * @param {Number} min the minimum value * @param {Number} max the maxmimum value * * clamps a value between a minimum & maximum value */ function clamp(v, min, max) { if (v < min) return min; if (v > max) return max; return v; } /** * @function byte * @private * @param {Number} v the value to scale * * converts a floating-point number in the range 0-1 to a byte 0-255 */ function byte(v) { return clamp(255 * v, 0, 255); } /** * @private * @class Cubic * @param {Number} p0 the start point of the curve * @param {Number} c0 the first control point * @param {Number} c1 the second control point * @param {Number} p1 the end point * * a cubic curve */ class Cubic { constructor(p0, c0, c1, p1) { this.p0 = p0; this.c0 = c0; this.c1 = c1; this.p1 = p1; } /** * @return {Object} the quadratic approximation * * converts the cubic to a quadtratic approximation by * picking an appropriate quadratic control point */ toQuadratic() { return { x: this.p0.x, y: this.p0.y, x1: this.p1.x, y1: this.p1.y, cx: ((this.c0.x + this.c1.x) * 3 - (this.p0.x + this.p1.x)) / 4, cy: ((this.c0.y + this.c1.y) * 3 - (this.p0.y + this.p1.y)) / 4 }; } /** * @return {Number} the error * * calculates the magnitude of error of this curve's * quadratic approximation. */ quadError() { return Vector.sub(Vector.sub(this.p1, this.p0), Vector.mult(Vector.sub(this.c1, this.c0), 3)).mag() / 2; } /** * @param {Number} t the value (0-1) at which to split * @return {Cubic} the second part of the curve * * splits the cubic into two parts at a point 't' along the curve. * this cubic keeps its start point and its end point becomes the * point at 't'. the 'end half is returned. */ split(t) { const m1 = Vector.lerp(this.p0, this.c0, t); const m2 = Vector.lerp(this.c0, this.c1, t); const mm1 = Vector.lerp(m1, m2, t); this.c1 = Vector.lerp(this.c1, this.p1, t); this.c0 = Vector.lerp(m2, this.c1, t); const pt = Vector.lerp(mm1, this.c0, t); const part1 = new Cubic(this.p0, m1, mm1, pt); this.p0 = pt; return part1; } /** * @return {Cubic[]} the non-inflecting pieces of this cubic * * returns an array containing 0, 1 or 2 cubics split resulting * from splitting this cubic at its inflection points. * this cubic is (potentially) altered and returned in the list. */ splitInflections() { const a = Vector.sub(this.c0, this.p0); const b = Vector.sub(Vector.sub(this.c1, this.c0), a); const c = Vector.sub(Vector.sub(Vector.sub(this.p1, this.c1), a), Vector.mult(b, 2)); const cubics = []; let A = b.x * c.y - b.y * c.x; if (A !== 0) { let B = a.x * c.y - a.y * c.x; let C = a.x * b.y - a.y * b.x; const disc = B * B - 4 * A * C; if (disc >= 0) { if (A < 0) { A = -A; B = -B; C = -C; } const Q = Math.sqrt(disc); const t0 = (-B - Q) / (2 * A); let t1 = (-B + Q) / (2 * A); if (t0 > 0 && t0 < 1) { cubics.push(this.split(t0)); t1 = 1 - (1 - t1) / (1 - t0); } if (t1 > 0 && t1 < 1) cubics.push(this.split(t1)); } } cubics.push(this); return cubics; } } /** * @function cubicToQuadratics * @private * @param {Number} x0 * @param {Number} y0 * @param {Number} cx0 * @param {Number} cy0 * @param {Number} cx1 * @param {Number} cy1 * @param {Number} x1 * @param {Number} y1 * @returns {Cubic[]} an array of cubics whose quadratic approximations * closely match the civen cubic. * * converts a cubic curve to a list of quadratics. */ function cubicToQuadratics(x0, y0, cx0, cy0, cx1, cy1, x1, y1) { const cubics = new Cubic(new Vector(x0, y0), new Vector(cx0, cy0), new Vector(cx1, cy1), new Vector(x1, y1)).splitInflections(); const qs = []; const precision = 30 / SQRT3; for (let cubic of cubics) { const tail = []; let t3; for (;;) { t3 = precision / cubic.quadError(); if (t3 >= .125) break; const t = Math.pow(t3, 1 / 3); const start = cubic.split(t); const middle = cubic.split(1 - t / (1 - t)); qs.push(start); tail.push(cubic); cubic = middle; } if (t3 < 1) qs.push(cubic.split(.5)); qs.push(cubic); Array.prototype.push.apply(qs, tail.reverse()); } return qs; } /** * @function pushLine * @private * @param {Number} x0 * @param {Number} y0 * @param {Number} x1 * @param {Number} y1 * * add a straight line to the row/col grid of a glyph */ function pushLine(x0, y0, x1, y1) { const mx = (x0 + x1) / 2; const my = (y0 + y1) / 2; push([x0, x1], [y0, y1], { x: x0, y: y0, cx: mx, cy: my }); } /** * @function samePoint * @private * @param {Number} x0 * @param {Number} y0 * @param {Number} x1 * @param {Number} y1 * @return {Boolean} true if the two points are sufficiently close * * tests if two points are close enough to be considered the same */ function samePoint(x0, y0, x1, y1) { return Math.abs(x1 - x0) < 1e-5 && Math.abs(y1 - y0) < 1e-5; } let x0, y0, xs, ys; for (const cmd of cmds) { const x1 = (cmd.x - xMin) / gWidth; const y1 = (cmd.y - yMin) / gHeight; if (samePoint(x0, y0, x1, y1)) continue; switch (cmd.type) { case "M": xs = x1; ys = y1; break; case "L": pushLine(x0, y0, x1, y1); break; case "Q": { const cx = (cmd.x1 - xMin) / gWidth; const cy = (cmd.y1 - yMin) / gHeight; push([ x0, x1, cx ], [ y0, y1, cy ], { x: x0, y: y0, cx, cy }); break; } case "Z": if (!samePoint(x0, y0, xs, ys)) { pushLine(x0, y0, xs, ys); strokes.push({ x: xs, y: ys }); } else strokes.push({ x: x0, y: y0 }); break; case "C": { const cx1 = (cmd.x1 - xMin) / gWidth; const cy1 = (cmd.y1 - yMin) / gHeight; const cx2 = (cmd.x2 - xMin) / gWidth; const cy2 = (cmd.y2 - yMin) / gHeight; const qs = cubicToQuadratics(x0, y0, cx1, cy1, cx2, cy2, x1, y1); for (let iq = 0; iq < qs.length; iq++) { const q = qs[iq].toQuadratic(); push([ q.x, q.x1, q.cx ], [ q.y, q.y1, q.cy ], q); } break; } default: throw new Error(`unknown command type: ${cmd.type}`); } x0 = x1; y0 = y1; } const strokeCount = strokes.length; const strokeImageInfo = this.strokeImageInfos.findImage(strokeCount); const strokeOffset = strokeImageInfo.index; for (let il = 0; il < strokeCount; ++il) { const s = strokes[il]; setPixel(strokeImageInfo, byte(s.x), byte(s.y), byte(s.cx), byte(s.cy)); } /** * @function layout * @private * @param {Number[][]} dim * @param {ImageInfos} dimImageInfos * @param {ImageInfos} cellImageInfos * @return {Object} * * lays out the curves in a dimension (row or col) into two * images, one for the indices of the curves themselves, and * one containing the offset and length of those index spans. */ function layout(dim, dimImageInfos, cellImageInfos) { const dimLength = dim.length; const dimImageInfo = dimImageInfos.findImage(dimLength); const dimOffset = dimImageInfo.index; let totalStrokes = 0; for (let id = 0; id < dimLength; ++id) totalStrokes += dim[id].length; const cellImageInfo = cellImageInfos.findImage(totalStrokes); for (let i = 0; i < dimLength; ++i) { const strokeIndices = dim[i]; const strokeCount = strokeIndices.length; const cellLineIndex = cellImageInfo.index; setPixel(dimImageInfo, cellLineIndex >> 7, cellLineIndex & 127, strokeCount >> 7, strokeCount & 127); for (let iil = 0; iil < strokeCount; ++iil) { const strokeIndex = strokeIndices[iil] + strokeOffset; setPixel(cellImageInfo, strokeIndex >> 7, strokeIndex & 127, 0, 0); } } return { cellImageInfo, dimOffset, dimImageInfo }; } gi = this.glyphInfos[glyph.index] = { glyph, uGlyphRect: [ xMin, yMin, xMax, yMax ], strokeImageInfo, strokes, colInfo: layout(cols, this.colDimImageInfos, this.colCellImageInfos), rowInfo: layout(rows, this.rowDimImageInfos, this.rowCellImageInfos) }; gi.uGridOffset = [gi.colInfo.dimOffset, gi.rowInfo.dimOffset]; return gi; } } Renderer3D.prototype._renderText = function(line, x, y, maxY, minY) { if (!this.states.textFont || typeof this.states.textFont === "string") { console.log("WEBGL: you must load and set a font before drawing text. See `loadFont` and `textFont` for more details."); return; } if (y >= maxY || !this.states.fillColor) return; if (!p5.Font.hasGlyphData(this.states.textFont)) { console.log("WEBGL: only Opentype (.otf) and Truetype (.ttf) fonts with glyph data are supported. Make sure to set the font using textFont() before drawing text."); return; } this.push(); const doStroke = this.states.strokeColor; const drawMode = this.states.drawMode; this.states.setValue("strokeColor", null); this.states.setValue("drawMode", TEXTURE); const { font } = this.states.textFont; if (!font) throw new Error("In WebGL mode, textFont() needs to be given the result of loadFont() instead of a font family name."); const axs = font._currentAxes(this); let fontInfo = font._getFontInfo(axs); const pos = { x, y }; const scale = this.states.textSize / (font.data?.head?.unitsPerEm || 1e3); this.translate(pos.x, pos.y, 0); this.scale(scale, scale, 1); const initializeShader = !this._defaultFontShader; const sh = this._getFontShader(); sh.init(); sh.bindShader("text"); if (initializeShader) { sh.setUniform("uGridImageSize", [gridImageWidth, gridImageHeight]); sh.setUniform("uCellsImageSize", [cellImageWidth, cellImageHeight]); sh.setUniform("uStrokeImageSize", [strokeImageWidth, strokeImageHeight]); sh.setUniform("uGridSize", [charGridWidth, charGridHeight]); } const curFillColor = this.states.fillSet ? this.states.curFillColor : [ 0, 0, 0, 1 ]; this._setGlobalUniforms(sh); this._applyColorBlend(curFillColor); let g = this.geometryBufferCache.getGeometryByID("glyph"); if (!g) { g = this._textGeom = new Geometry(1, 1, function() { for (let i = 0; i <= 1; i++) for (let j = 0; j <= 1; j++) { this.vertices.push(new Vector(j, i, 0)); this.uvs.push(j, i); } }, this); g.gid = "glyph"; g.computeFaces().computeNormals(); this.geometryBufferCache.ensureCached(g); } for (const buff of this.buffers.text) buff._prepareBuffer(g, sh); sh.setUniform("uMaterialColor", curFillColor); this._disableRemainingAttributes(sh); this._beforeDrawText(); this.glyphDataCache = this.glyphDataCache || /* @__PURE__ */ new Set(); try { const glyphs = font._positionGlyphs(line); for (const glyph of glyphs) { const gi = fontInfo.getGlyphInfo(glyph); if (gi.uGlyphRect) { const rowInfo = gi.rowInfo; const colInfo = gi.colInfo; const glyphResources = [ gi.strokeImageInfo.imageData, rowInfo.cellImageInfo.imageData, rowInfo.dimImageInfo.imageData, colInfo.cellImageInfo.imageData, colInfo.dimImageInfo.imageData ]; for (const resource of glyphResources) { this.glyphDataCache.delete(resource); this.glyphDataCache.add(resource); } while (this.glyphDataCache.size > this.maxCachedGlyphs()) { const data = this.glyphDataCache.values().next().value; this.glyphDataCache.delete(data); const tex = this.textures.get(data); if (tex) { tex.remove(); this.textures.delete(data); } } sh.setUniform("uSamplerStrokes", gi.strokeImageInfo.imageData); sh.setUniform("uSamplerRowStrokes", rowInfo.cellImageInfo.imageData); sh.setUniform("uSamplerRows", rowInfo.dimImageInfo.imageData); sh.setUniform("uSamplerColStrokes", colInfo.cellImageInfo.imageData); sh.setUniform("uSamplerCols", colInfo.dimImageInfo.imageData); sh.setUniform("uGridOffset", gi.uGridOffset); sh.setUniform("uGlyphRect", gi.uGlyphRect); sh.setUniform("uGlyphOffset", glyph.x); sh.bindTextures(); this._drawBuffers(g, { mode: 4, count: 1 }); } } } finally { sh.unbindShader(); this.states.setValue("strokeColor", doStroke); this.states.setValue("drawMode", drawMode); this._afterDrawText(); this.pop(); } }; } //#endregion export { text as default };