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.

fix(cocos): a texture that keeps its colour under a clear alpha holds numbers, and is imported uncompressed and not as sRGB, so a terrain's weight map reaches its shader as it was painted

yhh7e0e48af217f
diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.ts
index 42b0bcf01..586cbbde0 100644
--- a/pipeline/src/import/cocos/importProject.ts
+++ b/pipeline/src/import/cocos/importProject.ts
@@ -9,6 +9,7 @@
* other. Only what the converted documents reference is copied.
*/
import { createHash } from 'node:crypto';
+import { decodePngImage } from '../../assets/atlasPacker';
import { copyFileSync, existsSync, linkSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
@@ -31,7 +32,7 @@ import { convertPass, isOutlinePass, type PassConversion } from './effectConvert
* importer that made less (or differently), and is brought up to date when it is opened. Raise it when the converted output changes in a
* way an existing project needs to pick up: a new generated file, a field a document or a manifest now carries.
*/
-export const COCOS_IMPORT_REVISION = 18;
+export const COCOS_IMPORT_REVISION = 19;
/** Whether the project at @p projectRoot was written by an importer of this revision. A project that was not converted has nothing to bring up. */
export function cocosImportIsCurrent(projectRoot: string): boolean {
@@ -89,6 +90,32 @@ function withoutDerivedTwin(source: string): string {
.replace(/\n?#pragma vertexoffset wgsl\n\/\/ GENERATED[\s\S]*?#pragma end\n?/g, '\n');
}
+/**
+ * Whether a PNG keeps its colour under a clear alpha: most of its texels are clear and carry colour all the same. That is a texture that holds numbers in
+ * its channels (a weight map the ground is mixed by), not a picture, and compressing it, or reading its colour as sRGB, wrecks it: a cook that encodes a
+ * texture is free to forget what is under alpha 0.
+ */
+export function hidesColorUnderClearAlpha(file: string): boolean {
+ try {
+ const bytes = readFileSync(file);
+ // IHDR: colour type 4 (grey + alpha) and 6 (RGBA) are the ones with an alpha channel
+ if (bytes.length < 26 || bytes.toString('latin1', 1, 4) !== 'PNG' || (bytes[25] !== 4 && bytes[25] !== 6)) return false;
+ const image = decodePngImage(file, new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength));
+ let clear = 0, coloured = 0;
+ const step = Math.max(1, Math.floor(image.rgba.length / 4 / 65536));
+ let sampled = 0;
+ for (let i = 0; i < image.rgba.length; i += 4 * step) {
+ sampled++;
+ if (image.rgba[i + 3]! !== 0) continue;
+ clear++;
+ if (image.rgba[i]! + image.rgba[i + 1]! + image.rgba[i + 2]! > 0) coloured++;
+ }
+ return sampled > 0 && clear / sampled > 0.5 && coloured / sampled > 0.1;
+ } catch {
+ return false;
+ }
+}
+
function writeOut(file: string, text: string): void {
mkdirSync(path.dirname(file), { recursive: true });
writeFileSync(file, text);
@@ -1071,9 +1098,12 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Impo
writeOut(`${dest}.meta`, `${JSON.stringify({ uuid: entry.uuid, version: '2.0', type: 'bitmapfont', importer: {} }, null, 2)}
`);
}
- if (slice) {
- // A slice border is a texture import setting here; the Cocos image keeps its uuid.
- writeOut(`${dest}.meta`, `${JSON.stringify({ uuid: entry.uuid, version: '2.0', type: 'texture', importer: { sliceBorder: slice } }, null, 2)}\n`);
+ const data = dest.endsWith('.png') && hidesColorUnderClearAlpha(entry.file);
+ if (slice || data) {
+ // A slice border is a texture import setting here; the Cocos image keeps its uuid. A texture that holds numbers is shipped as the numbers it has.
+ const importer = { ...(slice ? { sliceBorder: slice } : {}), ...(data ? { compress: 'off', sRGB: false } : {}) };
+ writeOut(`${dest}.meta`, `${JSON.stringify({ uuid: entry.uuid, version: '2.0', type: 'texture', importer }, null, 2)}\n`);
+ if (data) report.note('texture-kept-as-data', entry.rel);
}
}
// The shaders and materials of an earlier import that this one did not write are the effects' own leftovers (a combination of macros no material
diff --git a/pipeline/tests/cocos-import-data-texture.test.ts b/pipeline/tests/cocos-import-data-texture.test.ts
new file mode 100644
index 000000000..baecb86ed
--- /dev/null
+++ b/pipeline/tests/cocos-import-data-texture.test.ts
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A PNG that keeps its colour under a clear alpha holds numbers (a weight map), and is told apart from a picture so it ships as it is.
+ */
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { encodeRgbaPng } from '../src/assets/atlasPacker';
+import { hidesColorUnderClearAlpha } from '../src/import/cocos/importProject';
+
+describe('a PNG that hides colour under a clear alpha', () => {
+ let dir: string;
+ const png = (name: string, texel: (i: number) => [number, number, number, number], width = 16, height = 16): string => {
+ const rgba = new Uint8Array(width * height * 4);
+ for (let i = 0; i < width * height; i++) rgba.set(texel(i), i * 4);
+ const file = path.join(dir, name);
+ writeFileSync(file, encodeRgbaPng(width, height, rgba));
+ return file;
+ };
+ beforeAll(() => { dir = mkdtempSync(path.join(tmpdir(), 'cocos-data-texture-')); });
+ afterAll(() => rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));
+
+ it('is a weight map: clear everywhere, with colour in every texel', () => {
+ expect(hidesColorUnderClearAlpha(png('weights.png', (i) => (i % 2 ? [255, 0, 0, 0] : [0, 0, 255, 0])))).toBe(true);
+ });
+
+ it('is not a picture: opaque, or clear with nothing under it', () => {
+ expect(hidesColorUnderClearAlpha(png('opaque.png', () => [200, 120, 40, 255]))).toBe(false);
+ expect(hidesColorUnderClearAlpha(png('empty.png', () => [0, 0, 0, 0]))).toBe(false);
+ });
+
+ it('is not a cutout: a few clear texels around a solid shape', () => {
+ expect(hidesColorUnderClearAlpha(png('sprite.png', (i) => (i < 40 ? [0, 0, 0, 0] : [200, 120, 40, 255])))).toBe(false);
+ });
+
+ it('is not one when the file is not a PNG, or is missing', () => {
+ const jpg = path.join(dir, 'x.png');
+ writeFileSync(jpg, Buffer.from('not a png at all, not even close to one'));
+ expect(hidesColorUnderClearAlpha(jpg)).toBe(false);
+ expect(hidesColorUnderClearAlpha(path.join(dir, 'nowhere.png'))).toBe(false);
+ });
+});