Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(text): Text can underline its lines and grow its box to its text (ResizeHeight), and the Cocos Label maps onto both

yhhffc01f270312
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fd6311c93..f033d3018 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,7 @@ published separately; it ships inside the editor.
- **Scroll areas can be pulled past an end and spring back.** A scroll area whose movement is Elastic now does what the setting always said: a drag past an end is stiffer the further out it goes, letting go returns the content, and a flick that reaches an end bounces off it. It is opt-in per area (`ScrollMovement.Elastic`; Clamped, the default, behaves as before), and the gesture model (`ScrollMotion`, with `ScrollContainer.dragTo` and `getOverscroll`) is exported for scrolling anything else the same way.
- **More easing curves.** Sine, quart, quint, expo and circ (each in, out and in-out), bounce in and in-out, and smoothstep and smootherstep join the quad, cubic, back, elastic and out-bounce curves. They are new `EasingType` members after the existing ones, so a saved tween keeps its curve, and they ease the same in a C++ tween and a script value tween.
- **World content has a rectangle: `ContentRect`.** A size and the pivot the entity's transform sits on, which the `Sprite` and `Text` on the entity follow and which a `UIMask` on it clips to — no `UINode` needed, so a clipping region or a scroll viewport can stand in the world. `contentRectContains` tests a world point against it.
+- **Text can underline, and a box can grow to its text.** `Text.underline` draws a bar under each line, taken from the font's own underscore. `TextOverflow.ResizeHeight` keeps every line and sets the entity's `ContentRect` height to the height they take, so what sits below a paragraph can follow it.
- **An emitter runs on its own clock.** `ParticleEmitter.simulationSpeed` scales how fast that emitter's time runs: 2 plays it twice as fast, 0.5 at half, 0 holds it. Emission, lifetimes and motion all follow it. The default, 1, is the behaviour before.
- **An animator state can play at the speed of a parameter.** `speedParameter` on an `AnimatorState` names a float parameter; the state's clock advances by `dt` times its value, so a run clip follows a character's speed and a value of 0 holds the pose. It applies to every kind of motion, since it is the state's own clock that is scaled.
- **Particles can carry an added velocity and be held to a speed limit.** `ParticleEmitter.addedVelocityMin` and `addedVelocityMax` give each particle a velocity on top of its own, chosen between the two when it is born and untouched by gravity, damping and noise. `speedLimit` pulls a faster particle back toward the limit, by `limitDampen` of the excess every 1/60 s so the braking does not depend on the frame rate. Both are run by the CPU simulation.
diff --git a/docs/astro/src/content/docs/ui/text.mdx b/docs/astro/src/content/docs/ui/text.mdx
index f87ffebce..22e27c312 100644
--- a/docs/astro/src/content/docs/ui/text.mdx
+++ b/docs/astro/src/content/docs/ui/text.mdx
@@ -80,7 +80,8 @@ Defaults below are the component defaults (what the inspector shows).
| `align` | `TextAlign` | `Left` | Horizontal alignment: `Left` / `Center` / `Right`. |
| `verticalAlign` | `TextVerticalAlign` | `Top` | Vertical alignment: `Top` / `Middle` / `Bottom`. |
| `wordWrap` | boolean | `true` | Wrap lines at the box width (needs a box: a `UINode`, or the `Text`'s own `boxWidth`). |
-| `overflow` | `TextOverflow` | `Visible` | What text too big for its box does (needs a box): `Visible` keeps it all; `Clip` and `Ellipsis` drop the lines past the box height and trim a line past its width; `Shrink` sets the type smaller, a whole pixel at a time, until it fits both (line height and letter spacing shrink with it, down to 1px). |
+| `overflow` | `TextOverflow` | `Visible` | What text too big for its box does (needs a box): `Visible` keeps it all; `Clip` and `Ellipsis` drop the lines past the box height and trim a line past its width; `Shrink` sets the type smaller, a whole pixel at a time, until it fits both (line height and letter spacing shrink with it, down to 1px); `ResizeHeight` keeps every line and grows the entity's `ContentRect` to the height they take. |
+| `underline` | boolean | `false` | A bar under each line, cut from the font's own underscore so its thickness and depth are the font's. |
| `boxWidth` / `boxHeight` | number | `0` | The layout box of a `Text` with **no** `UINode`, in px. `0` means no box (the entity origin is the box). With a box, alignment, wrapping and overflow work inside it while the text stays world content, sorted by `layer`. A `UINode`, when present, decides the box instead. |
| `boxPivot` | Vec2 | `(0.5, 0.5)` | Where the entity origin sits in that box, as a fraction from its left and bottom edges: `(0.5, 0.5)` is the centre, `(0, 1)` the top-left corner. It is the anchor point of a Cocos or Unity rect transform. |
| `lineHeight` | number | `1.2` | Line spacing as a **ratio of `fontSize`** (baseline-to-baseline = `lineHeight × fontSize`). |
diff --git a/docs/astro/src/content/docs/zh-cn/ui/text.mdx b/docs/astro/src/content/docs/zh-cn/ui/text.mdx
index 1eea0f09a..00cc3b812 100644
--- a/docs/astro/src/content/docs/zh-cn/ui/text.mdx
+++ b/docs/astro/src/content/docs/zh-cn/ui/text.mdx
@@ -74,7 +74,8 @@ const pulseBanner = defineSystem([Query(Mut(Transform), Text), Res(Time)], (q, t
| `align` | `TextAlign` | `Left` | 水平对齐:`Left` / `Center` / `Right`。 |
| `verticalAlign` | `TextVerticalAlign` | `Top` | 垂直对齐:`Top` / `Middle` / `Bottom`。 |
| `wordWrap` | boolean | `true` | 按盒宽换行(需要盒:`UINode`,或 `Text` 自己的 `boxWidth`)。 |
-| `overflow` | `TextOverflow` | `Visible` | 文本超出盒时怎么办(需要盒):`Visible` 全部保留;`Clip` 和 `Ellipsis` 丢弃超出盒高的行、截断超出盒宽的行;`Shrink` 把字一个像素一个像素地缩小,直到放进盒里(行高和字距随之缩小,最小 1px)。 |
+| `overflow` | `TextOverflow` | `Visible` | 文本超出盒时怎么办(需要盒):`Visible` 全部保留;`Clip` 和 `Ellipsis` 丢弃超出盒高的行、截断超出盒宽的行;`Shrink` 把字一个像素一个像素地缩小,直到放进盒里(行高和字距随之缩小,最小 1px);`ResizeHeight` 保留所有行,并把实体的 `ContentRect` 高度撑到这些行的总高。 |
+| `underline` | boolean | `false` | 每行文字下面画一条线,取自字体自己的下划线字形,所以粗细和位置是字体的。 |
| `boxWidth` / `boxHeight` | number | `0` | **没有** `UINode` 的 `Text` 的排版盒,单位 px。`0` 表示没有盒(实体原点就是盒)。有盒时对齐、换行、溢出都在盒内工作,而文本仍是世界内容,按 `layer` 排序。存在 `UINode` 时由它决定盒。 |
| `boxPivot` | Vec2 | `(0.5, 0.5)` | 实体原点在这个盒里的位置,按距盒左边、下边的比例:`(0.5, 0.5)` 是中心,`(0, 1)` 是左上角。相当于 Cocos / Unity 矩形变换的锚点。 |
| `lineHeight` | number | `1.2` | 行距,为 **`fontSize` 的比率**(基线间距 = `lineHeight × fontSize`)。 |
diff --git a/pipeline/src/import/cocos/components.ts b/pipeline/src/import/cocos/components.ts
index 6b79e4db2..d143a1be1 100644
--- a/pipeline/src/import/cocos/components.ts
+++ b/pipeline/src/import/cocos/components.ts
@@ -231,7 +231,7 @@ function label(c: CocosComponent, siblings: CocosComponent[], box: UiBox | null,
align: clamp012(d._horizontalAlign),
verticalAlign: clamp012(d._verticalAlign),
wordWrap: d._enableWrapText !== false,
- overflow: overflow === 1 ? 1 : overflow === 2 ? 3 : 0, // Clip, Shrink, otherwise Visible
+ overflow: overflow === 1 ? 1 : overflow === 2 ? 3 : overflow === 3 ? 4 : 0, // Clip, Shrink, ResizeHeight, otherwise Visible
lineHeight: fontSize > 0 ? Math.round((lineHeight / fontSize) * 1000) / 1000 : 1.2,
bold: d._isBold === true,
italic: d._isItalic === true,
@@ -243,11 +243,6 @@ function label(c: CocosComponent, siblings: CocosComponent[], box: UiBox | null,
data.boxHeight = box.height;
data.boxPivot = { x: box.ax, y: box.ay };
}
- if (overflow === 3) {
- status = 'partial';
- ctx.report.note('label-resize-height', where);
- }
-
const fontUuid = uuidOf(d._font);
if (d._isSystemFontUsed === false && fontUuid) {
const font = ctx.assets.byUuid.get(fontUuid);
@@ -265,10 +260,7 @@ function label(c: CocosComponent, siblings: CocosComponent[], box: UiBox | null,
} else if (typeof d._fontFamily === 'string') {
data.fontFamily = d._fontFamily;
}
- if (d._isUnderline === true) {
- status = 'partial';
- ctx.report.note('label-underline', where);
- }
+ if (d._isUnderline === true) data.underline = true;
const outline = siblings.find((s) => s.type === 'cc.LabelOutline' && s.enabled);
if (outline) {
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 29c9be289..0b82f341e 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -10819,6 +10819,7 @@ shadowOffsetX: number
shadowOffsetY: number
strokeColor: Color
strokeWidth: number
+underline: boolean | undefined
verticalAlign: TextVerticalAlign
wordWrap: boolean
```
@@ -10849,6 +10850,7 @@ shadowOffsetX: number | undefined
shadowOffsetY: number | undefined
strokeColor: Color | undefined
strokeWidth: number | undefined
+underline: boolean | undefined
verticalAlign: TextVerticalAlign | undefined
wordWrap: boolean | undefined
```
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index a5f94f087..4ca16ee84 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -11032,6 +11032,7 @@ shadowOffsetX: number
shadowOffsetY: number
strokeColor: Color
strokeWidth: number
+underline: boolean | undefined
verticalAlign: TextVerticalAlign
wordWrap: boolean
```
@@ -11062,6 +11063,7 @@ shadowOffsetX: number | undefined
shadowOffsetY: number | undefined
strokeColor: Color | undefined
strokeWidth: number | undefined
+underline: boolean | undefined
verticalAlign: TextVerticalAlign | undefined
wordWrap: boolean | undefined
```
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 39b35ff64..3194430cb 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -10814,6 +10814,7 @@ shadowOffsetX: number
shadowOffsetY: number
strokeColor: Color
strokeWidth: number
+underline: boolean | undefined
verticalAlign: TextVerticalAlign
wordWrap: boolean
```
@@ -10844,6 +10845,7 @@ shadowOffsetX: number | undefined
shadowOffsetY: number | undefined
strokeColor: Color | undefined
strokeWidth: number | undefined
+underline: boolean | undefined
verticalAlign: TextVerticalAlign | undefined
wordWrap: boolean | undefined
```
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index d5e84ae17..4379e431b 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -11109,6 +11109,7 @@ shadowOffsetX: number
shadowOffsetY: number
strokeColor: Color
strokeWidth: number
+underline: boolean | undefined
verticalAlign: TextVerticalAlign
wordWrap: boolean
```
@@ -11139,6 +11140,7 @@ shadowOffsetX: number | undefined
shadowOffsetY: number | undefined
strokeColor: Color | undefined
strokeWidth: number | undefined
+underline: boolean | undefined
verticalAlign: TextVerticalAlign | undefined
wordWrap: boolean | undefined
```
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 4ba4aa21b..d42314197 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -10821,6 +10821,7 @@ shadowOffsetX: number
shadowOffsetY: number
strokeColor: Color
strokeWidth: number
+underline: boolean | undefined
verticalAlign: TextVerticalAlign
wordWrap: boolean
```
@@ -10851,6 +10852,7 @@ shadowOffsetX: number | undefined
shadowOffsetY: number | undefined
strokeColor: Color | undefined
strokeWidth: number | undefined
+underline: boolean | undefined
verticalAlign: TextVerticalAlign | undefined
wordWrap: boolean | undefined
```
diff --git a/sdk/src/cocos/ui/label.ts b/sdk/src/cocos/ui/label.ts
index 252bd355d..edad52e12 100644
--- a/sdk/src/cocos/ui/label.ts
+++ b/sdk/src/cocos/ui/label.ts
@@ -25,12 +25,14 @@ const CacheMode = Object.freeze({ NONE: 0, BITMAP: 1, CHAR: 2 });
function toEngineOverflow(cocos: number): number {
if (cocos === Overflow.CLAMP) return TextOverflow.Clip;
if (cocos === Overflow.SHRINK) return TextOverflow.Shrink;
- return TextOverflow.Visible; // NONE, and RESIZE_HEIGHT, which the engine has no equivalent of
+ if (cocos === Overflow.RESIZE_HEIGHT) return TextOverflow.ResizeHeight;
+ return TextOverflow.Visible;
}
function toCocosOverflow(engine: number): number {
if (engine === TextOverflow.Clip || engine === TextOverflow.Ellipsis) return Overflow.CLAMP;
if (engine === TextOverflow.Shrink) return Overflow.SHRINK;
+ if (engine === TextOverflow.ResizeHeight) return Overflow.RESIZE_HEIGHT;
return Overflow.NONE;
}
@@ -76,6 +78,9 @@ export class Label extends TextView {
get enableWrapText(): boolean { return this.text_().wordWrap; }
set enableWrapText(v: boolean) { this.patch_({ wordWrap: v }); }
+ get isUnderline(): boolean { return this.text_().underline === true; }
+ set isUnderline(v: boolean) { this.patch_({ underline: v }); }
+
get isBold(): boolean { return this.text_().bold; }
set isBold(v: boolean) { this.patch_({ bold: v }); }
get isItalic(): boolean { return this.text_().italic; }
diff --git a/sdk/src/ui/core/text.ts b/sdk/src/ui/core/text.ts
index 45668eefe..40500940f 100644
--- a/sdk/src/ui/core/text.ts
+++ b/sdk/src/ui/core/text.ts
@@ -45,6 +45,8 @@ export const TextOverflow = {
Ellipsis: 2,
/** Smaller type until the text fits the box: the size drops a whole pixel at a time, and line height and letter spacing with it. */
Shrink: 3,
+ /** Every line shows, and the box grows to hold them: the entity's `ContentRect` height becomes the text's own. */
+ ResizeHeight: 4,
} as const;
/** @public */
export type TextOverflow = (typeof TextOverflow)[keyof typeof TextOverflow];
@@ -103,6 +105,8 @@ export interface TextData {
shadowBlur: number;
shadowOffsetX: number;
shadowOffsetY: number;
+ /** A line under each line of text, in the font's own underscore. Absent is off. */
+ underline?: boolean;
richText: boolean;
renderMode: TextRenderMode;
/**
diff --git a/sdk/src/ui/text/layout.ts b/sdk/src/ui/text/layout.ts
index 05943a555..97b755f92 100644
--- a/sdk/src/ui/text/layout.ts
+++ b/sdk/src/ui/text/layout.ts
@@ -51,8 +51,17 @@ export interface LaidImage {
tint: RGBA | null;
}
+/** Where one laid-out line sits: its left edge and width, and the baseline, in the same y-up local space as the glyphs. */
+export interface LaidLine {
+ x: number;
+ width: number;
+ baseline: number;
+}
+
export interface TextLayout {
glyphs: LaidGlyph[];
+ /** Each line's extent, top to bottom. Undefined for a layout that is a single line laid out on its own. */
+ lines?: LaidLine[];
/** Inline `<img>` placements (rich text only). Undefined/empty = none. */
images?: LaidImage[];
/** Total pen advance (display px). */
@@ -416,14 +425,16 @@ export function layoutText(
// is what every layout engine does and what a reader can act on.
const overflow = opts.overflow ?? TextOverflow.Visible;
const boxHeight = opts.boxHeight ?? 0;
- const maxLines = overflow !== TextOverflow.Visible && boxHeight > 0
+ // ResizeHeight keeps every line (the box grows to them) and every character (nothing is trimmed).
+ const keepsAll = overflow === TextOverflow.Visible || overflow === TextOverflow.ResizeHeight;
+ const maxLines = !keepsAll && boxHeight > 0
? Math.max(1, Math.floor(boxHeight / lineHeight))
: Infinity;
const ellipsis = overflow === TextOverflow.Ellipsis;
// The width a line may not exceed. maxWidth already wrapped to it, so this is
// for the unwrapped case — a single line in a fixed box, which is the one
// ellipsis is usually asked for.
- const widthLimit = overflow === TextOverflow.Visible ? 0
+ const widthLimit = keepsAll ? 0
: (opts.maxWidth && opts.maxWidth > 0) ? opts.maxWidth
: (opts.boxWidth ?? 0);
@@ -468,6 +479,7 @@ export function layoutText(
: contentWidth;
const glyphs: LaidGlyph[] = [];
const images: LaidImage[] = [];
+ const laidLines: LaidLine[] = [];
for (let i = 0; i < lineLayouts.length; i++) {
const ll = lineLayouts[i];
@@ -475,6 +487,7 @@ export function layoutText(
: align === TEXT_ALIGN_RIGHT ? (alignWidth - ll.width)
: 0;
const dy = -i * lineHeight; // y-up: first line on top
+ laidLines.push({ x: dx, width: ll.width, baseline: dy });
for (const g of ll.glyphs) {
glyphs.push({ ...g, x0: g.x0 + dx, x1: g.x1 + dx, y0: g.y0 + dy, y1: g.y1 + dy });
}
@@ -483,7 +496,7 @@ export function layoutText(
}
}
- return { glyphs, images, width: contentWidth, lineHeight: lines.length * lineHeight };
+ return { glyphs, images, lines: laidLines, width: contentWidth, lineHeight: lines.length * lineHeight };
}
/**
diff --git a/sdk/src/ui/text/plugin.ts b/sdk/src/ui/text/plugin.ts
index a56f3d021..14755f402 100644
--- a/sdk/src/ui/text/plugin.ts
+++ b/sdk/src/ui/text/plugin.ts
@@ -19,7 +19,8 @@ import type { World } from '../../ecs/world';
import { SdfTextRenderer } from './text-renderer';
import type { RGBA } from './layout';
import { composeTRS, DEFAULT_ASCENT, rectTextBox, UI_TEXT_BOLD, UI_TEXT_ITALIC } from './text-transform';
-import { Text, TextRenderMode, type TextData } from '../core/text';
+import { Text, TextOverflow, TextRenderMode, type TextData } from '../core/text';
+import { ContentRect } from '../core/content-rect';
import { bitmapFontOf, fontAscent } from './bitmap-font';
import { UINode } from '../core/ui-node';
import { Localization } from '../../i18n/Localization';
@@ -106,7 +107,7 @@ export function textFrame(world: World, entity: Entity, t: TextData): TextFrame
/** The Text fields a retained label's geometry was laid out from; a label is rebuilt when any of them differs, and not otherwise. */
export interface TextSnapshot {
content: string; family: string; fontSize: number; bold: boolean; italic: boolean; richText: boolean; renderMode: number;
- align: number; verticalAlign: number; wordWrap: boolean; overflow: number; lineHeight: number; layer: number;
+ align: number; verticalAlign: number; wordWrap: boolean; overflow: number; lineHeight: number; layer: number; underline: boolean;
boxW: number; boxH: number; boxPx: number; boxPy: number;
cr: number; cg: number; cb: number; ca: number;
strokeWidth: number; sr: number; sg: number; sb: number; sa: number;
@@ -124,7 +125,7 @@ interface RetainedLabel {
export function snapshotOf(t: TextData, family: string): TextSnapshot {
return {
content: t.content, family, fontSize: t.fontSize, bold: !!t.bold, italic: !!t.italic, richText: !!t.richText, renderMode: t.renderMode,
- align: t.align, verticalAlign: t.verticalAlign, wordWrap: !!t.wordWrap, overflow: t.overflow, lineHeight: t.lineHeight, layer: t.layer | 0,
+ align: t.align, verticalAlign: t.verticalAlign, wordWrap: !!t.wordWrap, overflow: t.overflow, lineHeight: t.lineHeight, layer: t.layer | 0, underline: !!t.underline,
boxW: t.boxWidth || 0, boxH: t.boxHeight || 0, boxPx: t.boxPivot?.x ?? 0.5, boxPy: t.boxPivot?.y ?? 0.5,
cr: t.color.r, cg: t.color.g, cb: t.color.b, ca: t.color.a,
strokeWidth: t.strokeWidth, sr: t.strokeColor.r, sg: t.strokeColor.g, sb: t.strokeColor.b, sa: t.strokeColor.a,
@@ -137,7 +138,7 @@ export function sameSnapshot(s: TextSnapshot, t: TextData, family: string): bool
return s.content === t.content && s.family === family && s.fontSize === t.fontSize
&& s.bold === !!t.bold && s.italic === !!t.italic && s.richText === !!t.richText && s.renderMode === t.renderMode
&& s.align === t.align && s.verticalAlign === t.verticalAlign && s.wordWrap === !!t.wordWrap
- && s.overflow === t.overflow && s.lineHeight === t.lineHeight && s.layer === (t.layer | 0)
+ && s.overflow === t.overflow && s.lineHeight === t.lineHeight && s.layer === (t.layer | 0) && s.underline === !!t.underline
&& s.boxW === (t.boxWidth || 0) && s.boxH === (t.boxHeight || 0) && s.boxPx === (t.boxPivot?.x ?? 0.5) && s.boxPy === (t.boxPivot?.y ?? 0.5)
&& s.cr === t.color.r && s.cg === t.color.g && s.cb === t.color.b && s.ca === t.color.a
&& s.strokeWidth === t.strokeWidth
@@ -421,7 +422,7 @@ export class TextPlugin implements Plugin {
width: t.strokeWidth,
}
: undefined;
- renderer.retain(
+ const blockHeight = renderer.retain(
api,
{
text: t.content,
@@ -437,6 +438,7 @@ export class TextPlugin implements Plugin {
boxWidth,
boxHeight,
overflow: t.overflow,
+ underline: !!t.underline,
originX,
originY,
shadow,
@@ -448,6 +450,12 @@ export class TextPlugin implements Plugin {
t.renderMode !== TextRenderMode.Bitmap && t.renderMode !== TextRenderMode.Sdf && !bitmapFontOf(family),
);
appState.retained.set(entity as number, { snap: snapshotOf(t, family), screen, gen: renderer.atlas.generation, renderer });
+ // A box that grows to its text: the rectangle the entity occupies takes the height the lines laid out to. The sprite and text follow the
+ // rectangle on the next frame, where the box is the same height and nothing changes again.
+ if (t.overflow === TextOverflow.ResizeHeight && blockHeight > 0) {
+ const rect = world.tryGet(entity, ContentRect);
+ if (rect && Math.abs(rect.size.y - blockHeight) > 0.5) world.set(entity, ContentRect, { ...rect, size: { x: rect.size.x, y: blockHeight } });
+ }
}
private drawDomainWithMatrix(app: App, screen: boolean, readMatrix?: (entity: number) => boolean, projection?: Float32Array): void {
diff --git a/sdk/src/ui/text/text-renderer.ts b/sdk/src/ui/text/text-renderer.ts
index 1ee32aae8..7bf044ca7 100644
--- a/sdk/src/ui/text/text-renderer.ts
+++ b/sdk/src/ui/text/text-renderer.ts
@@ -18,7 +18,7 @@ import { CanvasGlyphRasterizer, type CanvasGlyphRasterizerOptions } from './glyp
import { NativeGlyphRasterizer } from './native-glyph-rasterizer';
import { EngineAtlasPageStore } from './atlas-page-store';
import { TextAlign, TextVerticalAlign, TextOverflow } from '../core/text';
-import { layoutText, buildGlyphVertices, MAX_TEXT_BATCH_GLYPHS, type LaidGlyph, type RGBA } from './layout';
+import { layoutText, buildGlyphVertices, MAX_TEXT_BATCH_GLYPHS, type LaidGlyph, type RGBA, type TextLayout } from './layout';
import { submitTextBatch, TEXT_VERTEX_FLOATS, TextGlyphMode } from './submit';
import { bitmapFontOf, fontAscent } from './bitmap-font';
import { DEFAULT_ASCENT } from './text-transform';
@@ -58,6 +58,8 @@ export interface DrawTextParams {
boxHeight?: number;
/** What a run too big for the box does. */
overflow?: TextOverflow;
+ /** A bar under each line. */
+ underline?: boolean;
/**
* Drop shadow: an offset, recolored copy of the glyphs drawn behind the fill.
* `blur` (px, 0 = hard) spreads that copy into a ring so the shadow reads as
@@ -178,10 +180,32 @@ export function textBlockOriginY(
* Lay out text against the atlas and emit index-safe quad batches to the sink.
* Pure given the atlas, so grouping and geometry are unit-testable.
*/
-export function drawTextWith(atlas: GlyphAtlas, sink: GlyphBatchSink, p: DrawTextParams): void {
+/**
+ * Draw a bar under each line. The font has no underline to ask for, but it has an underscore: its middle is a bar of the font's own thickness
+ * and depth below the baseline, and a glyph quad can be stretched across the line along that middle (the distance field is flat there).
+ */
+function addUnderlines(layout: TextLayout, atlas: GlyphAtlas, fontFamily: string, fontSizePx: number, style: number): void {
+ if (!layout.lines || layout.lines.length === 0) return;
+ const pixelSize = atlas.pixelSizeFor(fontSizePx, fontFamily);
+ const g = atlas.getGlyph(0x5f, fontFamily, style, pixelSize);
+ if (!g || g.width <= 0 || g.height <= 0) return;
+ const scale = fontSizePx / pixelSize;
+ const span = g.u1 - g.u0;
+ const u0 = g.u0 + span * 0.4, u1 = g.u0 + span * 0.6;
+ const top = g.bearingY * scale, bottom = top - g.height * scale;
+ for (const line of layout.lines) {
+ if (line.width <= 0) continue;
+ layout.glyphs.push({
+ u0, v0: g.v0, u1, v1: g.v1,
+ x0: line.x, x1: line.x + line.width, y0: line.baseline + bottom, y1: line.baseline + top, pageId: g.pageId,
+ });
+ }
+}
+
+export function drawTextWith(atlas: GlyphAtlas, sink: GlyphBatchSink, p: DrawTextParams): number {
if (atlas.metricsOnly) throw new Error('Measurement atlases cannot submit text.');
const opacity = p.opacity ?? 1;
- if (opacity <= 0) return;
+ if (opacity <= 0) return 0;
const layout = layoutText(p.text, atlas, p.fontFamily, {
fontSizePx: p.fontSizePx,
letterSpacing: p.letterSpacing,
@@ -194,7 +218,8 @@ export function drawTextWith(atlas: GlyphAtlas, sink: GlyphBatchSink, p: DrawTex
boxHeight: p.boxHeight,
overflow: p.overflow,
}, p.style ?? 0);
- if (layout.glyphs.length === 0) return;
+ if (layout.glyphs.length === 0) return layout.lineHeight;
+ if (p.underline) addUnderlines(layout, atlas, p.fontFamily, layout.fontSizePx ?? p.fontSizePx, p.style ?? 0);
// Position the block within its box: [originX .. originX+boxWidth] × [originY .. -boxHeight].
// A boxless label (box 0×0) collapses the box to the entity origin, so align/verticalAlign
@@ -278,6 +303,7 @@ export function drawTextWith(atlas: GlyphAtlas, sink: GlyphBatchSink, p: DrawTex
}
// Fill (on top).
emitPass(p.color, 0, 0, 0, true, baked ? TextGlyphMode.Fill : undefined);
+ return layout.lineHeight;
}
export interface TextRendererOptions extends CanvasGlyphRasterizerOptions {
@@ -424,10 +450,10 @@ export class SdfTextRenderer {
retain(
api: EngineApi, p: DrawTextParams, entity: number,
screen: boolean, hasBox: boolean, layer: number, boxWidth: number, boxHeight: number, autoKind: boolean,
- ): void {
+ ): number {
if (this.atlas.metricsOnly) throw new Error('Measurement atlases cannot submit text.');
const batches: Array<{ vertices: Float32Array; indices: Uint16Array; pageId: number; mode?: TextGlyphMode }> = [];
- drawTextWith(this.atlas, (vertices, indices, pageId, mode) => {
+ const blockHeight = drawTextWith(this.atlas, (vertices, indices, pageId, mode) => {
batches.push({ vertices, indices, pageId, ...(mode !== undefined ? { mode } : {}) });
}, { ...p, opacity: 1 });
api.renderer_retainedTextBegin!(entity, this.sdf ? 1 : 0, screen ? 1 : 0, hasBox ? 1 : 0, layer, boxWidth, boxHeight, autoKind ? 1 : 0);
@@ -447,6 +473,7 @@ export class SdfTextRenderer {
this.retainedPages_.set(entity, batches.map(b => b.pageId));
this.drawn_.add(entity);
this.cache_.delete(entity);
+ return blockHeight;
}
/** A retained label that is not rebuilt this frame is still on screen: its atlas pages must stay. */
@@ -483,7 +510,7 @@ function textSignature(p: DrawTextParams, opacity: number): string {
p.richText ? 1 : 0, p.align ?? 0, p.verticalAlign ?? 0,
p.lineHeight ?? 0, p.letterSpacing ?? 0,
p.maxWidth ?? 0, p.boxWidth ?? 0, p.boxHeight ?? 0,
- p.overflow ?? TextOverflow.Visible,
+ p.overflow ?? TextOverflow.Visible, p.underline ? 1 : 0,
p.originX ?? 0, p.originY ?? 0,
p.color.join(','), opacity, shadow, outline,
]);
diff --git a/sdk/tests/cocos/ui-adapters-wasm.test.ts b/sdk/tests/cocos/ui-adapters-wasm.test.ts
index 884584c86..bde1334f9 100644
--- a/sdk/tests/cocos/ui-adapters-wasm.test.ts
+++ b/sdk/tests/cocos/ui-adapters-wasm.test.ts
@@ -114,8 +114,12 @@ describe.skipIf(!HAS_WASM)('built-in UI components on the engine', () => {
expect(label.overflow).toBe(Label.Overflow.SHRINK);
label.overflow = Label.Overflow.CLAMP;
expect(W().get(n._entity, Text).overflow).toBe(TextOverflow.Clip);
- label.overflow = Label.Overflow.RESIZE_HEIGHT; // no engine counterpart: draws whole
- expect(W().get(n._entity, Text).overflow).toBe(TextOverflow.Visible);
+ label.overflow = Label.Overflow.RESIZE_HEIGHT;
+ expect(W().get(n._entity, Text).overflow).toBe(TextOverflow.ResizeHeight);
+ expect(label.overflow).toBe(Label.Overflow.RESIZE_HEIGHT);
+ label.isUnderline = true;
+ expect(W().get(n._entity, Text).underline).toBe(true);
+ expect(label.isUnderline).toBe(true);
label.horizontalAlign = Label.HorizontalAlign.RIGHT;
label.verticalAlign = Label.VerticalAlign.BOTTOM;
const t = W().get(n._entity, Text);
diff --git a/sdk/tests/ui-text-overflow.test.ts b/sdk/tests/ui-text-overflow.test.ts
index 461fcee8d..039f07ffa 100644
--- a/sdk/tests/ui-text-overflow.test.ts
+++ b/sdk/tests/ui-text-overflow.test.ts
@@ -12,6 +12,7 @@ import {
GlyphAtlas, type GlyphRasterizer, type AtlasPageStore, type RasterGlyph,
} from '../src/ui/text/glyph-atlas';
import { layoutText, measureWidth, shrinkFontSize } from '../src/ui/text/layout';
+import { drawTextWith } from '../src/ui/text/text-renderer';
import { TextOverflow } from '../src/ui/core/text';
function makeAtlas(): GlyphAtlas {
@@ -208,3 +209,49 @@ describe('TextOverflow.Shrink', () => {
expect(l.glyphs.length).toBeGreaterThan(0);
});
});
+
+describe('TextOverflow.ResizeHeight', () => {
+ it('keeps every line however short the box, and reports the height of all of them', () => {
+ const l = lay('one\ntwo\nthree', { boxHeight: LINE, overflow: TextOverflow.ResizeHeight });
+ expect(linesOf(l)).toBe(3);
+ expect(l.lineHeight).toBeCloseTo(3 * LINE, 6);
+ });
+
+ it('does not trim a line that is wider than the box', () => {
+ const l = lay('a long line of text', { boxWidth: 20, overflow: TextOverflow.ResizeHeight });
+ expect(l.width).toBeCloseTo(width('a long line of text'), 6);
+ });
+
+ it('grows with wrapping: a narrower wrap width makes the block taller', () => {
+ const wide = lay('one two three four five six', { maxWidth: 400, overflow: TextOverflow.ResizeHeight });
+ const narrow = lay('one two three four five six', { maxWidth: 60, overflow: TextOverflow.ResizeHeight });
+ expect(narrow.lineHeight).toBeGreaterThan(wide.lineHeight);
+ });
+});
+
+describe('a laid-out line', () => {
+ it('says where it sits: its left edge, its width, and its baseline', () => {
+ const l = lay('ab\ncd', { align: 1, boxWidth: 100 });
+ expect(l.lines).toHaveLength(2);
+ expect(l.lines![0]!.baseline).toBeCloseTo(0, 6);
+ expect(l.lines![1]!.baseline).toBeCloseTo(-LINE, 6);
+ expect(l.lines![0]!.x).toBeCloseTo((100 - l.lines![0]!.width) / 2, 6);
+ });
+});
+
+describe('underline', () => {
+ const quads = (underline: boolean) => {
+ const out: number[] = [];
+ drawTextWith(atlas, (vertices) => { out.push(vertices.length); }, {
+ text: 'ab\ncd', fontFamily: 'Arial', fontSizePx: F, color: [1, 1, 1, 1], lineHeight: LINE, underline,
+ });
+ return out.reduce((a, b) => a + b, 0);
+ };
+
+ it('adds one bar to each line', () => {
+ const without = quads(false);
+ const withBars = quads(true);
+ // four glyphs and two bars, against four glyphs: the vertex data grows by one third
+ expect(withBars).toBeCloseTo(without * 6 / 4, 6);
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 2034016cf..5222436f9 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';
* the reader recognises anyway.
*/
export const NOTED = {
+ 'feat(text): Text can underline its lines and grow its box to its text (ResizeHeight), and the Cocos Label maps onto both':
+ {"note":"Text can underline, and a box can grow to its text."},
'feat(cocos): a project effect is judged by its fragment stage and the features a material switches on, and a sprite-stencil mask maps to the engine stencil mask':
{"internal":"The Cocos Creator compatibility layer and importer have not shipped; nothing a creator reaches without opting in."},
'feat(particle): an emitter has its own simulation speed, and the Cocos simulation speed, noise, trail and burst time map onto the emitter':