-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathHypertextBase.cs
378 lines (312 loc) · 12 KB
/
HypertextBase.cs
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
/*
* uGUI-Hypertext (https://github.com/setchi/uGUI-Hypertext)
* Copyright (c) 2019 setchi
* Licensed under MIT (https://github.com/setchi/uGUI-Hypertext/blob/master/LICENSE)
*/
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace Hypertext
{
public abstract class HypertextBase : Text, IPointerClickHandler
{
class Span
{
public readonly int StartIndex;
public readonly int Length;
public readonly Color Color;
public readonly Action<string> Callback;
public List<Rect> BoundingBoxes;
public Span(int startIndex, int length, Color color, Action<string> callback)
{
StartIndex = startIndex;
Length = length;
Color = color;
Callback = callback;
BoundingBoxes = new List<Rect>();
}
};
readonly List<Span> spans = new List<Span>();
// TODO: 頂点が生成されない空白文字をすべて洗い出す
readonly char[] invisibleChars =
{
Space,
Tab,
LineFeed
};
static readonly ObjectPool<List<UIVertex>> verticesPool = new ObjectPool<List<UIVertex>>(null, l => l.Clear());
const int CharVerts = 6;
const char
Tab = '\t',
LineFeed = '\n',
Space = ' ',
LesserThan = '<',
GreaterThan = '>';
int[] visibleCharIndexMap;
Canvas rootCanvas;
Canvas RootCanvas => rootCanvas ?? (rootCanvas = GetComponentInParent<Canvas>());
/// <summary>
/// 指定した部分文字列にクリックイベントリスナを登録します
/// </summary>
/// <param name="startIndex">部分文字列の開始文字位置</param>
/// <param name="length">部分文字列の長さ</param>
/// <param name="color">部分文字列につける色</param>
/// <param name="onClick">部分文字列がクリックされたときのコールバック</param>
protected void OnClick(int startIndex, int length, Color color, Action<string> onClick)
{
if (onClick == null)
{
throw new ArgumentNullException(nameof(onClick));
}
if (startIndex < 0 || startIndex > text.Length - 1)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
if (length < 1 || startIndex + length > text.Length)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
spans.Add(new Span(startIndex, length, color, onClick));
}
/// <summary>
/// イベントリスナを削除します
/// </summary>
public virtual void RemoveListeners()
{
spans.Clear();
}
/// <summary>
/// イベントリスナを追加します
/// テキストの変更などでイベントリスナの再登録が必要なときにも呼び出されます
/// <see cref="HypertextBase.OnClick"/> を使ってクリックイベントリスナを登録してください
/// </summary>
protected abstract void AddListeners();
readonly UIVertex[] tempVerts = new UIVertex[4];
protected override void OnPopulateMesh(VertexHelper toFill)
{
if (font == null)
{
return;
}
m_DisableFontTextureRebuiltCallback = true;
var extents = rectTransform.rect.size;
var settings = GetGenerationSettings(extents);
settings.generateOutOfBounds = true;
cachedTextGenerator.PopulateWithErrors(text, settings, gameObject);
var verts = cachedTextGenerator.verts;
var unitsPerPixel = 1 / pixelsPerUnit;
int vertCount = verts.Count;
if (vertCount <= 0)
{
toFill.Clear();
return;
}
var roundingOffset = new Vector2(verts[0].position.x, verts[0].position.y) * unitsPerPixel;
roundingOffset = PixelAdjustPoint(roundingOffset) - roundingOffset;
toFill.Clear();
if (roundingOffset != Vector2.zero)
{
for (int i = 0; i < vertCount; ++i)
{
int tempVertsIndex = i & 3;
tempVerts[tempVertsIndex] = verts[i];
tempVerts[tempVertsIndex].position *= unitsPerPixel;
tempVerts[tempVertsIndex].position.x += roundingOffset.x;
tempVerts[tempVertsIndex].position.y += roundingOffset.y;
if (tempVertsIndex == 3)
{
toFill.AddUIVertexQuad(tempVerts);
}
}
}
else
{
for (int i = 0; i < vertCount; ++i)
{
int tempVertsIndex = i & 3;
tempVerts[tempVertsIndex] = verts[i];
tempVerts[tempVertsIndex].position *= unitsPerPixel;
if (tempVertsIndex == 3)
{
toFill.AddUIVertexQuad(tempVerts);
}
}
}
var vertices = verticesPool.Get();
toFill.GetUIVertexStream(vertices);
GenerateVisibleCharIndexMap(vertices.Count < text.Length * CharVerts);
spans.Clear();
AddListeners();
GenerateHrefBoundingBoxes(ref vertices);
toFill.Clear();
toFill.AddUIVertexTriangleStream(vertices);
verticesPool.Release(vertices);
m_DisableFontTextureRebuiltCallback = false;
}
void GenerateHrefBoundingBoxes(ref List<UIVertex> vertices)
{
var verticesCount = vertices.Count;
for (var i = 0; i < spans.Count; i++)
{
var span = spans[i];
var startIndex = visibleCharIndexMap[span.StartIndex];
var endIndex = visibleCharIndexMap[span.StartIndex + span.Length - 1];
for (var textIndex = startIndex; textIndex <= endIndex; textIndex++)
{
var vertexStartIndex = textIndex * CharVerts;
if (vertexStartIndex + CharVerts > verticesCount)
{
break;
}
var min = Vector2.one * float.MaxValue;
var max = Vector2.one * float.MinValue;
for (var vertexIndex = 0; vertexIndex < CharVerts; vertexIndex++)
{
var vertex = vertices[vertexStartIndex + vertexIndex];
vertex.color = span.Color;
vertices[vertexStartIndex + vertexIndex] = vertex;
var pos = vertices[vertexStartIndex + vertexIndex].position;
if (pos.y < min.y)
{
min.y = pos.y;
}
if (pos.x < min.x)
{
min.x = pos.x;
}
if (pos.y > max.y)
{
max.y = pos.y;
}
if (pos.x > max.x)
{
max.x = pos.x;
}
}
span.BoundingBoxes.Add(new Rect {min = min, max = max});
}
// 文字ごとのバウンディングボックスを行ごとのバウンディングボックスにまとめる
span.BoundingBoxes = CalculateLineBoundingBoxes(span.BoundingBoxes);
}
}
static List<Rect> CalculateLineBoundingBoxes(List<Rect> charBoundingBoxes)
{
var lineBoundingBoxes = new List<Rect>();
var lineStartIndex = 0;
for (var i = 1; i < charBoundingBoxes.Count; i++)
{
if (charBoundingBoxes[i].xMin >= charBoundingBoxes[i - 1].xMin)
{
continue;
}
lineBoundingBoxes.Add(CalculateAABB(charBoundingBoxes.GetRange(lineStartIndex, i - lineStartIndex)));
lineStartIndex = i;
}
if (lineStartIndex < charBoundingBoxes.Count)
{
lineBoundingBoxes.Add(CalculateAABB(charBoundingBoxes.GetRange(lineStartIndex, charBoundingBoxes.Count - lineStartIndex)));
}
return lineBoundingBoxes;
}
static Rect CalculateAABB(IReadOnlyList<Rect> rects)
{
var min = Vector2.one * float.MaxValue;
var max = Vector2.one * float.MinValue;
for (var i = 0; i < rects.Count; i++)
{
if (rects[i].xMin < min.x)
{
min.x = rects[i].xMin;
}
if (rects[i].yMin < min.y)
{
min.y = rects[i].yMin;
}
if (rects[i].xMax > max.x)
{
max.x = rects[i].xMax;
}
if (rects[i].yMax > max.y)
{
max.y = rects[i].yMax;
}
}
return new Rect {min = min, max = max};
}
void GenerateVisibleCharIndexMap(bool verticesReduced)
{
if (visibleCharIndexMap == null || visibleCharIndexMap.Length < text.Length)
{
Array.Resize(ref visibleCharIndexMap, text.Length);
}
if (!verticesReduced)
{
for (var i = 0; i < visibleCharIndexMap.Length; i++)
{
visibleCharIndexMap[i] = i;
}
return;
}
var offset = 0;
var inTag = false;
for (var i = 0; i < text.Length; i++)
{
var character = text[i];
if (inTag)
{
offset--;
if (character == GreaterThan)
{
inTag = false;
}
}
else if (supportRichText && character == LesserThan)
{
offset--;
inTag = true;
}
else if (invisibleChars.Contains(character))
{
offset--;
}
visibleCharIndexMap[i] = Mathf.Max(0, i + offset);
}
}
Vector3 CalculateLocalPosition(Vector3 position, Camera pressEventCamera)
{
if (!RootCanvas)
{
return Vector3.zero;
}
if (RootCanvas.renderMode == RenderMode.ScreenSpaceOverlay)
{
return transform.InverseTransformPoint(position);
}
RectTransformUtility.ScreenPointToLocalPointInRectangle(
rectTransform,
position,
pressEventCamera,
out var localPosition
);
return localPosition;
}
void IPointerClickHandler.OnPointerClick(PointerEventData eventData)
{
var localPosition = CalculateLocalPosition(eventData.position, eventData.pressEventCamera);
for (var s = 0; s < spans.Count; s++)
{
for (var b = 0; b < spans[s].BoundingBoxes.Count; b++)
{
if (spans[s].BoundingBoxes[b].Contains(localPosition))
{
spans[s].Callback(text.Substring(spans[s].StartIndex, spans[s].Length));
break;
}
}
}
}
}
}