Debian Codegraph @

node/@xterm/addon-webgl/src/GlyphRenderer.ts

raw
1 /**
2 * Copyright (c) 2018 The xterm.js authors. All rights reserved.
3 * @license MIT
4 */
5 import { TextureAtlas } from './TextureAtlas';
6 import { IRenderDimensions } from 'browser/renderer/shared/Types';
7 import { NULL_CELL_CODE } from 'common/buffer/Constants';
8 import { Disposable, toDisposable } from 'vs/base/common/lifecycle';
9 import { Terminal } from '@xterm/xterm';
10 import { IRenderModel, IWebGL2RenderingContext, IWebGLVertexArrayObject, type IRasterizedGlyph, type ITextureAtlas } from './Types';
11 import { createProgram, GLTexture, PROJECTION_MATRIX } from './WebglUtils';
12 import type { IOptionsService } from 'common/services/Services';
13 import { allowRescaling, throwIfFalsy } from 'browser/renderer/shared/RendererUtils';
14
15 interface IVertices {
16 attributes: Float32Array;
17 /**
18 * These buffers are the ones used to bind to WebGL, the reason there are
19 * multiple is to allow double buffering to work as you cannot modify the
20 * buffer while it's being used by the GPU. Having multiple lets us start
21 * working on the next frame.
22 */
23 attributesBuffers: Float32Array[];
24 count: number;
25 }
26
27 const enum VertexAttribLocations {
28 UNIT_QUAD = 0,
29 CELL_POSITION = 1,
30 OFFSET = 2,
31 SIZE = 3,
32 TEXPAGE = 4,
33 TEXCOORD = 5,
34 TEXSIZE = 6
35 }
36
37 const vertexShaderSource = `#version 300 es
38 layout (location = ${VertexAttribLocations.UNIT_QUAD}) in vec2 a_unitquad;
39 layout (location = ${VertexAttribLocations.CELL_POSITION}) in vec2 a_cellpos;
40 layout (location = ${VertexAttribLocations.OFFSET}) in vec2 a_offset;
41 layout (location = ${VertexAttribLocations.SIZE}) in vec2 a_size;
42 layout (location = ${VertexAttribLocations.TEXPAGE}) in float a_texpage;
43 layout (location = ${VertexAttribLocations.TEXCOORD}) in vec2 a_texcoord;
44 layout (location = ${VertexAttribLocations.TEXSIZE}) in vec2 a_texsize;
45
46 uniform mat4 u_projection;
47 uniform vec2 u_resolution;
48
49 out vec2 v_texcoord;
50 flat out int v_texpage;
51
52 void main() {
53 vec2 zeroToOne = (a_offset / u_resolution) + a_cellpos + (a_unitquad * a_size);
54 gl_Position = u_projection * vec4(zeroToOne, 0.0, 1.0);
55 v_texpage = int(a_texpage);
56 v_texcoord = a_texcoord + a_unitquad * a_texsize;
57 }`;
58
59 function createFragmentShaderSource(maxFragmentShaderTextureUnits: number): string {
60 let textureConditionals = '';
61 for (let i = 1; i < maxFragmentShaderTextureUnits; i++) {
62 textureConditionals += ` else if (v_texpage == ${i}) { outColor = texture(u_texture[${i}], v_texcoord); }`;
63 }
64 return (`#version 300 es
65 precision lowp float;
66
67 in vec2 v_texcoord;
68 flat in int v_texpage;
69
70 uniform sampler2D u_texture[${maxFragmentShaderTextureUnits}];
71
72 out vec4 outColor;
73
74 void main() {
75 if (v_texpage == 0) {
76 outColor = texture(u_texture[0], v_texcoord);
77 } ${textureConditionals}
78 }`);
79 }
80
81 const INDICES_PER_CELL = 11;
82 const BYTES_PER_CELL = INDICES_PER_CELL * Float32Array.BYTES_PER_ELEMENT;
83 const CELL_POSITION_INDICES = 2;
84
85 // Work variables to avoid garbage collection
86 let $i = 0;
87 let $glyph: IRasterizedGlyph | undefined = undefined;
88 let $leftCellPadding = 0;
89 let $clippedPixels = 0;
90
91 export class GlyphRenderer extends Disposable {
92 private readonly _program: WebGLProgram;
93 private readonly _vertexArrayObject: IWebGLVertexArrayObject;
94 private readonly _projectionLocation: WebGLUniformLocation;
95 private readonly _resolutionLocation: WebGLUniformLocation;
96 private readonly _textureLocation: WebGLUniformLocation;
97 private readonly _atlasTextures: GLTexture[];
98 private readonly _attributesBuffer: WebGLBuffer;
99
100 private _atlas: ITextureAtlas | undefined;
101 private _activeBuffer: number = 0;
102 private readonly _vertices: IVertices = {
103 count: 0,
104 attributes: new Float32Array(0),
105 attributesBuffers: [
106 new Float32Array(0),
107 new Float32Array(0)
108 ]
109 };
110
111 constructor(
112 private readonly _terminal: Terminal,
113 private readonly _gl: IWebGL2RenderingContext,
114 private _dimensions: IRenderDimensions,
115 private readonly _optionsService: IOptionsService
116 ) {
117 super();
118
119 const gl = this._gl;
120
121 if (TextureAtlas.maxAtlasPages === undefined) {
122 // Typically 8 or 16
123 TextureAtlas.maxAtlasPages = Math.min(32, throwIfFalsy(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS) as number | null));
124 // Almost all clients will support >= 4096
125 TextureAtlas.maxTextureSize = throwIfFalsy(gl.getParameter(gl.MAX_TEXTURE_SIZE) as number | null);
126 }
127
128 this._program = throwIfFalsy(createProgram(gl, vertexShaderSource, createFragmentShaderSource(TextureAtlas.maxAtlasPages)));
129 this._register(toDisposable(() => gl.deleteProgram(this._program)));
130
131 // Uniform locations
132 this._projectionLocation = throwIfFalsy(gl.getUniformLocation(this._program, 'u_projection'));
133 this._resolutionLocation = throwIfFalsy(gl.getUniformLocation(this._program, 'u_resolution'));
134 this._textureLocation = throwIfFalsy(gl.getUniformLocation(this._program, 'u_texture'));
135
136 // Create and set the vertex array object
137 this._vertexArrayObject = gl.createVertexArray();
138 gl.bindVertexArray(this._vertexArrayObject);
139
140 // Setup a_unitquad, this defines the 4 vertices of a rectangle
141 const unitQuadVertices = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]);
142 const unitQuadVerticesBuffer = gl.createBuffer();
143 this._register(toDisposable(() => gl.deleteBuffer(unitQuadVerticesBuffer)));
144 gl.bindBuffer(gl.ARRAY_BUFFER, unitQuadVerticesBuffer);
145 gl.bufferData(gl.ARRAY_BUFFER, unitQuadVertices, gl.STATIC_DRAW);
146 gl.enableVertexAttribArray(VertexAttribLocations.UNIT_QUAD);
147 gl.vertexAttribPointer(VertexAttribLocations.UNIT_QUAD, 2, this._gl.FLOAT, false, 0, 0);
148
149 // Setup the unit quad element array buffer, this points to indices in
150 // unitQuadVertices to allow is to draw 2 triangles from the vertices via a
151 // triangle strip
152 const unitQuadElementIndices = new Uint8Array([0, 1, 2, 3]);
153 const elementIndicesBuffer = gl.createBuffer();
154 this._register(toDisposable(() => gl.deleteBuffer(elementIndicesBuffer)));
155 gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, elementIndicesBuffer);
156 gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, unitQuadElementIndices, gl.STATIC_DRAW);
157
158 // Setup attributes
159 this._attributesBuffer = throwIfFalsy(gl.createBuffer());
160 this._register(toDisposable(() => gl.deleteBuffer(this._attributesBuffer)));
161 gl.bindBuffer(gl.ARRAY_BUFFER, this._attributesBuffer);
162 gl.enableVertexAttribArray(VertexAttribLocations.OFFSET);
163 gl.vertexAttribPointer(VertexAttribLocations.OFFSET, 2, gl.FLOAT, false, BYTES_PER_CELL, 0);
164 gl.vertexAttribDivisor(VertexAttribLocations.OFFSET, 1);
165 gl.enableVertexAttribArray(VertexAttribLocations.SIZE);
166 gl.vertexAttribPointer(VertexAttribLocations.SIZE, 2, gl.FLOAT, false, BYTES_PER_CELL, 2 * Float32Array.BYTES_PER_ELEMENT);
167 gl.vertexAttribDivisor(VertexAttribLocations.SIZE, 1);
168 gl.enableVertexAttribArray(VertexAttribLocations.TEXPAGE);
169 gl.vertexAttribPointer(VertexAttribLocations.TEXPAGE, 1, gl.FLOAT, false, BYTES_PER_CELL, 4 * Float32Array.BYTES_PER_ELEMENT);
170 gl.vertexAttribDivisor(VertexAttribLocations.TEXPAGE, 1);
171 gl.enableVertexAttribArray(VertexAttribLocations.TEXCOORD);
172 gl.vertexAttribPointer(VertexAttribLocations.TEXCOORD, 2, gl.FLOAT, false, BYTES_PER_CELL, 5 * Float32Array.BYTES_PER_ELEMENT);
173 gl.vertexAttribDivisor(VertexAttribLocations.TEXCOORD, 1);
174 gl.enableVertexAttribArray(VertexAttribLocations.TEXSIZE);
175 gl.vertexAttribPointer(VertexAttribLocations.TEXSIZE, 2, gl.FLOAT, false, BYTES_PER_CELL, 7 * Float32Array.BYTES_PER_ELEMENT);
176 gl.vertexAttribDivisor(VertexAttribLocations.TEXSIZE, 1);
177 gl.enableVertexAttribArray(VertexAttribLocations.CELL_POSITION);
178 gl.vertexAttribPointer(VertexAttribLocations.CELL_POSITION, 2, gl.FLOAT, false, BYTES_PER_CELL, 9 * Float32Array.BYTES_PER_ELEMENT);
179 gl.vertexAttribDivisor(VertexAttribLocations.CELL_POSITION, 1);
180
181 // Setup static uniforms
182 gl.useProgram(this._program);
183 const textureUnits = new Int32Array(TextureAtlas.maxAtlasPages);
184 for (let i = 0; i < TextureAtlas.maxAtlasPages; i++) {
185 textureUnits[i] = i;
186 }
187 gl.uniform1iv(this._textureLocation, textureUnits);
188 gl.uniformMatrix4fv(this._projectionLocation, false, PROJECTION_MATRIX);
189
190 // Setup 1x1 red pixel textures for all potential atlas pages, if one of these invalid textures
191 // is ever drawn it will show characters as red rectangles.
192 this._atlasTextures = [];
193 for (let i = 0; i < TextureAtlas.maxAtlasPages; i++) {
194 const glTexture = new GLTexture(throwIfFalsy(gl.createTexture()));
195 this._register(toDisposable(() => gl.deleteTexture(glTexture.texture)));
196 gl.activeTexture(gl.TEXTURE0 + i);
197 gl.bindTexture(gl.TEXTURE_2D, glTexture.texture);
198 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
199 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
200 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 0, 0, 255]));
201 this._atlasTextures[i] = glTexture;
202 }
203
204 // Allow drawing of transparent texture
205 gl.enable(gl.BLEND);
206 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
207
208 // Set viewport
209 this.handleResize();
210 }
211
212 public beginFrame(): boolean {
213 return this._atlas ? this._atlas.beginFrame() : true;
214 }
215
216 public updateCell(x: number, y: number, code: number, bg: number, fg: number, ext: number, chars: string, width: number, lastBg: number): void {
217 // Since this function is called for every cell (`rows*cols`), it must be very optimized. It
218 // should not instantiate any variables unless a new glyph is drawn to the cache where the
219 // slight slowdown is acceptable for the developer ergonomics provided as it's a once of for
220 // each glyph.
221 this._updateCell(this._vertices.attributes, x, y, code, bg, fg, ext, chars, width, lastBg);
222 }
223
224 private _updateCell(array: Float32Array, x: number, y: number, code: number | undefined, bg: number, fg: number, ext: number, chars: string, width: number, lastBg: number): void {
225 $i = (y * this._terminal.cols + x) * INDICES_PER_CELL;
226
227 // Exit early if this is a null character, allow space character to continue as it may have
228 // underline/strikethrough styles
229 if (code === NULL_CELL_CODE || code === undefined/* This is used for the right side of wide chars */) {
230 array.fill(0, $i, $i + INDICES_PER_CELL - 1 - CELL_POSITION_INDICES);
231 return;
232 }
233
234 if (!this._atlas) {
235 return;
236 }
237
238 // Get the glyph
239 if (chars && chars.length > 1) {
240 $glyph = this._atlas.getRasterizedGlyphCombinedChar(chars, bg, fg, ext, false, this._terminal.element);
241 } else {
242 $glyph = this._atlas.getRasterizedGlyph(code, bg, fg, ext, false, this._terminal.element);
243 }
244
245 $leftCellPadding = Math.floor((this._dimensions.device.cell.width - this._dimensions.device.char.width) / 2);
246 if (bg !== lastBg && $glyph.offset.x > $leftCellPadding) {
247 $clippedPixels = $glyph.offset.x - $leftCellPadding;
248 // a_origin
249 array[$i ] = -($glyph.offset.x - $clippedPixels) + this._dimensions.device.char.left;
250 array[$i + 1] = -$glyph.offset.y + this._dimensions.device.char.top;
251 // a_size
252 array[$i + 2] = ($glyph.size.x - $clippedPixels) / this._dimensions.device.canvas.width;
253 array[$i + 3] = $glyph.size.y / this._dimensions.device.canvas.height;
254 // a_texpage
255 array[$i + 4] = $glyph.texturePage;
256 // a_texcoord
257 array[$i + 5] = $glyph.texturePositionClipSpace.x + $clippedPixels / this._atlas.pages[$glyph.texturePage].canvas.width;
258 array[$i + 6] = $glyph.texturePositionClipSpace.y;
259 // a_texsize
260 array[$i + 7] = $glyph.sizeClipSpace.x - $clippedPixels / this._atlas.pages[$glyph.texturePage].canvas.width;
261 array[$i + 8] = $glyph.sizeClipSpace.y;
262 } else {
263 // a_origin
264 array[$i ] = -$glyph.offset.x + this._dimensions.device.char.left;
265 array[$i + 1] = -$glyph.offset.y + this._dimensions.device.char.top;
266 // a_size
267 array[$i + 2] = $glyph.size.x / this._dimensions.device.canvas.width;
268 array[$i + 3] = $glyph.size.y / this._dimensions.device.canvas.height;
269 // a_texpage
270 array[$i + 4] = $glyph.texturePage;
271 // a_texcoord
272 array[$i + 5] = $glyph.texturePositionClipSpace.x;
273 array[$i + 6] = $glyph.texturePositionClipSpace.y;
274 // a_texsize
275 array[$i + 7] = $glyph.sizeClipSpace.x;
276 array[$i + 8] = $glyph.sizeClipSpace.y;
277 }
278 // a_cellpos only changes on resize
279
280 // Reduce scale horizontally for wide glyphs printed in cells that would overlap with the
281 // following cell (ie. the width is not 2).
282 if (this._optionsService.rawOptions.rescaleOverlappingGlyphs) {
283 if (allowRescaling(code, width, $glyph.size.x, this._dimensions.device.cell.width)) {
284 array[$i + 2] = (this._dimensions.device.cell.width - 1) / this._dimensions.device.canvas.width; // - 1 to improve readability
285 }
286 }
287 }
288
289 public clear(): void {
290 const terminal = this._terminal;
291 const newCount = terminal.cols * terminal.rows * INDICES_PER_CELL;
292
293 // Clear vertices
294 if (this._vertices.count !== newCount) {
295 this._vertices.attributes = new Float32Array(newCount);
296 } else {
297 this._vertices.attributes.fill(0);
298 }
299 let i = 0;
300 for (; i < this._vertices.attributesBuffers.length; i++) {
301 if (this._vertices.count !== newCount) {
302 this._vertices.attributesBuffers[i] = new Float32Array(newCount);
303 } else {
304 this._vertices.attributesBuffers[i].fill(0);
305 }
306 }
307 this._vertices.count = newCount;
308 i = 0;
309 for (let y = 0; y < terminal.rows; y++) {
310 for (let x = 0; x < terminal.cols; x++) {
311 this._vertices.attributes[i + 9] = x / terminal.cols;
312 this._vertices.attributes[i + 10] = y / terminal.rows;
313 i += INDICES_PER_CELL;
314 }
315 }
316 }
317
318 public handleResize(): void {
319 const gl = this._gl;
320 gl.useProgram(this._program);
321 gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
322 gl.uniform2f(this._resolutionLocation, gl.canvas.width, gl.canvas.height);
323 this.clear();
324 }
325
326 public render(renderModel: IRenderModel): void {
327 if (!this._atlas) {
328 return;
329 }
330
331 const gl = this._gl;
332
333 gl.useProgram(this._program);
334 gl.bindVertexArray(this._vertexArrayObject);
335
336 // Alternate buffers each frame as the active buffer gets locked while it's in use by the GPU
337 this._activeBuffer = (this._activeBuffer + 1) % 2;
338 const activeBuffer = this._vertices.attributesBuffers[this._activeBuffer];
339
340 // Copy data for each cell of each line up to its line length (the last non-whitespace cell)
341 // from the attributes buffer into activeBuffer, which is the one that gets bound to the GPU.
342 // The reasons for this are as follows:
343 // - So the active buffer can be alternated so we don't get blocked on rendering finishing
344 // - To copy either the normal attributes buffer or the selection attributes buffer when there
345 // is a selection
346 // - So we don't send vertices for all the line-ending whitespace to the GPU
347 let bufferLength = 0;
348 for (let y = 0; y < renderModel.lineLengths.length; y++) {
349 const si = y * this._terminal.cols * INDICES_PER_CELL;
350 const sub = this._vertices.attributes.subarray(si, si + renderModel.lineLengths[y] * INDICES_PER_CELL);
351 activeBuffer.set(sub, bufferLength);
352 bufferLength += sub.length;
353 }
354
355 // Bind the attributes buffer
356 gl.bindBuffer(gl.ARRAY_BUFFER, this._attributesBuffer);
357 gl.bufferData(gl.ARRAY_BUFFER, activeBuffer.subarray(0, bufferLength), gl.STREAM_DRAW);
358
359 // Bind the atlas page texture if they have changed
360 for (let i = 0; i < this._atlas.pages.length; i++) {
361 if (this._atlas.pages[i].version !== this._atlasTextures[i].version) {
362 this._bindAtlasPageTexture(gl, this._atlas, i);
363 }
364 }
365
366 // Draw the viewport
367 gl.drawElementsInstanced(gl.TRIANGLE_STRIP, 4, gl.UNSIGNED_BYTE, 0, bufferLength / INDICES_PER_CELL);
368 }
369
370 public setAtlas(atlas: ITextureAtlas): void {
371 this._atlas = atlas;
372 for (const glTexture of this._atlasTextures) {
373 glTexture.version = -1;
374 }
375 }
376
377 private _bindAtlasPageTexture(gl: IWebGL2RenderingContext, atlas: ITextureAtlas, i: number): void {
378 gl.activeTexture(gl.TEXTURE0 + i);
379 gl.bindTexture(gl.TEXTURE_2D, this._atlasTextures[i].texture);
380 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
381 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
382 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, atlas.pages[i].canvas);
383 gl.generateMipmap(gl.TEXTURE_2D);
384 this._atlasTextures[i].version = atlas.pages[i].version;
385 }
386
387 public setDimensions(dimensions: IRenderDimensions): void {
388 this._dimensions = dimensions;
389 }
390 }