This repository was archived by the owner on Jan 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathfont_renderer.js
552 lines (466 loc) · 16.4 KB
/
font_renderer.js
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
var FontRenderer = pc.createScript('fontRenderer');
/**
* Attributes
*/
FontRenderer.attributes.add('text', {
type: 'string'
});
FontRenderer.attributes.add('maxTextLength', {
type: 'number',
default: 256,
description: 'The maximum length of the text - used to set the initial size of the vertex buffer'
});
FontRenderer.attributes.add('fontAtlas', {
type: 'asset',
assetType: 'texture',
description: 'The texture atlas that contains all the letters, this has to be a png file with an alpha channel'
});
FontRenderer.attributes.add('fontJson', {
type: 'asset',
assetType: 'json',
description: 'JSON file that contains all the font metadata that was converted from an .fnt file'
});
FontRenderer.attributes.add('x', {
type: 'number',
default: 0,
description: 'The x coordinate in pixels'
});
FontRenderer.attributes.add('y', {
type: 'number',
default: 0,
description: 'The y coordinate in pixels'
});
FontRenderer.attributes.add('depth', {
type: 'number',
default: 1,
description: 'The z depth of the font compared to other fonts'
});
FontRenderer.attributes.add('anchor', {
type: 'number',
default: 0,
description: 'The anchor of the font related to the screen bounds',
enum: [
{ 'topLeft': 0 },
{ 'top': 1 },
{ 'topRight': 2 },
{ 'left': 3 },
{ 'center': 4 },
{ 'right': 5 },
{ 'bottomLeft': 6 },
{ 'bottom': 7 },
{ 'bottomRight': 8 }
]
});
FontRenderer.attributes.add('pivot', {
type: 'number',
default: 0,
description: 'The pivot point of the font',
enum: [
{ 'topLeft': 0 },
{ 'top': 1 },
{ 'topRight': 2 },
{ 'left': 3 },
{ 'center': 4 },
{ 'right': 5 },
{ 'bottomLeft': 6 },
{ 'bottom': 7 },
{ 'bottomRight': 8 }
]
});
FontRenderer.attributes.add('tint', {
type: 'rgba',
description: 'A color that is multiplied with the current color of the font',
default: [ 1, 1, 1, 1 ]
});
FontRenderer.attributes.add('maxResHeight', {
type: 'number',
default: 720,
description: 'The maximum resolution height of the application. Used to scale the font accordingly.'
});
/**
* Static variables
*/
FontRenderer.material = null;
FontRenderer.vertexFormat = null;
FontRenderer.resolution = new pc.Vec2();
// initialize code called once per entity
FontRenderer.prototype.initialize = function() {
var canvas = document.getElementById('application-canvas');
this.userOffset = new pc.Vec2();
this.offset = new pc.Vec2();
this.scaling = new pc.Vec2();
this.anchorOffset = new pc.Vec2();
this.pivotOffset = new pc.Vec2();
this.width = 0;
this.height = 0;
var app = this.app;
// Create shader and material
var gd = app.graphicsDevice;
if (!FontRenderer.material) {
var shaderDefinition = {
attributes: {
aPosition: pc.SEMANTIC_POSITION,
aUv0: pc.SEMANTIC_TEXCOORD0
},
vshader: [
"attribute vec2 aPosition;",
"attribute vec2 aUv0;",
"varying vec2 vUv0;",
"uniform vec2 uResolution;",
"uniform vec2 uOffset;",
"uniform vec2 uScale;",
"",
"void main(void)",
"{",
" gl_Position = vec4(2.0 * ((uScale * aPosition.xy + uOffset) / uResolution ) - 1.0, -0.9, 1.0);",
" vUv0 = aUv0;",
"}"
].join("\n"),
fshader: [
"precision " + gd.precision + " float;",
"",
"varying vec2 vUv0;",
"",
"uniform vec4 vTint;",
"",
"uniform sampler2D uColorMap;",
"",
"void main(void)",
"{",
" vec4 color = texture2D(uColorMap, vUv0);",
" gl_FragColor = vec4(color.rgb * vTint.rgb, color.a * vTint.a);",
"}"
].join("\n")
};
var shader = new pc.Shader(gd, shaderDefinition);
var material = new pc.Material();
material.shader = shader;
material.blend = true;
material.blendSrc = pc.BLENDMODE_SRC_ALPHA;
material.blendDst = pc.BLENDMODE_ONE_MINUS_SRC_ALPHA;
material.depthTest = false;
material.depthWrite = false;
FontRenderer.material = material;
}
// Create the vertex format
if (!FontRenderer.vertexFormat) {
FontRenderer.vertexFormat = new pc.VertexFormat(gd, [
{ semantic: pc.SEMANTIC_POSITION, components: 2, type: pc.ELEMENTTYPE_FLOAT32 },
{ semantic: pc.SEMANTIC_TEXCOORD0, components: 2, type: pc.ELEMENTTYPE_FLOAT32 }
]);
}
if (! this.fontAtlas)
return;
this.atlas = this.fontAtlas.resource;
this.font = this.fontJson.resource;
// Create mesh
var mesh = new pc.Mesh();
mesh.vertexBuffer = new pc.VertexBuffer(gd, FontRenderer.vertexFormat, 6 * this.maxTextLength, pc.BUFFER_DYNAMIC);
mesh.primitive[0].type = pc.PRIMITIVE_TRIANGLES;
mesh.primitive[0].base = 0;
mesh.primitive[0].count = 6 * this.maxTextLength;
mesh.primitive[0].indexed = false;
// Create mesh instance
this.meshInstance = new pc.MeshInstance(this.entity, mesh, FontRenderer.material);
this.meshInstance.castShadow = false;
this.meshInstance.receiveShadow = false;
this.meshInstance.drawOrder = this.depth;
this.updateText(this.text);
// Get layer
this.layer = app.scene.layers.getLayerById(pc.LAYERID_UI) || app.scene.layers.getLayerById(pc.LAYERID_WORLD);
// var command = new pc.Command(pc.LAYER_HUD, pc.BLEND_NORMAL, function () {
// if (this.entity.enabled) {
// // Set the shader
// gd.setShader(FontRenderer.shader);
// var oldBlending = gd.getBlending();
// var oldDepthTest = gd.getDepthTest();
// var oldDepthWrite = gd.getDepthWrite();
// gd.setBlending(true);
// gd.setDepthTest(false);
// gd.setDepthWrite(false);
// gd.setBlendFunction(pc.BLENDMODE_SRC_ALPHA, pc.BLENDMODE_ONE_MINUS_SRC_ALPHA);
// FontRenderer.resolution.set(canvas.offsetWidth, canvas.offsetHeight);
// gd.scope.resolve("uResolution").setValue(FontRenderer.resolution.data);
// gd.scope.resolve("uScale").setValue(this.calculateScaling().data);
// gd.scope.resolve("uOffset").setValue(this.calculateOffset().data);
// gd.scope.resolve("uColorMap").setValue(this.atlas);
// gd.scope.resolve("vTint").setValue(this.tint.data);
// // Set the vertex buffer
// gd.setVertexBuffer(this.vertexBuffer, 0);
// gd.draw({
// type: pc.PRIMITIVE_TRIANGLES,
// base: 0,
// count: this.text.length * 6,
// indexed: false
// });
// gd.setBlending(oldBlending);
// gd.setDepthTest(oldDepthTest);
// gd.setDepthWrite(oldDepthWrite);
// }
// }.bind(this));
// this.command = command;
// command.key = this.depth;
// app.scene.drawCalls.push(command);
this.on('attr', this.onAttributeChanged, this);
this.on('state', this.onState);
this.on('destroy', this.onDestroy);
app.mouse.on('mousedown', this.onMouseDown, this);
if (app.touch)
app.touch.on('touchstart', this.onTouchDown, this);
this.onState(true);
};
FontRenderer.prototype.onMouseDown = function (e) {
if (!this.eventsEnabled)
return;
this.onClick(e);
};
FontRenderer.prototype.onTouchDown = function (e) {
if (!this.eventsEnabled)
return;
this.onClick(e.changedTouches[0]);
};
/**
* Calculates if the click has happened inside the rect of this
* sprite and fires 'click' event if it has
*/
FontRenderer.prototype.onClick = function (cursor) {
var canvas = this.app.graphicsDevice.canvas;
var tlx, tly, brx, bry, mx, my;
var scaling = this.scaling;
var offset = this.offset;
var width = this.width;
var height = this.height;
tlx = 2.0 * (scaling.x * 0 + offset.x) / FontRenderer.resolution.x - 1.0;
tly = 2.0 * (scaling.y * 0 + offset.y) / FontRenderer.resolution.y - 1.0;
brx = 2.0 * (scaling.x * width + offset.x) / FontRenderer.resolution.x - 1.0;
bry = 2.0 * (scaling.y * (- height) + offset.y) / FontRenderer.resolution.y - 1.0;
mx = (2.0 * cursor.x / canvas.offsetWidth) - 1;
my = (2.0 * (canvas.offsetHeight - cursor.y) / canvas.offsetHeight) - 1;
if (mx >= tlx && mx <= brx &&
my <= tly && my >= bry) {
this.fire('click');
}
};
/**
* Re-render the text if necessary
*/
FontRenderer.prototype.onAttributeChanged = function (name, newValue, oldValue) {
this.eventsEnabled = false;
if (name === 'text' ) {
if (oldValue !== newValue)
this.updateText();
} else if (name === 'depth') {
this.meshInstance.drawOrder = newValue;
}
};
FontRenderer.prototype.getTotalOffset = function (result) {
return result.copy(this.userOffset).add(this.alignOffset);
};
FontRenderer.prototype.updateText = function () {
// Fill the vertex buffer
var vb = this.meshInstance.mesh.vertexBuffer;
vb.lock();
// the cursor controls the position of the next character to be drawn
var cursorX = 0;
var cursorY = 0;
var tempCursorX = cursorX;
var tempCursorY = cursorY;
var uv0;
var uv1;
var uv2;
var uv3;
var text = this.text;
var textLength = text.length;
var i;
this.width = 0;
this.height = 0;
var iterator = new pc.VertexIterator(vb);
for (i = 0; i < textLength; i++) {
var charId = text.charCodeAt(i);
var fontChar = this.font.chars[charId];
// Check we have the requested character
if (fontChar === undefined)
continue;
// Get the uv's for our letter - these will be looked up in the texture atlas
uv0 = fontChar.x / this.font.common.scaleW;
uv1 = 1 - (fontChar.y + fontChar.height) / (this.font.common.scaleH);
uv2 = (fontChar.x + fontChar.width) / this.font.common.scaleW;
uv3 = 1 - fontChar.y / this.font.common.scaleH;
var width = fontChar.width;
var height = fontChar.height;
var xoffset = fontChar.xoffset;
var yoffset = fontChar.yoffset;
// offset the cursor by the appropriate amount for each letter
tempCursorX = cursorX + xoffset;
tempCursorY = -yoffset;
this.width = Math.max(this.width, tempCursorX + width);
this.height = Math.max(this.height, tempCursorY + height);
// Add vertices
iterator.element[pc.SEMANTIC_POSITION].set(tempCursorX, tempCursorY - height);
iterator.element[pc.SEMANTIC_TEXCOORD0].set(uv0, uv1);
iterator.next();
iterator.element[pc.SEMANTIC_POSITION].set(tempCursorX + width, tempCursorY - height);
iterator.element[pc.SEMANTIC_TEXCOORD0].set(uv2, uv1);
iterator.next();
iterator.element[pc.SEMANTIC_POSITION].set(tempCursorX, tempCursorY);
iterator.element[pc.SEMANTIC_TEXCOORD0].set(uv0, uv3);
iterator.next();
iterator.element[pc.SEMANTIC_POSITION].set(tempCursorX + width, tempCursorY - height);
iterator.element[pc.SEMANTIC_TEXCOORD0].set(uv2, uv1);
iterator.next();
iterator.element[pc.SEMANTIC_POSITION].set(tempCursorX + width, tempCursorY);
iterator.element[pc.SEMANTIC_TEXCOORD0].set(uv2, uv3);
iterator.next();
iterator.element[pc.SEMANTIC_POSITION].set(tempCursorX, tempCursorY);
iterator.element[pc.SEMANTIC_TEXCOORD0].set(uv0, uv3);
if (i == textLength - 1) {
iterator.end();
} else {
iterator.next();
var nextId = text.charCodeAt(i+1);
var kerning = 0;
if (this.font.kernings[charId] && this.font.kernings[charId][nextId])
kerning = this.font.kernings[charId][nextId];
// Advance the cursor by xadvance adding kerning if necessary for the current character pair
cursorX += (fontChar.xadvance + kerning);
}
}
vb.unlock();
this.meshInstance.mesh.primitive[0].count = 6 * this.text.length;
};
FontRenderer.prototype.calculateOffset = function () {
var canvas = this.app.graphicsDevice.canvas;
this.calculateAnchorOffset();
this.calculatePivotOffset();
this.offset.set(this.x * this.scaling.x, this.y * this.scaling.y)
.add(this.userOffset)
.add(this.anchorOffset)
.add(this.pivotOffset);
this.offset.y += canvas.offsetHeight;
return this.offset;
};
FontRenderer.prototype.calculateScaling = function () {
var canvas = this.app.graphicsDevice.canvas;
var scale = canvas.offsetHeight / this.maxResHeight;
this.scaling.set(scale, scale);
return this.scaling;
};
FontRenderer.prototype.calculateAnchorOffset = function () {
var canvas = this.app.graphicsDevice.canvas;
var width = canvas.offsetWidth;
var height = canvas.offsetHeight;
switch (this.anchor) {
// top left
case 0:
this.anchorOffset.set(0,0);
break;
// top
case 1:
this.anchorOffset.set(width * 0.5, 0);
break;
// top right
case 2:
this.anchorOffset.set(width, 0);
break;
// left
case 3:
this.anchorOffset.set(0, -height * 0.5);
break;
// center
case 4:
this.anchorOffset.set(width * 0.5, -height * 0.5);
break;
// right
case 5:
this.anchorOffset.set(width, -height * 0.5);
break;
// bottom left
case 6:
this.anchorOffset.set(0, -height);
break;
// bottom
case 7:
this.anchorOffset.set(width/2, -height);
break;
// bottom right
case 8:
this.anchorOffset.set(width, -height);
break;
default:
console.error('Wrong anchor: ' + this.anchor);
break;
}
return this.anchorOffset;
};
FontRenderer.prototype.calculatePivotOffset = function () {
var width = this.width * this.scaling.x;
var height = this.height * this.scaling.y;
switch (this.pivot) {
// top left
case 0:
this.pivotOffset.set(0,0);
break;
// top
case 1:
this.pivotOffset.set(-width * 0.5, 0);
break;
// top right
case 2:
this.pivotOffset.set(-width, 0);
break;
// left
case 3:
this.pivotOffset.set(0, height * 0.5);
break;
// center
case 4:
this.pivotOffset.set(-width * 0.5, height * 0.5);
break;
// right
case 5:
this.pivotOffset.set(-width, height * 0.5);
break;
// bottom left
case 6:
this.pivotOffset.set(0, height);
break;
// bottom
case 7:
this.pivotOffset.set(-width/2, height);
break;
// bottom right
case 8:
this.pivotOffset.set(-width, height);
break;
default:
console.error('Wrong pivot: ' + this.pivot);
break;
}
return this.pivotOffset;
};
FontRenderer.prototype.onState = function (enabled) {
this.eventsEnabled = false;
if (this.layer) {
if (enabled) {
this.layer.addMeshInstances([this.meshInstance]);
} else {
this.layer.removeMeshInstances([this.meshInstance]);
}
}
};
FontRenderer.prototype.update = function (dt) {
this.eventsEnabled = true;
var canvas = this.app.graphicsDevice.canvas;
FontRenderer.resolution.set(canvas.offsetWidth, canvas.offsetHeight);
this.meshInstance.setParameter('uResolution', FontRenderer.resolution.data);
this.meshInstance.setParameter('uScale', this.calculateScaling().data);
this.meshInstance.setParameter('uOffset', this.calculateOffset().data);
this.meshInstance.setParameter('uColorMap', this.atlas);
this.meshInstance.setParameter('vTint', this.tint.data);
};
FontRenderer.prototype.onDestroy = function () {
// remove mesh instance
if (this.layer) {
this.layer.removeMeshInstances([this.meshInstance]);
}
};