-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfont_renderer.js
512 lines (437 loc) · 17.2 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
/**
* Attributes
*/
pc.script.attribute('text', 'string');
// the maximum length of the text - used to set the initial size of the vertex buffer
pc.script.attribute('maxTextLength', 'number', 256);
// The texture atlas that contains all the letters - this has to be
// a png file with alpha
pc.script.attribute('fontAtlas', 'asset', [], {
type: 'texture',
max: 1
});
// text json file that contains all the font metadata (converted from an .fnt file)
pc.script.attribute('fontJson', 'asset', [], {
type: 'json',
max: 1
});
pc.script.attribute('x', 'number');
pc.script.attribute('y', 'number');
pc.script.attribute('depth', 'number', 1)
pc.script.attribute('anchor', 'enumeration', 0, {
enumerations: [{
name: 'topLeft',
value: 0
}, {
name: 'top',
value: 1
}, {
name: 'topRight',
value: 2
}, {
name: 'left',
value: 3
}, {
name: 'center',
value: 4
}, {
name: 'right',
value: 5
}, {
name: 'bottomLeft',
value: 6
}, {
name: 'bottom',
value: 7
}, {
name: 'bottomRight',
value: 8
}]
});
pc.script.attribute('pivot', 'enumeration', 0, {
enumerations: [{
name: 'topLeft',
value: 0
}, {
name: 'top',
value: 1
}, {
name: 'topRight',
value: 2
}, {
name: 'left',
value: 3
}, {
name: 'center',
value: 4
}, {
name: 'right',
value: 5
}, {
name: 'bottomLeft',
value: 6
}, {
name: 'bottom',
value: 7
}, {
name: 'bottomRight',
value: 8
}]
});
pc.script.attribute('tint', 'rgba', [1,1,1,1]);
pc.script.attribute('maxResHeight', 'number', 720);
pc.script.create('font_renderer', function (context) {
var shader = null;
var vertexFormat = null;
var resolution = new pc.Vec2();
// Creates a new Font_renderer instance
var Font_renderer = function (entity) {
this.entity = entity;
};
Font_renderer.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;
// Create shader
var gd = context.graphicsDevice;
if (!shader) {
var shaderDefinition = {
attributes: {
aPosition: pc.gfx.SEMANTIC_POSITION,
aUv0: pc.gfx.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")
};
shader = new pc.gfx.Shader(gd, shaderDefinition);
}
// Create the vertex format
if (!vertexFormat) {
vertexFormat = new pc.gfx.VertexFormat(gd, [
{ semantic: pc.gfx.SEMANTIC_POSITION, components: 2, type: pc.gfx.ELEMENTTYPE_FLOAT32 },
{ semantic: pc.gfx.SEMANTIC_TEXCOORD0, components: 2, type: pc.gfx.ELEMENTTYPE_FLOAT32 }
]);
}
// Load font assets
var assets = [
context.assets.getAssetById(this.fontAtlas),
context.assets.getAssetById(this.fontJson),
];
context.assets.load(assets).then(function (resources) {
this.atlas = resources[0];
this.font = resources[1];
// Create a vertex buffer
this.vertexBuffer = new pc.gfx.VertexBuffer(gd, vertexFormat, 6*this.maxTextLength, pc.gfx.BUFFER_DYNAMIC);
this.updateText(this.text);
var command = new pc.scene.Command(pc.scene.LAYER_HUD, pc.scene.BLEND_NORMAL, function () {
if (this.entity.enabled) {
// Set the shader
gd.setShader(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.gfx.BLENDMODE_SRC_ALPHA, pc.gfx.BLENDMODE_ONE_MINUS_SRC_ALPHA);
resolution.set(canvas.offsetWidth, canvas.offsetHeight);
gd.scope.resolve("uResolution").setValue(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.gfx.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;
context.scene.drawCalls.push(command);
this.on('set', this.onAttributeChanged, this);
}.bind(this));
context.mouse.on('mousedown', this.onMouseDown, this);
if (context.touch) {
context.touch.on('touchstart', this.onTouchDown, this);
}
},
onMouseDown: function (e) {
if (!this.eventsEnabled) {
return;
}
this.onClick(e);
},
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
*/
onClick: function (cursor) {
var canvas = context.graphicsDevice.canvas;
var tlx, tly, brx, bry, mx, my;
var scaling = this.scaling;
var offset = this.offset;
tlx = 2.0 * (scaling.x * 0 + offset.x) / resolution.x - 1.0;
tly = 2.0 * (scaling.y * 0 + offset.y) / resolution.y - 1.0;
brx = 2.0 * (scaling.x * this.width + offset.x) / resolution.x - 1.0;
bry = 2.0 * (scaling.y * (- this.height) + offset.y) / 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
*/
onAttributeChanged: function (name, oldValue, newValue) {
this.eventsEnabled = false;
if (name === 'text' ) {
if (oldValue !== newValue) {
this.updateText();
}
} else if (name === 'depth') {
this.command.key = newValue;
}
},
getTotalOffset: function (result) {
result.copy(this.userOffset).add(this.alignOffset);
return result;
},
updateText: function () {
// Fill the vertex buffer
this.vertexBuffer.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 kerning = 0;
var text = this.text;
var textLength = text.length;
var i;
this.width = 0;
this.height = 0;
var iterator = new pc.gfx.VertexIterator(this.vertexBuffer);
for (i = 0; i < textLength; i++) {
var charId = text.charCodeAt(i);
var fontChar = this.font.chars[charId];
// 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 = cursorY - yoffset;
this.width = Math.max(this.width, tempCursorX + width);
this.height = Math.max(this.height, tempCursorY + height);
// Add vertices
iterator.element[pc.gfx.SEMANTIC_POSITION].set(tempCursorX, tempCursorY - height);
iterator.element[pc.gfx.SEMANTIC_TEXCOORD0].set(uv0, uv1);
iterator.next();
iterator.element[pc.gfx.SEMANTIC_POSITION].set(tempCursorX + width, tempCursorY - height);
iterator.element[pc.gfx.SEMANTIC_TEXCOORD0].set(uv2, uv1);
iterator.next();
iterator.element[pc.gfx.SEMANTIC_POSITION].set(tempCursorX, tempCursorY);
iterator.element[pc.gfx.SEMANTIC_TEXCOORD0].set(uv0, uv3);
iterator.next();
iterator.element[pc.gfx.SEMANTIC_POSITION].set(tempCursorX + width, tempCursorY - height);
iterator.element[pc.gfx.SEMANTIC_TEXCOORD0].set(uv2, uv1);
iterator.next();
iterator.element[pc.gfx.SEMANTIC_POSITION].set(tempCursorX + width, tempCursorY);
iterator.element[pc.gfx.SEMANTIC_TEXCOORD0].set(uv2, uv3);
iterator.next();
iterator.element[pc.gfx.SEMANTIC_POSITION].set(tempCursorX, tempCursorY);
iterator.element[pc.gfx.SEMANTIC_TEXCOORD0].set(uv0, uv3);
if (i == textLength - 1) {
iterator.end();
} else {
iterator.next();
var nextId = text.charCodeAt(i+1);
kerning = this.font.kernings[charId] && this.font.kernings[charId][nextId] ?
this.font.kernings[charId][nextId] :
0;
// Advance the cursor by xadvance adding kerning if necessary for the current character pair
cursorX += (fontChar.xadvance + kerning);
}
}
this.vertexBuffer.unlock();
},
calculateOffset: function () {
var canvas = context.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;
},
calculateScaling: function () {
var canvas = context.graphicsDevice.canvas;
var scale = canvas.offsetHeight / this.maxResHeight;
this.scaling.set(scale, scale);
return this.scaling;
},
calculateAnchorOffset: function () {
var canvas = context.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;
},
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;
},
onEnable: function () {
this.eventsEnabled = false;
},
onDisable: function () {
this.eventsEnabled = false;
},
update: function (dt) {
this.eventsEnabled = true;
},
};
return Font_renderer;
});